summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAlex Perovich <alperovi@microsoft.com>2017-02-22 15:23:44 -0800
committerAlex Perovich <alperovi@microsoft.com>2017-02-23 13:43:32 -0800
commitea9bee5ac2f96a1ea6b202dc4094b8d418d9209c (patch)
tree6ed2957084ed081ff2fce06d26d748b37b30165f
parent2ace58ac2bba14ffd469ecb89f972b8e9b8fd61d (diff)
downloadcoreclr-ea9bee5ac2f96a1ea6b202dc4094b8d418d9209c.tar.gz
coreclr-ea9bee5ac2f96a1ea6b202dc4094b8d418d9209c.tar.bz2
coreclr-ea9bee5ac2f96a1ea6b202dc4094b8d418d9209c.zip
Run codeformatter on S.P.CoreLib sources
-rw-r--r--src/mscorlib/Common/PinnableBufferCache.cs34
-rw-r--r--src/mscorlib/Common/Preprocessed/AssemblyRefs.g.cs18
-rw-r--r--src/mscorlib/corefx/Interop/Windows/NtDll/Interop.ZeroMemory.cs1
-rw-r--r--src/mscorlib/corefx/Interop/Windows/kernel32/Interop.FileOperations.cs1
-rw-r--r--src/mscorlib/corefx/Interop/Windows/kernel32/Interop.GetFileInformationByHandleEx.cs1
-rw-r--r--src/mscorlib/corefx/Interop/Windows/kernel32/Interop.GetLongPathNameW.cs4
-rw-r--r--src/mscorlib/corefx/Interop/Windows/kernel32/Interop.GetTempFileNameW.cs4
-rw-r--r--src/mscorlib/corefx/Interop/Windows/kernel32/Interop.GetTempPathW.cs4
-rw-r--r--src/mscorlib/corefx/Interop/Windows/kernel32/Interop.WideCharToMultiByte.cs6
-rw-r--r--src/mscorlib/corefx/Interop/Windows/kernel32/Interop.WriteFile_SafeHandle_IntPtr.cs1
-rw-r--r--src/mscorlib/corefx/System/Buffers/Utilities.cs8
-rw-r--r--src/mscorlib/corefx/System/IO/FileStream.Win32.cs6
-rw-r--r--src/mscorlib/corefx/System/IO/FileStreamCompletionSource.Win32.cs11
-rw-r--r--src/mscorlib/corefx/System/IO/Path.Windows.cs12
-rw-r--r--src/mscorlib/corefx/System/IO/Path.cs13
-rw-r--r--src/mscorlib/corefx/System/IO/PathInternal.Windows.cs2
-rw-r--r--src/mscorlib/corefx/System/IO/PathInternal.cs5
-rw-r--r--src/mscorlib/corefx/System/Security/SecureString.Windows.cs3
-rw-r--r--src/mscorlib/src/Internal/Runtime/Augments/RuntimeThread.cs2
-rw-r--r--src/mscorlib/src/Microsoft/Win32/OAVariantLib.cs43
-rw-r--r--src/mscorlib/src/Microsoft/Win32/Registry.cs90
-rw-r--r--src/mscorlib/src/Microsoft/Win32/RegistryKey.cs888
-rw-r--r--src/mscorlib/src/Microsoft/Win32/RegistryValueKind.cs22
-rw-r--r--src/mscorlib/src/Microsoft/Win32/RegistryView.cs17
-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.cs27
-rw-r--r--src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeWaitHandle.cs4
-rw-r--r--src/mscorlib/src/Microsoft/Win32/SafeHandles/Win32SafeHandles.cs30
-rw-r--r--src/mscorlib/src/Microsoft/Win32/UnsafeNativeMethods.cs26
-rw-r--r--src/mscorlib/src/Microsoft/Win32/Win32Native.cs495
-rw-r--r--src/mscorlib/src/System/Action.cs20
-rw-r--r--src/mscorlib/src/System/Activator.cs113
-rw-r--r--src/mscorlib/src/System/AggregateException.cs9
-rw-r--r--src/mscorlib/src/System/AppContext/AppContext.cs24
-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.cs348
-rw-r--r--src/mscorlib/src/System/AppDomainAttributes.cs18
-rw-r--r--src/mscorlib/src/System/AppDomainManager.cs28
-rw-r--r--src/mscorlib/src/System/AppDomainSetup.cs224
-rw-r--r--src/mscorlib/src/System/AppDomainUnloadedException.cs16
-rw-r--r--src/mscorlib/src/System/ArgIterator.cs22
-rw-r--r--src/mscorlib/src/System/ArgumentOutOfRangeException.cs87
-rw-r--r--src/mscorlib/src/System/Array.cs1042
-rw-r--r--src/mscorlib/src/System/ArraySegment.cs18
-rw-r--r--src/mscorlib/src/System/Attribute.cs172
-rw-r--r--src/mscorlib/src/System/AttributeUsageAttribute.cs44
-rw-r--r--src/mscorlib/src/System/BCLDebug.cs195
-rw-r--r--src/mscorlib/src/System/BadImageFormatException.cs71
-rw-r--r--src/mscorlib/src/System/BitConverter.cs277
-rw-r--r--src/mscorlib/src/System/Boolean.cs332
-rw-r--r--src/mscorlib/src/System/Buffer.cs254
-rw-r--r--src/mscorlib/src/System/Byte.cs162
-rw-r--r--src/mscorlib/src/System/CLRConfig.cs4
-rw-r--r--src/mscorlib/src/System/Char.cs1081
-rw-r--r--src/mscorlib/src/System/Collections/ArrayList.cs417
-rw-r--r--src/mscorlib/src/System/Collections/CollectionBase.cs146
-rw-r--r--src/mscorlib/src/System/Collections/Comparer.cs62
-rw-r--r--src/mscorlib/src/System/Collections/CompatibleComparer.cs42
-rw-r--r--src/mscorlib/src/System/Collections/Concurrent/ConcurrentDictionary.cs6
-rw-r--r--src/mscorlib/src/System/Collections/Concurrent/ConcurrentQueue.cs2
-rw-r--r--src/mscorlib/src/System/Collections/Concurrent/ConcurrentStack.cs1
-rw-r--r--src/mscorlib/src/System/Collections/Concurrent/IProducerConsumerCollection.cs2
-rw-r--r--src/mscorlib/src/System/Collections/DictionaryEntry.cs35
-rw-r--r--src/mscorlib/src/System/Collections/EmptyReadOnlyDictionaryInternal.cs152
-rw-r--r--src/mscorlib/src/System/Collections/Generic/ArraySortHelper.cs95
-rw-r--r--src/mscorlib/src/System/Collections/Generic/Comparer.cs48
-rw-r--r--src/mscorlib/src/System/Collections/Generic/DebugView.cs124
-rw-r--r--src/mscorlib/src/System/Collections/Generic/Dictionary.cs960
-rw-r--r--src/mscorlib/src/System/Collections/Generic/EqualityComparer.cs211
-rw-r--r--src/mscorlib/src/System/Collections/Generic/ICollection.cs16
-rw-r--r--src/mscorlib/src/System/Collections/Generic/IComparer.cs8
-rw-r--r--src/mscorlib/src/System/Collections/Generic/IDictionary.cs27
-rw-r--r--src/mscorlib/src/System/Collections/Generic/IEnumerable.cs14
-rw-r--r--src/mscorlib/src/System/Collections/Generic/IEnumerator.cs15
-rw-r--r--src/mscorlib/src/System/Collections/Generic/IEqualityComparer.cs7
-rw-r--r--src/mscorlib/src/System/Collections/Generic/IList.cs22
-rw-r--r--src/mscorlib/src/System/Collections/Generic/IReadOnlyCollection.cs2
-rw-r--r--src/mscorlib/src/System/Collections/Generic/IReadOnlyDictionary.cs1
-rw-r--r--src/mscorlib/src/System/Collections/Generic/IReadOnlyList.cs2
-rw-r--r--src/mscorlib/src/System/Collections/Generic/KeyNotFoundException.cs39
-rw-r--r--src/mscorlib/src/System/Collections/Generic/KeyValuePair.cs34
-rw-r--r--src/mscorlib/src/System/Collections/Generic/List.cs669
-rw-r--r--src/mscorlib/src/System/Collections/Hashtable.cs880
-rw-r--r--src/mscorlib/src/System/Collections/ICollection.cs16
-rw-r--r--src/mscorlib/src/System/Collections/IComparer.cs11
-rw-r--r--src/mscorlib/src/System/Collections/IDictionary.cs33
-rw-r--r--src/mscorlib/src/System/Collections/IDictionaryEnumerator.cs27
-rw-r--r--src/mscorlib/src/System/Collections/IEnumerable.cs10
-rw-r--r--src/mscorlib/src/System/Collections/IEnumerator.cs17
-rw-r--r--src/mscorlib/src/System/Collections/IEqualityComparer.cs13
-rw-r--r--src/mscorlib/src/System/Collections/IHashCodeProvider.cs12
-rw-r--r--src/mscorlib/src/System/Collections/IList.cs30
-rw-r--r--src/mscorlib/src/System/Collections/IStructuralComparable.cs8
-rw-r--r--src/mscorlib/src/System/Collections/IStructuralEquatable.cs6
-rw-r--r--src/mscorlib/src/System/Collections/ListDictionaryInternal.cs370
-rw-r--r--src/mscorlib/src/System/Collections/ObjectModel/Collection.cs303
-rw-r--r--src/mscorlib/src/System/Collections/ObjectModel/KeyedCollection.cs209
-rw-r--r--src/mscorlib/src/System/Collections/ObjectModel/ReadOnlyCollection.cs196
-rw-r--r--src/mscorlib/src/System/Collections/ObjectModel/ReadOnlyDictionary.cs369
-rw-r--r--src/mscorlib/src/System/Collections/StructuralComparisons.cs64
-rw-r--r--src/mscorlib/src/System/ComponentModel/EditorBrowsableAttribute.cs2
-rw-r--r--src/mscorlib/src/System/Configuration/Assemblies/AssemblyHashAlgorithm.cs9
-rw-r--r--src/mscorlib/src/System/Configuration/Assemblies/AssemblyVersionCompatibility.cs16
-rw-r--r--src/mscorlib/src/System/Convert.cs1770
-rw-r--r--src/mscorlib/src/System/Currency.cs39
-rw-r--r--src/mscorlib/src/System/CurrentTimeZone.cs56
-rw-r--r--src/mscorlib/src/System/DBNull.cs83
-rw-r--r--src/mscorlib/src/System/DataMisalignedException.cs2
-rw-r--r--src/mscorlib/src/System/DateTime.cs897
-rw-r--r--src/mscorlib/src/System/DateTimeOffset.cs626
-rw-r--r--src/mscorlib/src/System/Decimal.cs826
-rw-r--r--src/mscorlib/src/System/DefaultBinder.cs481
-rw-r--r--src/mscorlib/src/System/Delegate.cs153
-rw-r--r--src/mscorlib/src/System/DelegateSerializationHolder.cs26
-rw-r--r--src/mscorlib/src/System/Diagnostics/Assert.cs43
-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.cs17
-rw-r--r--src/mscorlib/src/System/Diagnostics/ConditionalAttribute.cs11
-rw-r--r--src/mscorlib/src/System/Diagnostics/Contracts/Contracts.cs39
-rw-r--r--src/mscorlib/src/System/Diagnostics/Contracts/ContractsBCL.cs46
-rw-r--r--src/mscorlib/src/System/Diagnostics/Debugger.cs20
-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.cs26
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/EventDescriptor.cs18
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/EventProvider.cs18
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/EventSource.cs153
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/EventSourceException.cs6
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/EventSource_CoreCLR.cs12
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/FrameworkEventSource.cs239
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/StubEnvironment.cs4
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/ArrayTypeInfo.cs6
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/ConcurrentSet.cs6
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/DataCollector.cs110
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EnumerableTypeInfo.cs4
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventDataAttribute.cs8
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventPayload.cs14
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/FieldMetadata.cs46
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/InvokeTypeInfo.cs14
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/NameInfo.cs2
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/PropertyValue.cs6
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/SimpleTypeInfos.cs32
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingEventSource.cs21
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingEventTypes.cs4
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingMetadataCollector.cs68
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingTypeInfo.cs20
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/Winmeta.cs1
-rw-r--r--src/mscorlib/src/System/Diagnostics/ICustomDebuggerNotification.cs8
-rw-r--r--src/mscorlib/src/System/Diagnostics/LogSwitch.cs88
-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.cs201
-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.cs77
-rw-r--r--src/mscorlib/src/System/DllNotFoundException.cs36
-rw-r--r--src/mscorlib/src/System/Double.cs205
-rw-r--r--src/mscorlib/src/System/Empty.cs27
-rw-r--r--src/mscorlib/src/System/Enum.cs106
-rw-r--r--src/mscorlib/src/System/Environment.cs188
-rw-r--r--src/mscorlib/src/System/Exception.cs257
-rw-r--r--src/mscorlib/src/System/GC.cs145
-rw-r--r--src/mscorlib/src/System/Globalization/BidiCategory.cs9
-rw-r--r--src/mscorlib/src/System/Globalization/Calendar.cs233
-rw-r--r--src/mscorlib/src/System/Globalization/CalendarAlgorithmType.cs8
-rw-r--r--src/mscorlib/src/System/Globalization/CalendarData.cs172
-rw-r--r--src/mscorlib/src/System/Globalization/CalendarWeekRule.cs7
-rw-r--r--src/mscorlib/src/System/Globalization/CalendricalCalculationsHelper.cs134
-rw-r--r--src/mscorlib/src/System/Globalization/CharUnicodeInfo.cs173
-rw-r--r--src/mscorlib/src/System/Globalization/ChineseLunisolarCalendar.cs95
-rw-r--r--src/mscorlib/src/System/Globalization/CompareInfo.cs228
-rw-r--r--src/mscorlib/src/System/Globalization/CultureData.cs961
-rw-r--r--src/mscorlib/src/System/Globalization/CultureInfo.cs533
-rw-r--r--src/mscorlib/src/System/Globalization/CultureNotFoundException.cs47
-rw-r--r--src/mscorlib/src/System/Globalization/CultureTypes.cs31
-rw-r--r--src/mscorlib/src/System/Globalization/DateTimeFormat.cs451
-rw-r--r--src/mscorlib/src/System/Globalization/DateTimeFormatInfo.cs1079
-rw-r--r--src/mscorlib/src/System/Globalization/DateTimeFormatInfoScanner.cs249
-rw-r--r--src/mscorlib/src/System/Globalization/DateTimeParse.cs2515
-rw-r--r--src/mscorlib/src/System/Globalization/DateTimeStyles.cs29
-rw-r--r--src/mscorlib/src/System/Globalization/DaylightTime.cs27
-rw-r--r--src/mscorlib/src/System/Globalization/DigitShapes.cs14
-rw-r--r--src/mscorlib/src/System/Globalization/EastAsianLunisolarCalendar.cs331
-rw-r--r--src/mscorlib/src/System/Globalization/EncodingDataItem.cs77
-rw-r--r--src/mscorlib/src/System/Globalization/EncodingTable.cs126
-rw-r--r--src/mscorlib/src/System/Globalization/GlobalizationAssembly.cs52
-rw-r--r--src/mscorlib/src/System/Globalization/GregorianCalendar.cs199
-rw-r--r--src/mscorlib/src/System/Globalization/GregorianCalendarHelper.cs385
-rw-r--r--src/mscorlib/src/System/Globalization/GregorianCalendarTypes.cs8
-rw-r--r--src/mscorlib/src/System/Globalization/HebrewCalendar.cs286
-rw-r--r--src/mscorlib/src/System/Globalization/HebrewNumber.cs173
-rw-r--r--src/mscorlib/src/System/Globalization/HijriCalendar.cs267
-rw-r--r--src/mscorlib/src/System/Globalization/IdnMapping.cs246
-rw-r--r--src/mscorlib/src/System/Globalization/JapaneseCalendar.cs122
-rw-r--r--src/mscorlib/src/System/Globalization/JapaneseLunisolarCalendar.cs81
-rw-r--r--src/mscorlib/src/System/Globalization/JulianCalendar.cs132
-rw-r--r--src/mscorlib/src/System/Globalization/KoreanCalendar.cs93
-rw-r--r--src/mscorlib/src/System/Globalization/KoreanLunisolarCalendar.cs107
-rw-r--r--src/mscorlib/src/System/Globalization/NumberFormatInfo.cs405
-rw-r--r--src/mscorlib/src/System/Globalization/NumberStyles.cs54
-rw-r--r--src/mscorlib/src/System/Globalization/PersianCalendar.cs193
-rw-r--r--src/mscorlib/src/System/Globalization/RegionInfo.cs87
-rw-r--r--src/mscorlib/src/System/Globalization/SortKey.cs86
-rw-r--r--src/mscorlib/src/System/Globalization/SortVersion.cs58
-rw-r--r--src/mscorlib/src/System/Globalization/StringInfo.cs189
-rw-r--r--src/mscorlib/src/System/Globalization/TaiwanCalendar.cs131
-rw-r--r--src/mscorlib/src/System/Globalization/TaiwanLunisolarCalendar.cs86
-rw-r--r--src/mscorlib/src/System/Globalization/TextElementEnumerator.cs88
-rw-r--r--src/mscorlib/src/System/Globalization/TextInfo.cs344
-rw-r--r--src/mscorlib/src/System/Globalization/ThaiBuddhistCalendar.cs84
-rw-r--r--src/mscorlib/src/System/Globalization/TimeSpanFormat.cs226
-rw-r--r--src/mscorlib/src/System/Globalization/TimeSpanParse.cs1072
-rw-r--r--src/mscorlib/src/System/Globalization/TimeSpanStyles.cs11
-rw-r--r--src/mscorlib/src/System/Globalization/UmAlQuraCalendar.cs268
-rw-r--r--src/mscorlib/src/System/Globalization/UnicodeCategory.cs7
-rw-r--r--src/mscorlib/src/System/Guid.cs792
-rw-r--r--src/mscorlib/src/System/IAppDomainPauseManager.cs22
-rw-r--r--src/mscorlib/src/System/ICloneable.cs8
-rw-r--r--src/mscorlib/src/System/IO/BinaryReader.cs313
-rw-r--r--src/mscorlib/src/System/IO/BinaryWriter.cs207
-rw-r--r--src/mscorlib/src/System/IO/Directory.cs18
-rw-r--r--src/mscorlib/src/System/IO/DirectoryNotFoundException.cs31
-rw-r--r--src/mscorlib/src/System/IO/DriveNotFoundException.cs25
-rw-r--r--src/mscorlib/src/System/IO/EndOfStreamException.cs26
-rw-r--r--src/mscorlib/src/System/IO/File.cs77
-rw-r--r--src/mscorlib/src/System/IO/FileAccess.cs11
-rw-r--r--src/mscorlib/src/System/IO/FileLoadException.cs70
-rw-r--r--src/mscorlib/src/System/IO/FileMode.cs15
-rw-r--r--src/mscorlib/src/System/IO/FileNotFoundException.cs77
-rw-r--r--src/mscorlib/src/System/IO/FileOptions.cs3
-rw-r--r--src/mscorlib/src/System/IO/FileShare.cs13
-rw-r--r--src/mscorlib/src/System/IO/IOException.cs36
-rw-r--r--src/mscorlib/src/System/IO/MemoryStream.cs327
-rw-r--r--src/mscorlib/src/System/IO/PathTooLongException.cs26
-rw-r--r--src/mscorlib/src/System/IO/PinnedBufferMemoryStream.cs17
-rw-r--r--src/mscorlib/src/System/IO/SearchOption.cs3
-rw-r--r--src/mscorlib/src/System/IO/SeekOrigin.cs3
-rw-r--r--src/mscorlib/src/System/IO/Stream.cs335
-rw-r--r--src/mscorlib/src/System/IO/UnmanagedMemoryAccessor.cs613
-rw-r--r--src/mscorlib/src/System/IO/UnmanagedMemoryStream.cs395
-rw-r--r--src/mscorlib/src/System/IO/UnmanagedMemoryStreamWrapper.cs137
-rw-r--r--src/mscorlib/src/System/IO/__Error.cs174
-rw-r--r--src/mscorlib/src/System/IO/__HResults.cs7
-rw-r--r--src/mscorlib/src/System/IServiceObjectProvider.cs8
-rw-r--r--src/mscorlib/src/System/InsufficientMemoryException.cs31
-rw-r--r--src/mscorlib/src/System/Int16.cs195
-rw-r--r--src/mscorlib/src/System/Int32.cs136
-rw-r--r--src/mscorlib/src/System/Int64.cs134
-rw-r--r--src/mscorlib/src/System/IntPtr.cs98
-rw-r--r--src/mscorlib/src/System/Internal.cs49
-rw-r--r--src/mscorlib/src/System/Lazy.cs22
-rw-r--r--src/mscorlib/src/System/LowLevelConsole.cs16
-rw-r--r--src/mscorlib/src/System/Math.cs911
-rw-r--r--src/mscorlib/src/System/MathF.cs32
-rw-r--r--src/mscorlib/src/System/MissingFieldException.cs61
-rw-r--r--src/mscorlib/src/System/MissingMemberException.cs88
-rw-r--r--src/mscorlib/src/System/MissingMethodException.cs61
-rw-r--r--src/mscorlib/src/System/MulticastDelegate.cs166
-rw-r--r--src/mscorlib/src/System/NonSerializedAttribute.cs19
-rw-r--r--src/mscorlib/src/System/NotFiniteNumberException.cs40
-rw-r--r--src/mscorlib/src/System/Nullable.cs105
-rw-r--r--src/mscorlib/src/System/Number.cs752
-rw-r--r--src/mscorlib/src/System/Object.cs320
-rw-r--r--src/mscorlib/src/System/ObjectDisposedException.cs2
-rw-r--r--src/mscorlib/src/System/OleAutBinder.cs26
-rw-r--r--src/mscorlib/src/System/OperatingSystem.cs87
-rw-r--r--src/mscorlib/src/System/OperationCanceledException.cs38
-rw-r--r--src/mscorlib/src/System/OutOfMemoryException.cs34
-rw-r--r--src/mscorlib/src/System/ParamsArray.cs29
-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/Random.cs483
-rw-r--r--src/mscorlib/src/System/Reflection/AmbiguousMatchException.cs24
-rw-r--r--src/mscorlib/src/System/Reflection/Assembly.cs221
-rw-r--r--src/mscorlib/src/System/Reflection/AssemblyAttributes.cs122
-rw-r--r--src/mscorlib/src/System/Reflection/AssemblyName.cs159
-rw-r--r--src/mscorlib/src/System/Reflection/AssemblyNameFlags.cs24
-rw-r--r--src/mscorlib/src/System/Reflection/Associates.cs35
-rw-r--r--src/mscorlib/src/System/Reflection/Binder.cs36
-rw-r--r--src/mscorlib/src/System/Reflection/BindingFlags.cs51
-rw-r--r--src/mscorlib/src/System/Reflection/CallingConventions.cs19
-rw-r--r--src/mscorlib/src/System/Reflection/ConstructorInfo.cs104
-rw-r--r--src/mscorlib/src/System/Reflection/CustomAttribute.cs140
-rw-r--r--src/mscorlib/src/System/Reflection/CustomAttributeExtensions.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/CustomAttributeFormatException.cs25
-rw-r--r--src/mscorlib/src/System/Reflection/DefaultMemberAttribute.cs17
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/AQNBuilder.cs16
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/AssemblyBuilder.cs83
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderAccess.cs2
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderData.cs124
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/ConstructorBuilder.cs88
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/CustomAttributeBuilder.cs55
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/DynamicILGenerator.cs7
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/DynamicMethod.cs328
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/EnumBuilder.cs217
-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.cs59
-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.cs51
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/ILGenerator.cs720
-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.cs40
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/MethodBuilder.cs262
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/MethodBuilderInstantiation.cs26
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/MethodToken.cs30
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/ModuleBuilder.cs197
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/ModuleBuilderData.cs34
-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.cs108
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/PropertyToken.cs34
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/SignatureHelper.cs282
-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.cs50
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/SymbolType.cs256
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/TypeBuilder.cs470
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs55
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/TypeToken.cs40
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/XXXOnTypeBuilderInstantiation.cs54
-rw-r--r--src/mscorlib/src/System/Reflection/EventAttributes.cs21
-rw-r--r--src/mscorlib/src/System/Reflection/EventInfo.cs55
-rw-r--r--src/mscorlib/src/System/Reflection/FieldAttributes.cs49
-rw-r--r--src/mscorlib/src/System/Reflection/FieldInfo.cs137
-rw-r--r--src/mscorlib/src/System/Reflection/GenericParameterAttributes.cs2
-rw-r--r--src/mscorlib/src/System/Reflection/ICustomAttributeProvider.cs13
-rw-r--r--src/mscorlib/src/System/Reflection/IReflect.cs27
-rw-r--r--src/mscorlib/src/System/Reflection/IReflectableType.cs12
-rw-r--r--src/mscorlib/src/System/Reflection/InterfaceMapping.cs17
-rw-r--r--src/mscorlib/src/System/Reflection/IntrospectionExtensions.cs7
-rw-r--r--src/mscorlib/src/System/Reflection/InvalidFilterCriteriaException.cs23
-rw-r--r--src/mscorlib/src/System/Reflection/LoaderAllocator.cs11
-rw-r--r--src/mscorlib/src/System/Reflection/ManifestResourceInfo.cs21
-rw-r--r--src/mscorlib/src/System/Reflection/MdConstant.cs29
-rw-r--r--src/mscorlib/src/System/Reflection/MdImport.cs476
-rw-r--r--src/mscorlib/src/System/Reflection/MemberFilter.cs3
-rw-r--r--src/mscorlib/src/System/Reflection/MemberInfo.cs26
-rw-r--r--src/mscorlib/src/System/Reflection/MemberInfoSerializationHolder.cs233
-rw-r--r--src/mscorlib/src/System/Reflection/MemberTypes.cs26
-rw-r--r--src/mscorlib/src/System/Reflection/MethodAttributes.cs65
-rw-r--r--src/mscorlib/src/System/Reflection/MethodBase.cs60
-rw-r--r--src/mscorlib/src/System/Reflection/MethodBody.cs33
-rw-r--r--src/mscorlib/src/System/Reflection/MethodImplAttributes.cs49
-rw-r--r--src/mscorlib/src/System/Reflection/MethodInfo.cs171
-rw-r--r--src/mscorlib/src/System/Reflection/Missing.cs12
-rw-r--r--src/mscorlib/src/System/Reflection/Module.cs169
-rw-r--r--src/mscorlib/src/System/Reflection/ObfuscateAssemblyAttribute.cs2
-rw-r--r--src/mscorlib/src/System/Reflection/ObfuscationAttribute.cs2
-rw-r--r--src/mscorlib/src/System/Reflection/ParameterAttributes.cs32
-rw-r--r--src/mscorlib/src/System/Reflection/ParameterInfo.cs70
-rw-r--r--src/mscorlib/src/System/Reflection/ParameterModifier.cs19
-rw-r--r--src/mscorlib/src/System/Reflection/Pointer.cs29
-rw-r--r--src/mscorlib/src/System/Reflection/PropertyAttributes.cs28
-rw-r--r--src/mscorlib/src/System/Reflection/PropertyInfo.cs101
-rw-r--r--src/mscorlib/src/System/Reflection/ReflectionContext.cs4
-rw-r--r--src/mscorlib/src/System/Reflection/ReflectionTypeLoadException.cs44
-rw-r--r--src/mscorlib/src/System/Reflection/ResourceAttributes.cs16
-rw-r--r--src/mscorlib/src/System/Reflection/RuntimeReflectionExtensions.cs8
-rw-r--r--src/mscorlib/src/System/Reflection/StrongNameKeyPair.cs53
-rw-r--r--src/mscorlib/src/System/Reflection/TargetException.cs29
-rw-r--r--src/mscorlib/src/System/Reflection/TargetInvocationException.cs38
-rw-r--r--src/mscorlib/src/System/Reflection/TargetParameterCountException.cs26
-rw-r--r--src/mscorlib/src/System/Reflection/TypeAttributes.cs88
-rw-r--r--src/mscorlib/src/System/Reflection/TypeDelegator.cs172
-rw-r--r--src/mscorlib/src/System/Reflection/TypeFilter.cs3
-rw-r--r--src/mscorlib/src/System/Reflection/TypeInfo.cs57
-rw-r--r--src/mscorlib/src/System/Reflection/__Filters.cs42
-rw-r--r--src/mscorlib/src/System/ResId.cs156
-rw-r--r--src/mscorlib/src/System/Resources/FileBasedResourceGroveler.cs12
-rw-r--r--src/mscorlib/src/System/Resources/IResourceGroveler.cs16
-rw-r--r--src/mscorlib/src/System/Resources/IResourceReader.cs12
-rw-r--r--src/mscorlib/src/System/Resources/ManifestBasedResourceGroveler.cs39
-rw-r--r--src/mscorlib/src/System/Resources/MissingManifestResourceException.cs25
-rw-r--r--src/mscorlib/src/System/Resources/MissingSatelliteAssemblyException.cs33
-rw-r--r--src/mscorlib/src/System/Resources/NeutralResourcesLanguageAttribute.cs19
-rw-r--r--src/mscorlib/src/System/Resources/ResourceFallbackManager.cs2
-rw-r--r--src/mscorlib/src/System/Resources/ResourceManager.cs358
-rw-r--r--src/mscorlib/src/System/Resources/ResourceReader.cs563
-rw-r--r--src/mscorlib/src/System/Resources/ResourceSet.cs49
-rw-r--r--src/mscorlib/src/System/Resources/ResourceTypeCode.cs6
-rw-r--r--src/mscorlib/src/System/Resources/RuntimeResourceSet.cs116
-rw-r--r--src/mscorlib/src/System/Resources/SatelliteContractVersionAttribute.cs16
-rw-r--r--src/mscorlib/src/System/Resources/UltimateResourceFallbackLocation.cs6
-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.cs736
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/AccessedThroughPropertyAttribute.cs11
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/AssemblySettingAttributes.cs56
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/CompilationRelaxations.cs59
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/CompilerGeneratedAttribute.cs9
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/CompilerGlobalScopeAttribute.cs4
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/ConditionalWeakTable.cs5
-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.cs8
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/DiscardableAttribute.cs5
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/ExtensionAttribute.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/FixedAddressValueTypeAttribute.cs16
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/FixedBufferAttribute.cs15
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/FormattableStringFactory.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/ICastable.cs12
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/IndexerNameAttribute.cs12
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/InternalsVisibleToAttribute.cs16
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/IsVolatile.cs4
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/MethodImplAttribute.cs64
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/ReferenceAssemblyAttribute.cs11
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/RuntimeCompatibilityAttribute.cs26
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs26
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/RuntimeWrappedException.cs30
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/SpecialNameAttribute.cs6
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/SuppressIldasmAttribute.cs7
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/SuppressMergeCheckAttribute.cs10
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/TaskAwaiter.cs26
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/TypeDependencyAttribute.cs18
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/TypeForwardedFromAttribute.cs9
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/TypeForwardedToAttribute.cs9
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/UnsafeValueTypeAttribute.cs16
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/YieldAwaitable.cs3
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/jithelpers.cs20
-rw-r--r--src/mscorlib/src/System/Runtime/ExceptionServices/CorruptingExceptionCommon.cs7
-rw-r--r--src/mscorlib/src/System/Runtime/ExceptionServices/ExceptionNotification.cs11
-rw-r--r--src/mscorlib/src/System/Runtime/ExceptionServices/ExceptionServicesCommon.cs30
-rw-r--r--src/mscorlib/src/System/Runtime/GcSettings.cs36
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ArrayWithOffset.cs36
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/Attributes.cs59
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/BStrWrapper.cs13
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/COMException.cs50
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/CallingConvention.cs17
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/CharSet.cs9
-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.cs13
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/DispatchWrapper.cs13
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ErrorWrapper.cs13
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/Expando/IExpando.cs9
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ExternalException.cs55
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/GcHandle.cs16
-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.cs32
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/InvalidOleVariantTypeException.cs34
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/LayoutKind.cs13
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/Marshal.cs398
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/MarshalDirectiveException.cs32
-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/PInvokeMap.cs60
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/RuntimeEnvironment.cs4
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/SEHException.cs39
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/SafeArrayRankMismatchException.cs34
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/SafeArrayTypeMismatchException.cs34
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/SafeBuffer.cs33
-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.cs4
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIKeyValuePairImpl.cs3
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs162
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIReferenceImpl.cs55
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs42
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs14
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryKeyCollection.cs14
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryToMapAdapter.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryValueCollection.cs17
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/EnumeratorToIteratorAdapter.cs10
-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.cs17
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IPropertyValue.cs10
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyDictionaryToIMapViewAdapter.cs5
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyListToIVectorViewAdapter.cs4
-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.cs4
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorViewAdapter.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToVectorAdapter.cs4
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ManagedActivationFactory.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToDictionaryAdapter.cs2
-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/WindowsRuntimeBufferHelper.cs41
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs236
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMetadata.cs26
-rw-r--r--src/mscorlib/src/System/Runtime/Loader/AssemblyLoadContext.cs138
-rw-r--r--src/mscorlib/src/System/Runtime/MemoryFailPoint.cs174
-rw-r--r--src/mscorlib/src/System/Runtime/Reliability/PrePrepareMethodAttribute.cs7
-rw-r--r--src/mscorlib/src/System/Runtime/Reliability/ReliabilityContractAttribute.cs23
-rw-r--r--src/mscorlib/src/System/Runtime/Remoting/ObjectHandle.cs10
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/FormatterConverter.cs121
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/FormatterServices.cs55
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/IDeserializationCallback.cs9
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/IFormatterConverter.cs31
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/IObjectReference.cs9
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/ISerializable.cs17
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/SafeSerializationManager.cs3
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/SerializationAttributes.cs46
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/SerializationException.cs33
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/SerializationInfo.cs35
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/SerializationInfoEnumerator.cs130
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/StreamingContext.cs80
-rw-r--r--src/mscorlib/src/System/Runtime/Versioning/NonVersionableAttribute.cs12
-rw-r--r--src/mscorlib/src/System/Runtime/Versioning/TargetFrameworkAttribute.cs14
-rw-r--r--src/mscorlib/src/System/RuntimeArgumentHandle.cs9
-rw-r--r--src/mscorlib/src/System/RuntimeHandles.cs344
-rw-r--r--src/mscorlib/src/System/SByte.cs195
-rw-r--r--src/mscorlib/src/System/Security/Attributes.cs48
-rw-r--r--src/mscorlib/src/System/Security/SecurityException.cs20
-rw-r--r--src/mscorlib/src/System/Security/SecurityState.cs6
-rw-r--r--src/mscorlib/src/System/Security/Util/URLString.cs4
-rw-r--r--src/mscorlib/src/System/Security/VerificationException.cs30
-rw-r--r--src/mscorlib/src/System/SerializableAttribute.cs24
-rw-r--r--src/mscorlib/src/System/SharedStatics.cs28
-rw-r--r--src/mscorlib/src/System/Single.cs201
-rw-r--r--src/mscorlib/src/System/Span.cs4
-rw-r--r--src/mscorlib/src/System/String.Comparison.cs246
-rw-r--r--src/mscorlib/src/System/String.Manipulation.cs506
-rw-r--r--src/mscorlib/src/System/String.Searching.cs154
-rw-r--r--src/mscorlib/src/System/String.cs352
-rw-r--r--src/mscorlib/src/System/StringComparer.cs262
-rw-r--r--src/mscorlib/src/System/StringFreezingAttribute.cs3
-rw-r--r--src/mscorlib/src/System/StubHelpers.cs254
-rw-r--r--src/mscorlib/src/System/Text/ASCIIEncoding.cs43
-rw-r--r--src/mscorlib/src/System/Text/Decoder.cs25
-rw-r--r--src/mscorlib/src/System/Text/DecoderBestFitFallback.cs33
-rw-r--r--src/mscorlib/src/System/Text/DecoderExceptionFallback.cs19
-rw-r--r--src/mscorlib/src/System/Text/DecoderFallback.cs26
-rw-r--r--src/mscorlib/src/System/Text/DecoderNLS.cs49
-rw-r--r--src/mscorlib/src/System/Text/DecoderReplacementFallback.cs28
-rw-r--r--src/mscorlib/src/System/Text/Encoder.cs29
-rw-r--r--src/mscorlib/src/System/Text/EncoderBestFitFallback.cs31
-rw-r--r--src/mscorlib/src/System/Text/EncoderExceptionFallback.cs20
-rw-r--r--src/mscorlib/src/System/Text/EncoderFallback.cs27
-rw-r--r--src/mscorlib/src/System/Text/EncoderNLS.cs50
-rw-r--r--src/mscorlib/src/System/Text/EncoderReplacementFallback.cs36
-rw-r--r--src/mscorlib/src/System/Text/Encoding.cs315
-rw-r--r--src/mscorlib/src/System/Text/EncodingForwarder.cs6
-rw-r--r--src/mscorlib/src/System/Text/EncodingInfo.cs24
-rw-r--r--src/mscorlib/src/System/Text/EncodingNLS.cs23
-rw-r--r--src/mscorlib/src/System/Text/EncodingProvider.cs8
-rw-r--r--src/mscorlib/src/System/Text/Latin1Encoding.cs39
-rw-r--r--src/mscorlib/src/System/Text/Normalization.Windows.cs46
-rw-r--r--src/mscorlib/src/System/Text/Normalization.cs26
-rw-r--r--src/mscorlib/src/System/Text/StringBuilder.cs651
-rw-r--r--src/mscorlib/src/System/Text/StringBuilderCache.cs5
-rw-r--r--src/mscorlib/src/System/Text/UTF32Encoding.cs122
-rw-r--r--src/mscorlib/src/System/Text/UTF7Encoding.cs87
-rw-r--r--src/mscorlib/src/System/Text/UTF8Encoding.cs699
-rw-r--r--src/mscorlib/src/System/Text/UnicodeEncoding.cs168
-rw-r--r--src/mscorlib/src/System/Threading/AbandonedMutexException.cs69
-rw-r--r--src/mscorlib/src/System/Threading/ApartmentState.cs6
-rw-r--r--src/mscorlib/src/System/Threading/AsyncLocal.cs16
-rw-r--r--src/mscorlib/src/System/Threading/AutoResetEvent.cs13
-rw-r--r--src/mscorlib/src/System/Threading/CancellationToken.cs28
-rw-r--r--src/mscorlib/src/System/Threading/CancellationTokenRegistration.cs6
-rw-r--r--src/mscorlib/src/System/Threading/CancellationTokenSource.cs42
-rw-r--r--src/mscorlib/src/System/Threading/CountdownEvent.cs3
-rw-r--r--src/mscorlib/src/System/Threading/EventResetMode.cs3
-rw-r--r--src/mscorlib/src/System/Threading/EventWaitHandle.cs41
-rw-r--r--src/mscorlib/src/System/Threading/ExecutionContext.cs49
-rw-r--r--src/mscorlib/src/System/Threading/Interlocked.cs33
-rw-r--r--src/mscorlib/src/System/Threading/LazyInitializer.cs5
-rw-r--r--src/mscorlib/src/System/Threading/LockRecursionException.cs9
-rw-r--r--src/mscorlib/src/System/Threading/ManualResetEvent.cs15
-rw-r--r--src/mscorlib/src/System/Threading/ManualResetEventSlim.cs10
-rw-r--r--src/mscorlib/src/System/Threading/Monitor.cs31
-rw-r--r--src/mscorlib/src/System/Threading/Mutex.cs70
-rw-r--r--src/mscorlib/src/System/Threading/Overlapped.cs91
-rw-r--r--src/mscorlib/src/System/Threading/ParameterizedThreadStart.cs7
-rw-r--r--src/mscorlib/src/System/Threading/SemaphoreFullException.cs29
-rw-r--r--src/mscorlib/src/System/Threading/SemaphoreSlim.cs15
-rw-r--r--src/mscorlib/src/System/Threading/SendOrPostCallback.cs2
-rw-r--r--src/mscorlib/src/System/Threading/SpinWait.cs5
-rw-r--r--src/mscorlib/src/System/Threading/SynchronizationContext.cs46
-rw-r--r--src/mscorlib/src/System/Threading/SynchronizationLockException.cs34
-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.cs194
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/Task.cs40
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/TaskCanceledException.cs6
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/TaskCompletionSource.cs6
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/TaskContinuation.cs33
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/TaskExceptionHolder.cs34
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/TaskFactory.cs10
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/TaskScheduler.cs42
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/TaskSchedulerException.cs4
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/TaskToApm.cs6
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/ThreadPoolTaskScheduler.cs4
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/future.cs29
-rw-r--r--src/mscorlib/src/System/Threading/Thread.cs163
-rw-r--r--src/mscorlib/src/System/Threading/ThreadAbortException.cs18
-rw-r--r--src/mscorlib/src/System/Threading/ThreadInterruptedException.cs35
-rw-r--r--src/mscorlib/src/System/Threading/ThreadLocal.cs7
-rw-r--r--src/mscorlib/src/System/Threading/ThreadPool.cs220
-rw-r--r--src/mscorlib/src/System/Threading/ThreadPriority.cs8
-rw-r--r--src/mscorlib/src/System/Threading/ThreadStart.cs5
-rw-r--r--src/mscorlib/src/System/Threading/ThreadStartException.cs21
-rw-r--r--src/mscorlib/src/System/Threading/ThreadState.cs10
-rw-r--r--src/mscorlib/src/System/Threading/ThreadStateException.cs34
-rw-r--r--src/mscorlib/src/System/Threading/Timeout.cs9
-rw-r--r--src/mscorlib/src/System/Threading/Timer.cs145
-rw-r--r--src/mscorlib/src/System/Threading/Volatile.cs1
-rw-r--r--src/mscorlib/src/System/Threading/WaitHandle.cs155
-rw-r--r--src/mscorlib/src/System/Threading/WaitHandleCannotBeOpenedException.cs20
-rw-r--r--src/mscorlib/src/System/ThrowHelper.cs267
-rw-r--r--src/mscorlib/src/System/TimeSpan.cs234
-rw-r--r--src/mscorlib/src/System/TimeZone.cs139
-rw-r--r--src/mscorlib/src/System/TimeZoneInfo.AdjustmentRule.cs2
-rw-r--r--src/mscorlib/src/System/TimeZoneInfo.TransitionTime.cs2
-rw-r--r--src/mscorlib/src/System/TimeZoneInfo.Win32.cs1
-rw-r--r--src/mscorlib/src/System/TimeZoneInfo.cs7
-rw-r--r--src/mscorlib/src/System/Tuple.cs10
-rw-r--r--src/mscorlib/src/System/Type.cs735
-rw-r--r--src/mscorlib/src/System/TypeLoadException.cs92
-rw-r--r--src/mscorlib/src/System/TypeNameParser.cs9
-rw-r--r--src/mscorlib/src/System/TypeUnloadedException.cs32
-rw-r--r--src/mscorlib/src/System/TypedReference.cs35
-rw-r--r--src/mscorlib/src/System/UInt16.cs157
-rw-r--r--src/mscorlib/src/System/UInt32.cs129
-rw-r--r--src/mscorlib/src/System/UInt64.cs139
-rw-r--r--src/mscorlib/src/System/UIntPtr.cs78
-rw-r--r--src/mscorlib/src/System/UnitySerializationHolder.cs195
-rw-r--r--src/mscorlib/src/System/ValueType.cs38
-rw-r--r--src/mscorlib/src/System/Variant.cs387
-rw-r--r--src/mscorlib/src/System/Version.cs329
-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.cs2
-rw-r--r--src/mscorlib/src/System/__ComObject.cs36
-rw-r--r--src/mscorlib/src/System/__Filters.cs186
-rw-r--r--src/mscorlib/src/System/__HResults.cs153
-rw-r--r--src/mscorlib/src/mscorlib.Friends.cs7
681 files changed, 40714 insertions, 31719 deletions
diff --git a/src/mscorlib/Common/PinnableBufferCache.cs b/src/mscorlib/Common/PinnableBufferCache.cs
index 6c85a5a2f6..3f7853ce59 100644
--- a/src/mscorlib/Common/PinnableBufferCache.cs
+++ b/src/mscorlib/Common/PinnableBufferCache.cs
@@ -3,6 +3,7 @@
// See the LICENSE file in the project root for more information.
#define ENABLE
#define MINBUFFERS
+
using System;
using System.Runtime.InteropServices;
using System.Runtime.ConstrainedExecution;
@@ -20,7 +21,6 @@ namespace System
{
internal sealed class PinnableBufferCache
{
-
/// <summary>
/// Create a PinnableBufferCache that works on any object (it is intended for OverlappedData)
/// This is only used in mscorlib.
@@ -519,22 +519,22 @@ namespace System
public static readonly PinnableBufferCacheEventSource Log = new PinnableBufferCacheEventSource();
public bool IsEnabled() { return false; }
- public void DebugMessage(string message) {}
- public void Create(string cacheName) {}
- public void AllocateBuffer(string cacheName, ulong objectId, int objectHash, int objectGen, int freeCountAfter) {}
- public void AllocateBufferFromNotGen2(string cacheName, int notGen2CountAfter) {}
- public void AllocateBufferCreatingNewBuffers(string cacheName, int totalBuffsBefore, int objectCount) {}
- public void AllocateBufferAged(string cacheName, int agedCount) {}
- public void AllocateBufferFreeListEmpty(string cacheName, int notGen2CountBefore) {}
- public void FreeBuffer(string cacheName, ulong objectId, int objectHash, int freeCountBefore) {}
- public void FreeBufferStillTooYoung(string cacheName, int notGen2CountBefore) {}
- public void TrimCheck(string cacheName, int totalBuffs, bool neededMoreThanFreeList, int deltaMSec) {}
- public void TrimFree(string cacheName, int totalBuffs, int freeListCount, int toBeFreed) {}
- public void TrimExperiment(string cacheName, int totalBuffs, int freeListCount, int numTrimTrial) {}
- public void TrimFreeSizeOK(string cacheName, int totalBuffs, int freeListCount) {}
- public void TrimFlush(string cacheName, int totalBuffs, int freeListCount, int notGen2CountBefore) {}
- public void AgePendingBuffersResults(string cacheName, int promotedToFreeListCount, int heldBackCount) {}
- public void WalkFreeListResult(string cacheName, int freeListCount, int gen0BuffersInFreeList) {}
+ public void DebugMessage(string message) { }
+ public void Create(string cacheName) { }
+ public void AllocateBuffer(string cacheName, ulong objectId, int objectHash, int objectGen, int freeCountAfter) { }
+ public void AllocateBufferFromNotGen2(string cacheName, int notGen2CountAfter) { }
+ public void AllocateBufferCreatingNewBuffers(string cacheName, int totalBuffsBefore, int objectCount) { }
+ public void AllocateBufferAged(string cacheName, int agedCount) { }
+ public void AllocateBufferFreeListEmpty(string cacheName, int notGen2CountBefore) { }
+ public void FreeBuffer(string cacheName, ulong objectId, int objectHash, int freeCountBefore) { }
+ public void FreeBufferStillTooYoung(string cacheName, int notGen2CountBefore) { }
+ public void TrimCheck(string cacheName, int totalBuffs, bool neededMoreThanFreeList, int deltaMSec) { }
+ public void TrimFree(string cacheName, int totalBuffs, int freeListCount, int toBeFreed) { }
+ public void TrimExperiment(string cacheName, int totalBuffs, int freeListCount, int numTrimTrial) { }
+ public void TrimFreeSizeOK(string cacheName, int totalBuffs, int freeListCount) { }
+ public void TrimFlush(string cacheName, int totalBuffs, int freeListCount, int notGen2CountBefore) { }
+ public void AgePendingBuffersResults(string cacheName, int promotedToFreeListCount, int heldBackCount) { }
+ public void WalkFreeListResult(string cacheName, int freeListCount, int gen0BuffersInFreeList) { }
static internal ulong AddressOf(object obj)
{
diff --git a/src/mscorlib/Common/Preprocessed/AssemblyRefs.g.cs b/src/mscorlib/Common/Preprocessed/AssemblyRefs.g.cs
index d5866a4bcd..fba0953e20 100644
--- a/src/mscorlib/Common/Preprocessed/AssemblyRefs.g.cs
+++ b/src/mscorlib/Common/Preprocessed/AssemblyRefs.g.cs
@@ -15,19 +15,21 @@ using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
-internal static class FXAssembly {
+internal static class FXAssembly
+{
internal const string Version = "4.0.0.0";
}
-internal static class ThisAssembly {
+internal static class ThisAssembly
+{
internal const string Version = "4.0.0.0";
internal const int DailyBuildNumber = 22306;
}
-internal static class AssemblyRef {
- internal const string EcmaPublicKey = "b77a5c561934e089";
- internal const string EcmaPublicKeyToken = "b77a5c561934e089";
- internal const string MicrosoftPublicKeyToken = "b03f5f7f11d50a3a";
- internal const string SystemRuntimeWindowsRuntime = "System.Runtime.WindowsRuntime, Version=" + FXAssembly.Version + ", Culture=neutral, PublicKeyToken=" + EcmaPublicKey;
-
+internal static class AssemblyRef
+{
+ internal const string EcmaPublicKey = "b77a5c561934e089";
+ internal const string EcmaPublicKeyToken = "b77a5c561934e089";
+ internal const string MicrosoftPublicKeyToken = "b03f5f7f11d50a3a";
+ internal const string SystemRuntimeWindowsRuntime = "System.Runtime.WindowsRuntime, Version=" + FXAssembly.Version + ", Culture=neutral, PublicKeyToken=" + EcmaPublicKey;
}
diff --git a/src/mscorlib/corefx/Interop/Windows/NtDll/Interop.ZeroMemory.cs b/src/mscorlib/corefx/Interop/Windows/NtDll/Interop.ZeroMemory.cs
index bd2a64cf14..9bf7321f2a 100644
--- a/src/mscorlib/corefx/Interop/Windows/NtDll/Interop.ZeroMemory.cs
+++ b/src/mscorlib/corefx/Interop/Windows/NtDll/Interop.ZeroMemory.cs
@@ -10,7 +10,6 @@ internal partial class Interop
{
internal partial class NtDll
{
-
[DllImport(Libraries.NtDll, CharSet = CharSet.Unicode, EntryPoint = "RtlZeroMemory")]
internal static extern void ZeroMemory(IntPtr address, UIntPtr length);
}
diff --git a/src/mscorlib/corefx/Interop/Windows/kernel32/Interop.FileOperations.cs b/src/mscorlib/corefx/Interop/Windows/kernel32/Interop.FileOperations.cs
index 6e3ebb9ae9..2bc5228e60 100644
--- a/src/mscorlib/corefx/Interop/Windows/kernel32/Interop.FileOperations.cs
+++ b/src/mscorlib/corefx/Interop/Windows/kernel32/Interop.FileOperations.cs
@@ -6,7 +6,6 @@ internal partial class Interop
{
internal partial class Kernel32
{
-
internal const uint SEM_FAILCRITICALERRORS = 1;
}
}
diff --git a/src/mscorlib/corefx/Interop/Windows/kernel32/Interop.GetFileInformationByHandleEx.cs b/src/mscorlib/corefx/Interop/Windows/kernel32/Interop.GetFileInformationByHandleEx.cs
index 146c4638ee..40f9e91185 100644
--- a/src/mscorlib/corefx/Interop/Windows/kernel32/Interop.GetFileInformationByHandleEx.cs
+++ b/src/mscorlib/corefx/Interop/Windows/kernel32/Interop.GetFileInformationByHandleEx.cs
@@ -21,6 +21,5 @@ internal partial class Interop
internal BOOL DeletePending;
internal BOOL Directory;
}
-
}
}
diff --git a/src/mscorlib/corefx/Interop/Windows/kernel32/Interop.GetLongPathNameW.cs b/src/mscorlib/corefx/Interop/Windows/kernel32/Interop.GetLongPathNameW.cs
index a58d1013ca..ce04078af5 100644
--- a/src/mscorlib/corefx/Interop/Windows/kernel32/Interop.GetLongPathNameW.cs
+++ b/src/mscorlib/corefx/Interop/Windows/kernel32/Interop.GetLongPathNameW.cs
@@ -5,9 +5,9 @@
using System;
using System.Runtime.InteropServices;
-partial class Interop
+internal partial class Interop
{
- partial class Kernel32
+ internal partial class Kernel32
{
/// <summary>
/// WARNING: This method does not implicitly handle long paths. Use GetFullPath/PathHelper.
diff --git a/src/mscorlib/corefx/Interop/Windows/kernel32/Interop.GetTempFileNameW.cs b/src/mscorlib/corefx/Interop/Windows/kernel32/Interop.GetTempFileNameW.cs
index d157a29c92..36673895b4 100644
--- a/src/mscorlib/corefx/Interop/Windows/kernel32/Interop.GetTempFileNameW.cs
+++ b/src/mscorlib/corefx/Interop/Windows/kernel32/Interop.GetTempFileNameW.cs
@@ -6,9 +6,9 @@ using System;
using System.Text;
using System.Runtime.InteropServices;
-partial class Interop
+internal partial class Interop
{
- partial class Kernel32
+ internal partial class Kernel32
{
[DllImport(Libraries.Kernel32, CharSet = CharSet.Unicode, SetLastError = true, BestFitMapping = false)]
internal static extern uint GetTempFileNameW(string tmpPath, string prefix, uint uniqueIdOrZero, [Out]StringBuilder tmpFileName);
diff --git a/src/mscorlib/corefx/Interop/Windows/kernel32/Interop.GetTempPathW.cs b/src/mscorlib/corefx/Interop/Windows/kernel32/Interop.GetTempPathW.cs
index 25ffcd55b0..ff2783be26 100644
--- a/src/mscorlib/corefx/Interop/Windows/kernel32/Interop.GetTempPathW.cs
+++ b/src/mscorlib/corefx/Interop/Windows/kernel32/Interop.GetTempPathW.cs
@@ -6,9 +6,9 @@ using System.IO;
using System.Text;
using System.Runtime.InteropServices;
-partial class Interop
+internal partial class Interop
{
- partial class Kernel32
+ internal partial class Kernel32
{
[DllImport(Libraries.Kernel32, CharSet = CharSet.Unicode, BestFitMapping = false)]
internal static extern uint GetTempPathW(int bufferLen, [Out]StringBuilder buffer);
diff --git a/src/mscorlib/corefx/Interop/Windows/kernel32/Interop.WideCharToMultiByte.cs b/src/mscorlib/corefx/Interop/Windows/kernel32/Interop.WideCharToMultiByte.cs
index 07271cae33..a06c9153f4 100644
--- a/src/mscorlib/corefx/Interop/Windows/kernel32/Interop.WideCharToMultiByte.cs
+++ b/src/mscorlib/corefx/Interop/Windows/kernel32/Interop.WideCharToMultiByte.cs
@@ -11,9 +11,9 @@ internal partial class Interop
{
[DllImport(Libraries.Kernel32)]
internal static extern unsafe int WideCharToMultiByte(
- uint CodePage, uint dwFlags,
- char* lpWideCharStr, int cchWideChar,
- byte* lpMultiByteStr, int cbMultiByte,
+ uint CodePage, uint dwFlags,
+ char* lpWideCharStr, int cchWideChar,
+ byte* lpMultiByteStr, int cbMultiByte,
IntPtr lpDefaultChar, IntPtr lpUsedDefaultChar);
internal const uint CP_ACP = 0;
diff --git a/src/mscorlib/corefx/Interop/Windows/kernel32/Interop.WriteFile_SafeHandle_IntPtr.cs b/src/mscorlib/corefx/Interop/Windows/kernel32/Interop.WriteFile_SafeHandle_IntPtr.cs
index e7e868e142..69651ca1ca 100644
--- a/src/mscorlib/corefx/Interop/Windows/kernel32/Interop.WriteFile_SafeHandle_IntPtr.cs
+++ b/src/mscorlib/corefx/Interop/Windows/kernel32/Interop.WriteFile_SafeHandle_IntPtr.cs
@@ -19,6 +19,5 @@ internal partial class Interop
[DllImport(Libraries.Kernel32, SetLastError = true)]
internal static extern unsafe int WriteFile(SafeHandle handle, byte* bytes, int numBytesToWrite, out int numBytesWritten, IntPtr mustBeZero);
-
}
}
diff --git a/src/mscorlib/corefx/System/Buffers/Utilities.cs b/src/mscorlib/corefx/System/Buffers/Utilities.cs
index 823299f5fc..4f115fe9dd 100644
--- a/src/mscorlib/corefx/System/Buffers/Utilities.cs
+++ b/src/mscorlib/corefx/System/Buffers/Utilities.cs
@@ -16,10 +16,10 @@ namespace System.Buffers
int poolIndex = 0;
if (bitsRemaining > 0xFFFF) { bitsRemaining >>= 16; poolIndex = 16; }
- if (bitsRemaining > 0xFF) { bitsRemaining >>= 8; poolIndex += 8; }
- if (bitsRemaining > 0xF) { bitsRemaining >>= 4; poolIndex += 4; }
- if (bitsRemaining > 0x3) { bitsRemaining >>= 2; poolIndex += 2; }
- if (bitsRemaining > 0x1) { bitsRemaining >>= 1; poolIndex += 1; }
+ if (bitsRemaining > 0xFF) { bitsRemaining >>= 8; poolIndex += 8; }
+ if (bitsRemaining > 0xF) { bitsRemaining >>= 4; poolIndex += 4; }
+ if (bitsRemaining > 0x3) { bitsRemaining >>= 2; poolIndex += 2; }
+ if (bitsRemaining > 0x1) { bitsRemaining >>= 1; poolIndex += 1; }
return poolIndex + (int)bitsRemaining;
}
diff --git a/src/mscorlib/corefx/System/IO/FileStream.Win32.cs b/src/mscorlib/corefx/System/IO/FileStream.Win32.cs
index 683eef5e43..82e7473c02 100644
--- a/src/mscorlib/corefx/System/IO/FileStream.Win32.cs
+++ b/src/mscorlib/corefx/System/IO/FileStream.Win32.cs
@@ -353,8 +353,8 @@ namespace System.IO
_writePos = 0;
// Update the active buffer operation
- _activeBufferOperation = HasActiveBufferOperation ?
- Task.WhenAll(_activeBufferOperation, flushTask) :
+ _activeBufferOperation = HasActiveBufferOperation ?
+ Task.WhenAll(_activeBufferOperation, flushTask) :
flushTask;
return flushTask;
@@ -1726,7 +1726,7 @@ namespace System.IO
return Task.CompletedTask;
}
}
-
+
private Task<int> TaskFromResultOrCache(int result)
{
Task<int> completedTask = _lastSynchronouslyCompletedTask;
diff --git a/src/mscorlib/corefx/System/IO/FileStreamCompletionSource.Win32.cs b/src/mscorlib/corefx/System/IO/FileStreamCompletionSource.Win32.cs
index 159e416e63..7dca13335e 100644
--- a/src/mscorlib/corefx/System/IO/FileStreamCompletionSource.Win32.cs
+++ b/src/mscorlib/corefx/System/IO/FileStreamCompletionSource.Win32.cs
@@ -135,8 +135,8 @@ namespace System.IO
// overlapped was already in use by another operation).
object state = ThreadPoolBoundHandle.GetNativeOverlappedState(pOverlapped);
FileStream fs = state as FileStream;
- FileStreamCompletionSource completionSource = fs != null ?
- fs._currentOverlappedOwner :
+ FileStreamCompletionSource completionSource = fs != null ?
+ fs._currentOverlappedOwner :
(FileStreamCompletionSource)state;
Debug.Assert(completionSource._overlapped == pOverlapped, "Overlaps don't match");
@@ -169,7 +169,8 @@ namespace System.IO
// else: Some other thread is registering a cancellation, so it *must* finish the callback
}
- private void CompleteCallback(ulong packedResult) {
+ private void CompleteCallback(ulong packedResult)
+ {
// Free up the native resource and cancellation registration
ReleaseNativeResource();
@@ -203,7 +204,7 @@ namespace System.IO
Debug.Assert(completionSource._overlapped != null && !completionSource.Task.IsCompleted, "IO should not have completed yet");
// If the handle is still valid, attempt to cancel the IO
- if (!completionSource._stream._fileHandle.IsInvalid &&
+ if (!completionSource._stream._fileHandle.IsInvalid &&
!Interop.Kernel32.CancelIoEx(completionSource._stream._fileHandle, completionSource._overlapped))
{
int errorCode = Marshal.GetLastWin32Error();
@@ -216,6 +217,6 @@ namespace System.IO
}
}
}
- }
+ }
}
}
diff --git a/src/mscorlib/corefx/System/IO/Path.Windows.cs b/src/mscorlib/corefx/System/IO/Path.Windows.cs
index ce867efd2c..0f8e3b39cc 100644
--- a/src/mscorlib/corefx/System/IO/Path.Windows.cs
+++ b/src/mscorlib/corefx/System/IO/Path.Windows.cs
@@ -11,11 +11,11 @@ namespace System.IO
{
public static char[] GetInvalidFileNameChars() => new char[]
{
- '\"', '<', '>', '|', '\0',
- (char)1, (char)2, (char)3, (char)4, (char)5, (char)6, (char)7, (char)8, (char)9, (char)10,
- (char)11, (char)12, (char)13, (char)14, (char)15, (char)16, (char)17, (char)18, (char)19, (char)20,
- (char)21, (char)22, (char)23, (char)24, (char)25, (char)26, (char)27, (char)28, (char)29, (char)30,
- (char)31, ':', '*', '?', '\\', '/'
+ '\"', '<', '>', '|', '\0',
+ (char)1, (char)2, (char)3, (char)4, (char)5, (char)6, (char)7, (char)8, (char)9, (char)10,
+ (char)11, (char)12, (char)13, (char)14, (char)15, (char)16, (char)17, (char)18, (char)19, (char)20,
+ (char)21, (char)22, (char)23, (char)24, (char)25, (char)26, (char)27, (char)28, (char)29, (char)30,
+ (char)31, ':', '*', '?', '\\', '/'
};
public static char[] GetInvalidPathChars() => new char[]
@@ -122,7 +122,7 @@ namespace System.IO
PathInternal.CheckInvalidPathChars(path);
int length = path.Length;
- if ((length >= 1 && PathInternal.IsDirectorySeparator(path[0])) ||
+ if ((length >= 1 && PathInternal.IsDirectorySeparator(path[0])) ||
(length >= 2 && path[1] == PathInternal.VolumeSeparatorChar))
return true;
}
diff --git a/src/mscorlib/corefx/System/IO/Path.cs b/src/mscorlib/corefx/System/IO/Path.cs
index 77b213968b..ce80424d15 100644
--- a/src/mscorlib/corefx/System/IO/Path.cs
+++ b/src/mscorlib/corefx/System/IO/Path.cs
@@ -22,7 +22,7 @@ namespace System.IO
// For generating random file names
// 8 random bytes provides 12 chars in our encoding for the 8.3 name.
- const int KeyLength = 8;
+ private const int KeyLength = 8;
[Obsolete("Please use GetInvalidPathChars or GetInvalidFileNameChars instead.")]
public static readonly char[] InvalidPathChars = GetInvalidPathChars();
@@ -128,7 +128,7 @@ namespace System.IO
{
if (path == null)
return null;
-
+
int offset = PathInternal.FindFileNameIndex(path);
int count = path.Length - offset;
return path.Substring(offset, count);
@@ -142,7 +142,7 @@ namespace System.IO
int length = path.Length;
int offset = PathInternal.FindFileNameIndex(path);
-
+
int end = path.LastIndexOf('.', length - 1, length - offset);
return end == -1 ?
path.Substring(offset) : // No extension was found
@@ -153,7 +153,6 @@ namespace System.IO
// used as either a folder name or a file name.
public static unsafe string GetRandomFileName()
{
-
byte* pKey = stackalloc byte[KeyLength];
GetCryptoRandomBytes(pKey, KeyLength);
@@ -190,7 +189,7 @@ namespace System.IO
public static string Combine(string path1, string path2)
{
if (path1 == null || path2 == null)
- throw new ArgumentNullException((path1 == null) ? nameof(path1): nameof(path2));
+ throw new ArgumentNullException((path1 == null) ? nameof(path1) : nameof(path2));
Contract.EndContractBlock();
PathInternal.CheckInvalidPathChars(path1);
@@ -202,7 +201,7 @@ namespace System.IO
public static string Combine(string path1, string path2, string path3)
{
if (path1 == null || path2 == null || path3 == null)
- throw new ArgumentNullException((path1 == null) ? nameof(path1): (path2 == null) ? nameof(path2): nameof(path3));
+ throw new ArgumentNullException((path1 == null) ? nameof(path1) : (path2 == null) ? nameof(path2) : nameof(path3));
Contract.EndContractBlock();
PathInternal.CheckInvalidPathChars(path1);
@@ -215,7 +214,7 @@ namespace System.IO
public static string Combine(string path1, string path2, string path3, string path4)
{
if (path1 == null || path2 == null || path3 == null || path4 == null)
- throw new ArgumentNullException((path1 == null) ? nameof(path1): (path2 == null) ? nameof(path2): (path3 == null) ? nameof(path3): nameof(path4));
+ throw new ArgumentNullException((path1 == null) ? nameof(path1) : (path2 == null) ? nameof(path2) : (path3 == null) ? nameof(path3) : nameof(path4));
Contract.EndContractBlock();
PathInternal.CheckInvalidPathChars(path1);
diff --git a/src/mscorlib/corefx/System/IO/PathInternal.Windows.cs b/src/mscorlib/corefx/System/IO/PathInternal.Windows.cs
index 0ec9b30f99..ee0dd54383 100644
--- a/src/mscorlib/corefx/System/IO/PathInternal.Windows.cs
+++ b/src/mscorlib/corefx/System/IO/PathInternal.Windows.cs
@@ -206,7 +206,7 @@ namespace System.IO
/// </summary>
internal unsafe static int GetRootLength(string path)
{
- fixed(char* value = path)
+ fixed (char* value = path)
{
return GetRootLength(value, path.Length);
}
diff --git a/src/mscorlib/corefx/System/IO/PathInternal.cs b/src/mscorlib/corefx/System/IO/PathInternal.cs
index 6b4c3b2d30..0dab5b968a 100644
--- a/src/mscorlib/corefx/System/IO/PathInternal.cs
+++ b/src/mscorlib/corefx/System/IO/PathInternal.cs
@@ -40,7 +40,7 @@ namespace System.IO
if (HasIllegalCharacters(path))
throw new ArgumentException(SR.Argument_InvalidPathChars, nameof(path));
}
-
+
/// <summary>
/// Returns the start index of the filename
/// in the given path, or 0 if no directory
@@ -140,7 +140,7 @@ namespace System.IO
return firstRootLength == secondRootLength
&& string.Compare(
strA: first,
- indexA: 0,
+ indexA: 0,
strB: second,
indexB: 0,
length: firstRootLength,
@@ -166,7 +166,6 @@ namespace System.IO
searchPattern = searchPattern.Substring(index + 2);
}
-
}
}
}
diff --git a/src/mscorlib/corefx/System/Security/SecureString.Windows.cs b/src/mscorlib/corefx/System/Security/SecureString.Windows.cs
index 7ed0c6a15b..9d8d4956ec 100644
--- a/src/mscorlib/corefx/System/Security/SecureString.Windows.cs
+++ b/src/mscorlib/corefx/System/Security/SecureString.Windows.cs
@@ -158,7 +158,8 @@ namespace System.Security
int resultByteLength = (length + 1) * sizeof(char);
ptr = Win32Native.SysAllocStringLen(null, length);
- if (ptr == IntPtr.Zero) {
+ if (ptr == IntPtr.Zero)
+ {
throw new OutOfMemoryException();
}
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/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 d8c8db797d..47a6072e96 100644
--- a/src/mscorlib/src/Microsoft/Win32/Registry.cs
+++ b/src/mscorlib/src/Microsoft/Win32/Registry.cs
@@ -3,11 +3,12 @@
// See the LICENSE file in the project root for more information.
-namespace Microsoft.Win32 {
- using System;
- using System.Runtime.InteropServices;
- using System.Runtime.Versioning;
+using System;
+using System.Runtime.InteropServices;
+using System.Runtime.Versioning;
+namespace Microsoft.Win32
+{
/**
* Registry encapsulation. Contains members representing all top level system
* keys.
@@ -15,49 +16,49 @@ namespace Microsoft.Win32 {
* @security(checkClassLinking=on)
*/
//This class contains only static members and does not need to be serializable.
- internal static class Registry {
-
+ internal static class 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);
-
+ 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);
-
+ 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);
-
+ 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);
-
+ 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);
-
+ 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);
+ public static readonly RegistryKey CurrentConfig = RegistryKey.GetBaseKey(RegistryKey.HKEY_CURRENT_CONFIG);
//
// Following function will parse a keyName and returns the basekey for it.
@@ -65,66 +66,77 @@ namespace Microsoft.Win32 {
// 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) {
+ 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) {
+ if (i != -1)
+ {
basekeyName = keyName.Substring(0, i).ToUpper(System.Globalization.CultureInfo.InvariantCulture);
}
- else {
+ else
+ {
basekeyName = keyName.ToUpper(System.Globalization.CultureInfo.InvariantCulture);
- }
+ }
RegistryKey basekey = null;
- switch(basekeyName) {
- case "HKEY_CURRENT_USER":
+ switch (basekeyName)
+ {
+ case "HKEY_CURRENT_USER":
basekey = Registry.CurrentUser;
break;
- case "HKEY_LOCAL_MACHINE":
+ case "HKEY_LOCAL_MACHINE":
basekey = Registry.LocalMachine;
break;
- case "HKEY_CLASSES_ROOT":
+ case "HKEY_CLASSES_ROOT":
basekey = Registry.ClassesRoot;
break;
- case "HKEY_USERS":
+ case "HKEY_USERS":
basekey = Registry.Users;
break;
- case "HKEY_PERFORMANCE_DATA":
+ case "HKEY_PERFORMANCE_DATA":
basekey = Registry.PerformanceData;
break;
- case "HKEY_CURRENT_CONFIG":
+ case "HKEY_CURRENT_CONFIG":
basekey = Registry.CurrentConfig;
break;
default:
throw new ArgumentException(Environment.GetResourceString("Arg_RegInvalidKeyName", nameof(keyName)));
- }
- if( i == -1 || i == keyName.Length) {
+ }
+ if (i == -1 || i == keyName.Length)
+ {
subKeyName = string.Empty;
}
- else {
+ else
+ {
subKeyName = keyName.Substring(i + 1, keyName.Length - i - 1);
}
return basekey;
}
- public static object GetValue(string keyName, string valueName, object defaultValue ) {
+ 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
+ if (key == null)
+ { // if the key doesn't exist, do nothing
return null;
}
- try {
- return key.GetValue(valueName, defaultValue);
- }
- finally {
+ try
+ {
+ return key.GetValue(valueName, defaultValue);
+ }
+ finally
+ {
key.Close();
- }
+ }
}
}
}
diff --git a/src/mscorlib/src/Microsoft/Win32/RegistryKey.cs b/src/mscorlib/src/Microsoft/Win32/RegistryKey.cs
index f82b276059..89974e4e7f 100644
--- a/src/mscorlib/src/Microsoft/Win32/RegistryKey.cs
+++ b/src/mscorlib/src/Microsoft/Win32/RegistryKey.cs
@@ -49,23 +49,23 @@
*/
+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;
+
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.
@@ -74,33 +74,32 @@ namespace Microsoft.Win32
* @security(checkDllCalls=off)
* @security(checkClassLinking=on)
*/
- internal sealed class RegistryKey : MarshalByRefObject, IDisposable
+ internal sealed class RegistryKey : MarshalByRefObject, IDisposable
{
-
// 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));
+ 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 const int STATE_DIRTY = 0x0001;
// 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;
+ private const int STATE_WRITEACCESS = 0x0004;
// Indicates if this key is for HKEY_PERFORMANCE_DATA
- private const int STATE_PERF_DATA = 0x0008;
+ private const int STATE_PERF_DATA = 0x0008;
// Names of keys. This array must be in the same order as the HKEY values listed above.
//
@@ -130,20 +129,21 @@ namespace Microsoft.Win32
/**
* 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,
+ 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
+ CheckOpenSubKeyPermission = 12
};
@@ -156,37 +156,45 @@ 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, bool remoteKey, bool isPerfData, RegistryView view)
+ {
this.hkey = hkey;
- this.keyName = "";
+ keyName = "";
this.remoteKey = remoteKey;
- this.regView = view;
- if (systemkey) {
- this.state |= STATE_SYSTEMKEY;
+ regView = view;
+ if (systemkey)
+ {
+ state |= STATE_SYSTEMKEY;
}
- if (writable) {
- this.state |= STATE_WRITEACCESS;
+ if (writable)
+ {
+ state |= STATE_WRITEACCESS;
}
if (isPerfData)
- this.state |= STATE_PERF_DATA;
+ state |= STATE_PERF_DATA;
ValidateKeyView(view);
}
/**
* Closes this key, flushes it to disk if the contents have been modified.
*/
- public void Close() {
+ 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,7 +202,8 @@ namespace Microsoft.Win32
hkey = null;
}
}
- else if (disposing && IsPerfDataKey()) {
+ 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
@@ -207,7 +216,7 @@ namespace Microsoft.Win32
// 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,25 +225,28 @@ 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);
+ 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
// 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);
+ BCLDebug.Correctness(errorCode == 0, "RegDeleteValue failed. Here's your error code: " + errorCode);
}
/**
@@ -253,21 +265,22 @@ namespace Microsoft.Win32
*
* @return the RegistryKey requested.
*/
- internal static RegistryKey GetBaseKey(IntPtr hKey) {
+ internal static RegistryKey GetBaseKey(IntPtr hKey)
+ {
return GetBaseKey(hKey, RegistryView.Default);
}
- internal static RegistryKey GetBaseKey(IntPtr hKey, RegistryView view) {
-
+ 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(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);
- RegistryKey key = new RegistryKey(srh, true, true,false, isPerf, view);
+ RegistryKey key = new RegistryKey(srh, true, true, false, isPerf, view);
key.checkMode = RegistryKeyPermissionCheck.Default;
key.keyName = hkeyNames[index];
return key;
@@ -282,12 +295,13 @@ namespace Microsoft.Win32
*
* @return the Subkey requested, or <b>null</b> if the operation failed.
*/
- public RegistryKey OpenSubKey(string name, bool writable ) {
+ 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);
+ CheckPermission(RegistryInternalCheck.CheckOpenSubKeyWithWritablePermission, name, writable, RegistryKeyPermissionCheck.Default);
SafeRegistryHandle result = null;
int ret = Win32Native.RegOpenKeyEx(hkey,
name,
@@ -295,26 +309,29 @@ namespace Microsoft.Win32
GetRegistryKeyAccess(writable) | (int)regView,
out result);
- if (ret == 0 && !result.IsInvalid) {
- RegistryKey key = new RegistryKey(result, writable, false, remoteKey, false, regView);
+ if (ret == 0 && !result.IsInvalid)
+ {
+ RegistryKey key = new RegistryKey(result, writable, false, remoteKey, false, regView);
key.checkMode = GetSubKeyPermissonCheck(writable);
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) {
+ internal RegistryKey InternalOpenSubKey(String name, bool writable)
+ {
ValidateKeyName(name);
EnsureNotDisposed();
@@ -325,7 +342,8 @@ namespace Microsoft.Win32
GetRegistryKeyAccess(writable) | (int)regView,
out result);
- if (ret == 0 && !result.IsInvalid) {
+ if (ret == 0 && !result.IsInvalid)
+ {
RegistryKey key = new RegistryKey(result, writable, false, remoteKey, false, regView);
key.keyName = keyName + "\\" + name;
return key;
@@ -340,31 +358,33 @@ namespace Microsoft.Win32
*
* @return the Subkey requested, or <b>null</b> if the operation failed.
*/
- public RegistryKey OpenSubKey(String name) {
+ public RegistryKey OpenSubKey(String name)
+ {
return OpenSubKey(name, false);
}
- internal int InternalSubKeyCount() {
- EnsureNotDisposed();
+ 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);
- 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;
+ if (ret != 0)
+ Win32Error(ret, null);
+ return subkeys;
}
/**
@@ -372,24 +392,28 @@ namespace Microsoft.Win32
*
* @return all subkey names.
*/
- public String[] GetSubKeyNames() {
+ public String[] GetSubKeyNames()
+ {
CheckPermission(RegistryInternalCheck.CheckKeyReadPermission, null, false, RegistryKeyPermissionCheck.Default);
return InternalGetSubKeyNames();
}
- internal unsafe String[] InternalGetSubKeyNames() {
+ internal unsafe String[] InternalGetSubKeyNames()
+ {
EnsureNotDisposed();
int subkeys = InternalSubKeyCount();
String[] names = new String[subkeys]; // Returns 0-length array if empty.
- if (subkeys > 0) {
+ if (subkeys > 0)
+ {
char[] name = new char[MaxKeyLength + 1];
-
+
int namelen;
- fixed (char *namePtr = &name[0])
+ fixed (char* namePtr = &name[0])
{
- for (int i=0; i<subkeys; i++) {
+ 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,
@@ -409,7 +433,8 @@ namespace Microsoft.Win32
return names;
}
- internal int InternalValueCount() {
+ internal int InternalValueCount()
+ {
EnsureNotDisposed();
int values = 0;
int junk = 0;
@@ -426,7 +451,7 @@ namespace Microsoft.Win32
null,
null);
if (ret != 0)
- Win32Error(ret, null);
+ Win32Error(ret, null);
return values;
}
@@ -435,20 +460,23 @@ namespace Microsoft.Win32
*
* @return all value names.
*/
- public unsafe String[] GetValueNames() {
+ public unsafe String[] GetValueNames()
+ {
CheckPermission(RegistryInternalCheck.CheckKeyReadPermission, null, false, RegistryKeyPermissionCheck.Default);
EnsureNotDisposed();
int values = InternalValueCount();
String[] names = new String[values];
- if (values > 0) {
+ if (values > 0)
+ {
char[] name = new char[MaxValueLength + 1];
int namelen;
- fixed (char *namePtr = &name[0])
+ fixed (char* namePtr = &name[0])
{
- for (int i=0; i<values; i++) {
+ for (int i = 0; i < values; i++)
+ {
namelen = name.Length;
int ret = Win32Native.RegEnumValue(hkey,
@@ -460,7 +488,8 @@ namespace Microsoft.Win32
null,
null);
- if (ret != 0) {
+ if (ret != 0)
+ {
// ignore ERROR_MORE_DATA if we're querying HKEY_PERFORMANCE_DATA
if (!(IsPerfDataKey() && ret == Win32Native.ERROR_MORE_DATA))
Win32Error(ret, null);
@@ -485,8 +514,9 @@ namespace Microsoft.Win32
*
* @return the data associated with the value.
*/
- public Object GetValue(String name) {
- CheckPermission(RegistryInternalCheck.CheckValueReadPermission, name, false, RegistryKeyPermissionCheck.Default);
+ public Object GetValue(String name)
+ {
+ CheckPermission(RegistryInternalCheck.CheckValueReadPermission, name, false, RegistryKeyPermissionCheck.Default);
return InternalGetValue(name, null, false, true);
}
@@ -505,22 +535,27 @@ namespace Microsoft.Win32
*
* @return the data associated with the value.
*/
- public Object GetValue(String name, Object defaultValue) {
- CheckPermission(RegistryInternalCheck.CheckValueReadPermission, name, false, RegistryKeyPermissionCheck.Default);
+ 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) {
+ 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);
+ 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) {
+ 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();
}
@@ -531,24 +566,30 @@ namespace Microsoft.Win32
int ret = Win32Native.RegQueryValueEx(hkey, name, null, ref type, (byte[])null, ref datasize);
- if (ret != 0) {
- if (IsPerfDataKey()) {
+ 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) {
+ 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)) {
+ else if (size > (Int32.MaxValue / 2))
+ {
// at this point in the loop "size * 2" would cause an overflow
size = Int32.MaxValue;
}
- else {
- size *= 2;
+ else
+ {
+ size *= 2;
}
sizeInput = size;
blob = new byte[size];
@@ -557,199 +598,232 @@ namespace Microsoft.Win32
Win32Error(r, name);
return blob;
}
- else {
+ 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)
+ 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");
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;
- 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;
+ 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 IsSystemKey()
+ {
+ return (state & STATE_SYSTEMKEY) != 0;
}
- private bool IsWritable() {
- return (this.state & STATE_WRITEACCESS) != 0;
+ private bool IsWritable()
+ {
+ return (state & STATE_WRITEACCESS) != 0;
}
- private bool IsPerfDataKey() {
- return (this.state & STATE_PERF_DATA) != 0;
+ private bool IsPerfDataKey()
+ {
+ return (state & STATE_PERF_DATA) != 0;
}
- private void SetDirty() {
- this.state |= STATE_DIRTY;
+ private void SetDirty()
+ {
+ state |= STATE_DIRTY;
}
/**
@@ -758,15 +832,18 @@ namespace Microsoft.Win32
* @param name Name of value to store data in.
* @param value Data to store.
*/
- public void SetValue(String name, Object value) {
+ 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)
+ public unsafe void SetValue(String name, Object value, RegistryValueKind valueKind)
+ {
+ if (value == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
- if (name != null && name.Length > MaxValueLength) {
+ if (name != null && name.Length > MaxValueLength)
+ {
throw new ArgumentException(Environment.GetResourceString("Arg_RegValStrLenBug"));
}
@@ -775,32 +852,37 @@ namespace Microsoft.Win32
EnsureWriteable();
- if (!remoteKey && ContainsRegistryValue(name)) { // Existing key
+ 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);
+ }
+ else
+ { // Creating a new value
+ CheckPermission(RegistryInternalCheck.CheckValueCreatePermission, name, false, RegistryKeyPermissionCheck.Default);
}
- if (valueKind == RegistryValueKind.Unknown) {
+ 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);
}
int ret = 0;
- try {
- switch (valueKind) {
+ try
+ {
+ switch (valueKind)
+ {
case RegistryValueKind.ExpandString:
case RegistryValueKind.String:
{
String data = value.ToString();
- ret = Win32Native.RegSetValueEx(hkey,
- name,
- 0,
- valueKind,
- data,
- checked(data.Length * 2 + 2));
+ ret = Win32Native.RegSetValueEx(hkey,
+ name,
+ 0,
+ valueKind,
+ data,
+ checked(data.Length * 2 + 2));
break;
}
@@ -813,30 +895,34 @@ namespace Microsoft.Win32
// 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);
+ for (int i = 0; i < dataStrings.Length; i++)
+ {
+ if (dataStrings[i] == null)
+ {
+ ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSetStrArrNull);
}
- sizeInBytes = checked(sizeInBytes + 2);
+ 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);
+ fixed (byte* b = basePtr)
+ {
+ IntPtr currentPtr = new IntPtr((void*)b);
// Write out the strings...
//
- for (int i=0; i<dataStrings.Length; i++) {
+ 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);
- }
-
+ 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,
@@ -850,11 +936,11 @@ namespace Microsoft.Win32
case RegistryValueKind.None:
case RegistryValueKind.Binary:
- byte[] dataBytes = (byte[]) value;
+ byte[] dataBytes = (byte[])value;
ret = Win32Native.RegSetValueEx(hkey,
name,
0,
- (valueKind == RegistryValueKind.None ? Win32Native.REG_NONE: RegistryValueKind.Binary),
+ (valueKind == RegistryValueKind.None ? Win32Native.REG_NONE : RegistryValueKind.Binary),
dataBytes,
dataBytes.Length);
break;
@@ -888,34 +974,40 @@ namespace Microsoft.Win32
}
}
}
- catch (OverflowException) {
+ catch (OverflowException)
+ {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSetMismatchedKind);
}
- catch (InvalidOperationException) {
- ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSetMismatchedKind);
+ catch (InvalidOperationException)
+ {
+ ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSetMismatchedKind);
}
- catch (FormatException) {
- ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSetMismatchedKind);
+ catch (FormatException)
+ {
+ ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSetMismatchedKind);
}
- catch (InvalidCastException) {
- ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSetMismatchedKind);
+ catch (InvalidCastException)
+ {
+ ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSetMismatchedKind);
}
- if (ret == 0) {
+ if (ret == 0)
+ {
SetDirty();
}
else
Win32Error(ret, null);
-
}
- private RegistryValueKind CalculateValueKind(Object value) {
+ 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) {
+ else if (value is Array)
+ {
if (value is byte[])
return RegistryValueKind.Binary;
else if (value is String[])
@@ -932,7 +1024,8 @@ namespace Microsoft.Win32
*
* @return a string representing the key.
*/
- public override String ToString() {
+ public override String ToString()
+ {
EnsureNotDisposed();
return keyName;
}
@@ -944,8 +1037,10 @@ 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));
@@ -965,14 +1060,15 @@ namespace Microsoft.Win32
* 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;
+ if (!IsPerfDataKey())
+ {
+ hkey.SetHandleAsInvalid();
+ hkey = null;
}
- goto default;
+ goto default;
case Win32Native.ERROR_FILE_NOT_FOUND:
- throw new IOException(Environment.GetResourceString("Arg_RegKeyNotFound"), errorCode);
+ throw new IOException(Environment.GetResourceString("Arg_RegKeyNotFound"), errorCode);
default:
throw new IOException(Win32Native.GetMessage(errorCode), errorCode);
@@ -981,7 +1077,7 @@ namespace Microsoft.Win32
internal static String FixupName(String name)
{
- BCLDebug.Assert(name!=null,"[FixupName]name!=null");
+ BCLDebug.Assert(name != null, "[FixupName]name!=null");
if (name.IndexOf('\\') == -1)
return name;
@@ -997,7 +1093,7 @@ namespace Microsoft.Win32
private static void FixupPath(StringBuilder path)
{
Contract.Requires(path != null);
- int length = path.Length;
+ int length = path.Length;
bool fixup = false;
char markerChar = (char)0xFFFF;
@@ -1011,14 +1107,13 @@ namespace Microsoft.Win32
{
if (path[i] == '\\')
{
- path[i] = markerChar;
- i++;
- fixup = true;
+ path[i] = markerChar;
+ i++;
+ fixup = true;
}
else
- break;
+ break;
}
-
}
i++;
}
@@ -1029,7 +1124,7 @@ namespace Microsoft.Win32
int j = 0;
while (i < length)
{
- if(path[i] == markerChar)
+ if (path[i] == markerChar)
{
i++;
continue;
@@ -1040,7 +1135,6 @@ namespace Microsoft.Win32
}
path.Length += j - i;
}
-
}
private void CheckPermission(RegistryInternalCheck check, string item, bool subKeyWritable, RegistryKeyPermissionCheck subKeyCheck)
@@ -1048,60 +1142,75 @@ namespace Microsoft.Win32
// 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 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) {
+ 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) {
+ private static int GetRegistryKeyAccess(bool isWritable)
+ {
int winAccess;
- if (!isWritable) {
+ if (!isWritable)
+ {
winAccess = Win32Native.KEY_READ;
}
- else {
+ else
+ {
winAccess = Win32Native.KEY_READ | Win32Native.KEY_WRITE;
}
return winAccess;
}
- private RegistryKeyPermissionCheck GetSubKeyPermissonCheck(bool subkeyWritable) {
- if( checkMode == RegistryKeyPermissionCheck.Default) {
+ private RegistryKeyPermissionCheck GetSubKeyPermissonCheck(bool subkeyWritable)
+ {
+ if (checkMode == RegistryKeyPermissionCheck.Default)
+ {
return checkMode;
- }
-
- if(subkeyWritable) {
+ }
+
+ if (subkeyWritable)
+ {
return RegistryKeyPermissionCheck.ReadWriteSubTree;
}
- else {
+ else
+ {
return RegistryKeyPermissionCheck.ReadSubTree;
}
}
- static private void ValidateKeyName(string name) {
+ static private void ValidateKeyName(string name)
+ {
Contract.Ensures(name != null);
- if (name == null) {
+ 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 +1220,35 @@ 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) {
+ 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 {
+ internal enum RegistryValueOptions
+ {
None = 0,
DoNotExpandEnvironmentNames = 1
- }
+ }
// the name for this API is meant to mimic FileMode, which has similar values
- internal enum RegistryKeyPermissionCheck {
+ 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..6e2a4f3b6e 100644
--- a/src/mscorlib/src/Microsoft/Win32/RegistryValueKind.cs
+++ b/src/mscorlib/src/Microsoft/Win32/RegistryValueKind.cs
@@ -3,16 +3,18 @@
// 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, // REG_NONE is defined as zero but BCL
- None = unchecked((int)0xFFFFFFFF), // mistakingly overrode this value.
+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.
}
diff --git a/src/mscorlib/src/Microsoft/Win32/RegistryView.cs b/src/mscorlib/src/Microsoft/Win32/RegistryView.cs
index 302a603e0c..e4158656a8 100644
--- a/src/mscorlib/src/Microsoft/Win32/RegistryView.cs
+++ b/src/mscorlib/src/Microsoft/Win32/RegistryView.cs
@@ -8,12 +8,15 @@
// 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
+
+using System;
+
+namespace Microsoft.Win32
+{
+ 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..64dbb2c638 100644
--- a/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeRegistryHandle.cs
+++ b/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeRegistryHandle.cs
@@ -8,22 +8,27 @@
// 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;
- internal sealed class SafeRegistryHandle : SafeHandleZeroOrMinusOneIsInvalid {
- internal SafeRegistryHandle() : base(true) {}
+using System;
+using System.Security;
+using System.Runtime.InteropServices;
+using System.Runtime.CompilerServices;
+using System.Runtime.ConstrainedExecution;
+using System.Runtime.Versioning;
- public SafeRegistryHandle(IntPtr preexistingHandle, bool ownsHandle) : base(ownsHandle) {
+namespace Microsoft.Win32.SafeHandles
+{
+ internal sealed class SafeRegistryHandle : SafeHandleZeroOrMinusOneIsInvalid
+ {
+ internal SafeRegistryHandle() : base(true) { }
+
+ 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..80c8deb1d3 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,7 +52,8 @@ namespace Microsoft.Win32.SafeHandles
throw new NotImplementedException();
}
- public override bool IsInvalid {
+ public override bool IsInvalid
+ {
get { return handle == new IntPtr(-1); }
}
}
@@ -59,11 +61,12 @@ namespace Microsoft.Win32.SafeHandles
// Class of critical handle which uses 0 or -1 as an invalid handle.
public abstract class CriticalHandleZeroOrMinusOneIsInvalid : CriticalHandle
{
- protected CriticalHandleZeroOrMinusOneIsInvalid() : base(IntPtr.Zero)
+ protected CriticalHandleZeroOrMinusOneIsInvalid() : base(IntPtr.Zero)
{
}
- public override bool IsInvalid {
+ public override bool IsInvalid
+ {
get { return handle.IsNull() || handle == new IntPtr(-1); }
}
}
@@ -71,11 +74,12 @@ namespace Microsoft.Win32.SafeHandles
// Class of critical handle which uses only -1 as an invalid handle.
public abstract class CriticalHandleMinusOneIsInvalid : CriticalHandle
{
- protected CriticalHandleMinusOneIsInvalid() : base(new IntPtr(-1))
+ 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..6f618c2f64 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,7 +294,8 @@ namespace Microsoft.Win32 {
// [42-43] WORD wMilliseconds;
// } REG_TZI_FORMAT;
//
- if (bytes == null || bytes.Length != 44) {
+ if (bytes == null || bytes.Length != 44)
+ {
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidREG_TZI_FORMAT"), nameof(bytes));
}
Bias = BitConverter.ToInt32(bytes, 0);
@@ -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);
}
}
- [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,22 +800,22 @@ 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)]
+ [DllImport(KERNEL32, CharSet = CharSet.Auto, BestFitMapping = false)]
internal extern static int GetComputerName([Out]StringBuilder nameBuffer, ref int bufferSize);
[DllImport(OLE32)]
@@ -810,136 +831,136 @@ 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)]
diff --git a/src/mscorlib/src/System/Action.cs b/src/mscorlib/src/System/Action.cs
index 23c7e93194..b82c14d9dc 100644
--- a/src/mscorlib/src/System/Action.cs
+++ b/src/mscorlib/src/System/Action.cs
@@ -4,12 +4,12 @@
namespace System
{
- public delegate void Action<in T>(T obj);
+ 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 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);
@@ -17,10 +17,10 @@ namespace System
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 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);
@@ -29,7 +29,7 @@ namespace System
public delegate int Comparison<in T>(T x, T y);
- public delegate TOutput Converter<in TInput, out TOutput>(TInput input);
+ public delegate TOutput Converter<in TInput, out TOutput>(TInput input);
- public delegate bool Predicate<in T>(T obj);
+ 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 b3dd4a780f..3ee9ec5180 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,7 +48,7 @@ namespace System {
BindingFlags bindingAttr,
Binder binder,
Object[] args,
- CultureInfo culture)
+ CultureInfo culture)
{
return CreateInstance(type, bindingAttr, binder, args, culture, null);
}
@@ -68,11 +69,12 @@ namespace System {
throw new NotSupportedException(Environment.GetResourceString("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(Environment.GetResourceString("NotSupported_ActivAttr"));
}
RuntimeType rt = type.UnderlyingSystemType as RuntimeType;
@@ -81,7 +83,7 @@ namespace System {
throw new ArgumentException(Environment.GetResourceString("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);
@@ -122,7 +124,7 @@ namespace System {
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return CreateInstance(assemblyName,
- typeName,
+ typeName,
false,
Activator.ConstructorDefault,
null,
@@ -137,11 +139,11 @@ namespace System {
static public ObjectHandle CreateInstance(String assemblyName,
String typeName,
Object[] activationAttributes)
-
+
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return CreateInstance(assemblyName,
- typeName,
+ typeName,
false,
Activator.ConstructorDefault,
null,
@@ -151,7 +153,7 @@ namespace System {
null,
ref stackMark);
}
-
+
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
static public Object CreateInstance(Type type, bool nonPublic)
{
@@ -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,
@@ -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(Environment.GetResourceString("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..3a3b08dc04 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,7 +32,6 @@ namespace System
[DebuggerDisplay("Count = {InnerExceptionCount}")]
public class AggregateException : Exception
{
-
private ReadOnlyCollection<Exception> m_innerExceptions; // Complete set of exceptions.
/// <summary>
@@ -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)))
{
}
@@ -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..b8d3076e8c 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;
@@ -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)
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 c6fa7d45bf..9a3d70ad11 100644
--- a/src/mscorlib/src/System/AppDomain.cs
+++ b/src/mscorlib/src/System/AppDomain.cs
@@ -42,13 +42,15 @@ namespace System
private String _Name;
private Assembly _RequestingAssembly;
- public String Name {
- get {
+ public String Name
+ {
+ get
+ {
return _Name;
}
}
- public Assembly RequestingAssembly
+ public Assembly RequestingAssembly
{
get
{
@@ -72,8 +74,10 @@ namespace System
{
private Assembly _LoadedAssembly;
- public Assembly LoadedAssembly {
- get {
+ public Assembly LoadedAssembly
+ {
+ get
+ {
return _LoadedAssembly;
}
}
@@ -106,62 +110,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);
+ 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 +179,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;
@@ -248,25 +251,25 @@ namespace System
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";
@@ -279,16 +282,16 @@ namespace System
[Flags]
private enum APPX_FLAGS
{
- APPX_FLAGS_INITIALIZED = 0x01,
+ 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_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_API_CHECK = 0x10,
+ APPX_FLAGS_API_CHECK = 0x10,
}
private static APPX_FLAGS Flags
@@ -460,7 +463,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)
{
@@ -600,17 +603,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();
}
@@ -647,8 +653,10 @@ namespace System
runtimeSuppliedHomogenousGrantSet);
}
- public AppDomainManager DomainManager {
- get {
+ public AppDomainManager DomainManager
+ {
+ get
+ {
return _domainManager;
}
}
@@ -656,7 +664,7 @@ namespace System
public ObjectHandle CreateInstance(String assemblyName,
String typeName)
-
+
{
// jit does not check for that, so we should do it ...
if (this == null)
@@ -672,7 +680,8 @@ namespace System
public static AppDomain CurrentDomain
{
- get {
+ get
+ {
Contract.Ensures(Contract.Result<AppDomain>() != null);
return Thread.GetDomain();
}
@@ -680,7 +689,8 @@ namespace System
public String BaseDirectory
{
- get {
+ get
+ {
return FusionStore.ApplicationBase;
}
}
@@ -690,26 +700,29 @@ namespace System
StringBuilder sb = StringBuilderCache.Acquire();
String fn = nGetFriendlyName();
- if (fn != null) {
+ if (fn != null)
+ {
sb.Append(Environment.GetResourceString("Loader_Name") + fn);
sb.Append(Environment.NewLine);
}
- if(_Policies == null || _Policies.Length == 0)
+ if (_Policies == null || _Policies.Length == 0)
sb.Append(Environment.GetResourceString("Loader_NoContextPolicies")
+ Environment.NewLine);
- else {
+ else
+ {
sb.Append(Environment.GetResourceString("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();
@@ -722,14 +735,16 @@ 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)
@@ -737,7 +752,8 @@ namespace System
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_SetData_OnlyOnce"));
}
- lock (((ICollection)LocalStore).SyncRoot) {
+ lock (((ICollection)LocalStore).SyncRoot)
+ {
LocalStore[name] = data;
}
}
@@ -745,19 +761,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)
@@ -765,26 +782,29 @@ 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() {
+ private AppDomain()
+ {
throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_Constructor));
}
@@ -816,13 +836,13 @@ namespace System
if (value != null)
{
RuntimeHelpers.PrepareContractedDelegate(value);
- lock(this)
+ lock (this)
_processExit += value;
}
}
remove
{
- lock(this)
+ lock (this)
_processExit -= value;
}
}
@@ -835,13 +855,13 @@ namespace System
if (value != null)
{
RuntimeHelpers.PrepareContractedDelegate(value);
- lock(this)
+ lock (this)
_domainUnload += value;
}
}
remove
{
- lock(this)
+ lock (this)
_domainUnload -= value;
}
}
@@ -854,13 +874,13 @@ namespace System
if (value != null)
{
RuntimeHelpers.PrepareContractedDelegate(value);
- lock(this)
+ lock (this)
_unhandledException += value;
}
}
remove
{
- lock(this)
+ lock (this)
_unhandledException -= value;
}
}
@@ -876,13 +896,13 @@ namespace System
if (value != null)
{
RuntimeHelpers.PrepareContractedDelegate(value);
- lock(this)
+ lock (this)
_firstChanceException += value;
}
}
remove
{
- lock(this)
+ lock (this)
_firstChanceException -= value;
}
}
@@ -890,22 +910,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)
@@ -914,7 +936,7 @@ namespace System
return null;
}
-
+
// This method is called by the VM
private RuntimeAssembly OnTypeResolveEvent(RuntimeAssembly assembly, String typeName)
{
@@ -924,7 +946,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)
@@ -946,13 +969,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;
}
@@ -966,8 +990,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;
}
@@ -991,10 +1016,12 @@ namespace System
private Dictionary<String, Object> LocalStore
{
- get {
+ get
+ {
if (_LocalStore != null)
return _LocalStore;
- else {
+ else
+ {
_LocalStore = new Dictionary<String, Object>();
return _LocalStore;
}
@@ -1011,7 +1038,7 @@ namespace System
if (info.ApplicationBase == null)
{
- info.SetupDefaults(RuntimeEnvironment.GetModuleFileName(), imageLocationAlreadyNormalized : true);
+ info.SetupDefaults(RuntimeEnvironment.GetModuleFileName(), imageLocationAlreadyNormalized: true);
}
nCreateContext();
@@ -1024,11 +1051,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);
}
}
@@ -1051,8 +1078,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);
@@ -1065,37 +1092,36 @@ 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
private static Object Setup(Object arg)
@@ -1103,24 +1129,24 @@ namespace System
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++)
{
@@ -1139,55 +1165,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(Environment.GetResourceString("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;
+ 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");
}
}
- 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);
@@ -1213,10 +1239,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;
@@ -1278,7 +1304,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();
@@ -1298,7 +1324,6 @@ namespace System
JitHelpers.GetObjectHandleOnStack(ref stackEvidence),
creatorsSecurityDescriptor,
publishAppDomain);
-
}
[SuppressUnmanagedCodeSecurity]
@@ -1321,8 +1346,9 @@ namespace System
public AppDomainSetup SetupInformation
{
- get {
- return new AppDomainSetup(FusionStore,true);
+ get
+ {
+ return new AppDomainSetup(FusionStore, true);
}
}
@@ -1331,7 +1357,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);
@@ -1356,14 +1382,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..1c7fb08d98 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,13 +48,15 @@ namespace System
}
}
- internal static AppDomainManager CurrentAppDomainManager {
- get {
+ internal static AppDomainManager CurrentAppDomainManager
+ {
+ get
+ {
return AppDomain.CurrentDomain.DomainManager;
}
}
- public virtual bool CheckSecuritySettings (SecurityState state)
+ 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 284650480b..a8a1d09a5f 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,25 +31,25 @@ 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";
@@ -68,7 +65,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;
@@ -106,7 +103,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 +150,7 @@ namespace System
#endif
}
- else
+ else
_LoaderOptimization = LoaderOptimization.NotSpecified;
}
@@ -161,20 +159,23 @@ 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;
@@ -182,8 +183,9 @@ namespace System
internal string[] Value
{
- get {
- if( _Entries == null)
+ get
+ {
+ if (_Entries == null)
_Entries = new String[(int)LoaderInformation.LoaderMaximum];
return _Entries;
}
@@ -191,7 +193,7 @@ namespace System
internal String GetUnsecureApplicationBase()
{
- return Value[(int) LoaderInformation.ApplicationBaseValue];
+ return Value[(int)LoaderInformation.ApplicationBaseValue];
}
public string AppDomainManagerAssembly
@@ -209,18 +211,20 @@ namespace System
public String ApplicationBase
{
[Pure]
- get {
+ get
+ {
return VerifyDir(GetUnsecureApplicationBase(), false);
}
- set {
- Value[(int) LoaderInformation.ApplicationBaseValue] = NormalizePath(value, false);
+ set
+ {
+ Value[(int)LoaderInformation.ApplicationBaseValue] = NormalizePath(value, false);
}
}
private String NormalizePath(String path, bool useAppBase)
{
- if(path == null)
+ if (path == null)
return null;
// If we add very long file name support ("\\?\") to the Path class then this is unnecesary,
@@ -245,18 +249,20 @@ namespace System
#endif // !PLATFORM_UNIX
if ((len > 7) &&
- (String.Compare( path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0)) {
+ (String.Compare(path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0))
+ {
int trim;
-
- if (path[6] == '\\') {
- if ((path[7] == '\\') || (path[7] == '/')) {
+ 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] == '/')) )
+ if ((len > 8) &&
+ ((path[8] == '\\') || (path[8] == '/')))
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPathChars"));
-
+
// file:\\\ means local path
else
#if !PLATFORM_UNIX
@@ -271,7 +277,8 @@ namespace System
}
// file:\\ means remote server
- else {
+ else
+ {
trim = 5;
#if !PLATFORM_UNIX
UNCpath = true;
@@ -292,18 +299,21 @@ namespace System
#endif // !PLATFORM_UNIX
// remote
- else {
+ else
+ {
// file://\\remote
- if ( (len > 8) && (path[7] == '\\') && (path[8] == '\\') )
+ if ((len > 8) && (path[7] == '\\') && (path[8] == '\\'))
trim = 7;
- else { // file://remote
+ 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++) {
+ for (int i = 0; i < len; i++)
+ {
char c = path[i];
if (c == '/')
winPathBuilder.Append('\\');
@@ -327,35 +337,36 @@ namespace System
// UNC
if (UNCpath ||
- ( (len > 1) &&
- ( (path[0] == '/') || (path[0] == '\\') ) &&
- ( (path[1] == '/') || (path[1] == '\\') ) ))
+ ((len > 1) &&
+ ((path[0] == '/') || (path[0] == '\\')) &&
+ ((path[1] == '/') || (path[1] == '\\'))))
localPath = false;
- else {
+ 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] == '\\') ))
+ (len > colon + 1) &&
+ ((path[colon] == '/') || (path[colon] == '\\')) &&
+ ((path[colon + 1] == '/') || (path[colon + 1] == '\\')))
localPath = false;
else
localPath = true;
}
- if (localPath)
+ if (localPath)
#else
if ( (len == 1) ||
( (path[0] != '/') && (path[0] != '\\') ) )
#endif // !PLATFORM_UNIX
{
-
if (useAppBase &&
- ( (len == 1) || (path[1] != ':') )) {
- String appBase = Value[(int) LoaderInformation.ApplicationBaseValue];
+ ((len == 1) || (path[1] != ':')))
+ {
+ String appBase = Value[(int)LoaderInformation.ApplicationBaseValue];
if ((appBase == null) || (appBase.Length == 0))
throw new MemberAccessException(Environment.GetResourceString("AppDomain_AppBaseNotSet"));
@@ -363,11 +374,13 @@ namespace System
StringBuilder result = StringBuilderCache.Acquire();
bool slash = false;
- if ((path[0] == '/') || (path[0] == '\\')) {
+ 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
+ if (pathRoot.Length == 0)
+ { // URL
int index = appBase.IndexOf(":/", StringComparison.Ordinal);
if (index == -1)
index = appBase.IndexOf(":\\", StringComparison.Ordinal);
@@ -376,11 +389,11 @@ namespace System
int urlLen = appBase.Length;
for (index += 1;
(index < urlLen) && ((appBase[index] == '/') || (appBase[index] == '\\'));
- index++);
+ index++) ;
// Now find the next slash to get domain name
- for(; (index < urlLen) && (appBase[index] != '/') && (appBase[index] != '\\');
- index++);
+ for (; (index < urlLen) && (appBase[index] != '/') && (appBase[index] != '\\');
+ index++) ;
pathRoot = appBase.Substring(0, index);
}
@@ -394,8 +407,10 @@ namespace System
// Make sure there's a slash separator (and only one)
int aLen = result.Length - 1;
if ((result[aLen] != '/') &&
- (result[aLen] != '\\')) {
- if (!slash) {
+ (result[aLen] != '\\'))
+ {
+ if (!slash)
+ {
#if !PLATFORM_UNIX
if (appBase.IndexOf(":/", StringComparison.Ordinal) == -1)
result.Append('\\');
@@ -419,12 +434,14 @@ namespace System
public String ConfigurationFile
{
- get {
- return VerifyDir(Value[(int) LoaderInformation.ConfigurationFileValue], true);
+ get
+ {
+ return VerifyDir(Value[(int)LoaderInformation.ConfigurationFileValue], true);
}
- set {
- Value[(int) LoaderInformation.ConfigurationFileValue] = value;
+ set
+ {
+ Value[(int)LoaderInformation.ConfigurationFileValue] = value;
}
}
@@ -433,7 +450,7 @@ namespace System
if (_ConfigurationBytes == null)
return null;
- return (byte[]) _ConfigurationBytes.Clone();
+ return (byte[])_ConfigurationBytes.Clone();
}
// only needed by AppDomain.Setup(). Not really needed by users.
@@ -450,10 +467,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
@@ -464,25 +482,29 @@ 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 != null)
+ {
if (dir.Length == 0)
dir = null;
- else {
+ else
+ {
if (normalize)
dir = NormalizePath(dir, true);
}
@@ -493,33 +515,39 @@ namespace System
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;
}
}
@@ -547,36 +575,40 @@ 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 {
+ 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..b8b6150c9f 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")) {
+ internal class AppDomainUnloadedException : SystemException
+ {
+ public AppDomainUnloadedException()
+ : base(Environment.GetResourceString("Arg_AppDomainUnloadedException"))
+ {
SetErrorCode(__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/ArgIterator.cs b/src/mscorlib/src/System/ArgIterator.cs
index 83a60b95e1..394d579b94 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);
@@ -145,18 +145,18 @@ namespace System {
throw new PlatformNotSupportedException(); //The JIT requires work to enable ArgIterator see: https://github.com/dotnet/coreclr/issues/9204.
}
- public void End()
- {
+ public void End()
+ {
throw new PlatformNotSupportedException(); //The JIT requires work to enable ArgIterator see: https://github.com/dotnet/coreclr/issues/9204.
}
- public override bool Equals(Object o)
- {
+ 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 int GetHashCode()
- {
+ {
throw new PlatformNotSupportedException(); //The JIT requires work to enable ArgIterator see: https://github.com/dotnet/coreclr/issues/9204.
}
@@ -178,7 +178,7 @@ namespace System {
}
public int GetRemainingCount()
- {
+ {
throw new PlatformNotSupportedException(); //The JIT requires work to enable ArgIterator see: https://github.com/dotnet/coreclr/issues/9204.
}
#endif //VARARGS_ENABLED
diff --git a/src/mscorlib/src/System/ArgumentOutOfRangeException.cs b/src/mscorlib/src/System/ArgumentOutOfRangeException.cs
index 59a8434089..a20b43ff1f 100644
--- a/src/mscorlib/src/System/ArgumentOutOfRangeException.cs
+++ b/src/mscorlib/src/System/ArgumentOutOfRangeException.cs
@@ -11,24 +11,27 @@
**
=============================================================================*/
-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");
return _rangeMessage;
@@ -37,66 +40,78 @@ namespace System {
// Creates a new ArgumentOutOfRangeException with its message
// string set to a default message explaining an argument was out of range.
- public ArgumentOutOfRangeException()
- : base(RangeMessage) {
+ public ArgumentOutOfRangeException()
+ : base(RangeMessage)
+ {
SetErrorCode(__HResults.COR_E_ARGUMENTOUTOFRANGE);
}
-
- public ArgumentOutOfRangeException(String paramName)
- : base(RangeMessage, paramName) {
+
+ public ArgumentOutOfRangeException(String paramName)
+ : base(RangeMessage, paramName)
+ {
SetErrorCode(__HResults.COR_E_ARGUMENTOUTOFRANGE);
}
-
- public ArgumentOutOfRangeException(String paramName, String message)
- : base(message, paramName) {
+
+ public ArgumentOutOfRangeException(String paramName, String message)
+ : base(message, paramName)
+ {
SetErrorCode(__HResults.COR_E_ARGUMENTOUTOFRANGE);
}
- public ArgumentOutOfRangeException(String message, Exception innerException)
- : base(message, innerException) {
+ public ArgumentOutOfRangeException(String message, Exception innerException)
+ : base(message, innerException)
+ {
SetErrorCode(__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);
}
-
- public override String Message {
- get {
+
+ public override String Message
+ {
+ get
+ {
String s = base.Message;
- if (m_actualValue != null) {
+ if (m_actualValue != null)
+ {
String valueMessage = Environment.GetResourceString("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/Array.cs b/src/mscorlib/src/System/Array.cs
index 23989f30fb..6e7615d251 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,7 @@ namespace System {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
Contract.EndContractBlock();
- this.CopyTo(array, (int) index);
+ this.CopyTo(array, (int)index);
}
[Pure]
@@ -972,7 +1022,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 +1063,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 +1122,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 +1200,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 +1289,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 +1349,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 +1386,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 +1403,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 +1415,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 +1439,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 +1469,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 +1505,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 +1553,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 +1617,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 +1654,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 +1665,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 +1717,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 +1781,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 +1808,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 +1826,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 +1840,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 +1910,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 +1936,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 +1956,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 +1972,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 +2001,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 +2086,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 +2127,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 +2168,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 +2189,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 +2241,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 +2292,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 +2327,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 +2362,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 +2376,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 +2393,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 +2430,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 +2466,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 +2496,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 +2518,10 @@ namespace System {
return MemberwiseClone();
}
- public bool MoveNext() {
- if (_complete) {
+ public bool MoveNext()
+ {
+ if (_complete)
+ {
index = endIndex;
return false;
}
@@ -2334,25 +2529,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 +2592,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 +2615,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 +2624,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 +2635,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 +2718,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 +2728,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;
}
diff --git a/src/mscorlib/src/System/ArraySegment.cs b/src/mscorlib/src/System/ArraySegment.cs
index 03556e492a..98e0b7901e 100644
--- a/src/mscorlib/src/System/ArraySegment.cs
+++ b/src/mscorlib/src/System/ArraySegment.cs
@@ -59,7 +59,7 @@ namespace System
{
get
{
- Debug.Assert( (null == _array && 0 == _offset && 0 == _count)
+ Debug.Assert((null == _array && 0 == _offset && 0 == _count)
|| (null != _array && _offset >= 0 && _count >= 0 && _offset + _count <= _array.Length),
"ArraySegment is invalid");
@@ -78,7 +78,7 @@ namespace System
// 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)
+ Debug.Assert((null == _array && 0 == _offset && 0 == _count)
|| (null != _array && _offset >= 0 && _count >= 0 && _offset + _count <= _array.Length),
"ArraySegment is invalid");
@@ -97,7 +97,7 @@ namespace System
// 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)
+ Debug.Assert((null == _array && 0 == _offset && 0 == _count)
|| (null != _array && _offset >= 0 && _count >= 0 && _offset + _count <= _array.Length),
"ArraySegment is invalid");
@@ -120,11 +120,11 @@ 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();
@@ -138,17 +138,17 @@ namespace System
else
return false;
}
-
+
public bool Equals(ArraySegment<T> obj)
{
return obj._array == _array && obj._offset == _offset && obj._count == _count;
}
-
+
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);
@@ -161,7 +161,7 @@ namespace System
{
if (_array == null)
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_NullArray);
- if (index < 0 || index >= _count)
+ if (index < 0 || index >= _count)
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
Contract.EndContractBlock();
diff --git a/src/mscorlib/src/System/Attribute.cs b/src/mscorlib/src/System/Attribute.cs
index b44e13f959..7ffbedf78d 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];
@@ -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"));
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"));
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)
@@ -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,7 +568,7 @@ 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"));
@@ -578,7 +578,7 @@ namespace System {
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[];
@@ -595,9 +595,9 @@ namespace System {
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"));
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,7 +632,7 @@ 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"));
}
@@ -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)
@@ -716,7 +716,7 @@ namespace System {
throw new ArgumentException(Environment.GetResourceString("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;
@@ -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)
@@ -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;
@@ -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/AttributeUsageAttribute.cs b/src/mscorlib/src/System/AttributeUsageAttribute.cs
index 33f7fd805e..22cc54864c 100644
--- a/src/mscorlib/src/System/AttributeUsageAttribute.cs
+++ b/src/mscorlib/src/System/AttributeUsageAttribute.cs
@@ -10,44 +10,48 @@
**
**
===========================================================*/
-namespace System {
- using System.Reflection;
+using System.Reflection;
+
+namespace System
+{
/* By default, attributes are inherited and multiple attributes are not allowed */
-[Serializable]
+ [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) {
+ //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;
}
- internal AttributeUsageAttribute(AttributeTargets validOn, bool allowMultiple, bool inherited) {
- m_attributeTarget = validOn;
- m_allowMultiple = allowMultiple;
- m_inherited = inherited;
- }
-
-
- //Properties
- public AttributeTargets ValidOn
+
+
+ //Properties
+ public AttributeTargets ValidOn
{
- get{ return m_attributeTarget; }
+ get { return m_attributeTarget; }
}
-
- public bool AllowMultiple
+
+ public bool AllowMultiple
{
get { return m_allowMultiple; }
set { m_allowMultiple = value; }
}
-
- public bool Inherited
+
+ 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..13d9556f1d 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,23 +20,26 @@ 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")) {
+ public BadImageFormatException()
+ : base(Environment.GetResourceString("Arg_BadImageFormatException"))
+ {
SetErrorCode(__HResults.COR_E_BADIMAGEFORMAT);
}
-
- public BadImageFormatException(String message)
- : base(message) {
+
+ public BadImageFormatException(String message)
+ : base(message)
+ {
SetErrorCode(__HResults.COR_E_BADIMAGEFORMAT);
}
-
- public BadImageFormatException(String message, Exception inner)
- : base(message, inner) {
+
+ public BadImageFormatException(String message, Exception inner)
+ : base(message, inner)
+ {
SetErrorCode(__HResults.COR_E_BADIMAGEFORMAT);
}
@@ -46,15 +49,17 @@ namespace System {
_fileName = fileName;
}
- public BadImageFormatException(String message, String fileName, Exception inner)
- : base(message, inner) {
+ public BadImageFormatException(String message, String fileName, Exception inner)
+ : base(message, inner)
+ {
SetErrorCode(__HResults.COR_E_BADIMAGEFORMAT);
_fileName = fileName;
}
public override String Message
{
- get {
+ get
+ {
SetMessageField();
return _message;
}
@@ -62,7 +67,8 @@ 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");
@@ -72,7 +78,8 @@ namespace System {
}
}
- public String FileName {
+ public String FileName
+ {
get { return _fileName; }
}
@@ -82,7 +89,7 @@ namespace System {
if (_fileName != null && _fileName.Length != 0)
s += Environment.NewLine + Environment.GetResourceString("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;
}
@@ -125,17 +132,19 @@ namespace System {
{
SetErrorCode(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..304021674a 100644
--- a/src/mscorlib/src/System/BitConverter.cs
+++ b/src/mscorlib/src/System/BitConverter.cs
@@ -11,8 +11,9 @@
**
**
===========================================================*/
-namespace System {
-
+
+namespace System
+{
using System;
using System.Runtime.CompilerServices;
using System.Diagnostics;
@@ -25,8 +26,8 @@ namespace System {
// 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.
@@ -37,15 +38,16 @@ namespace System {
#endif
// Converts a byte into an array of bytes with length one.
- public static byte[] GetBytes(bool value) {
+ 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)Boolean.True : (byte)Boolean.False);
return r;
}
-
+
// Converts a char into an array of bytes with length two.
public static byte[] GetBytes(char value)
{
@@ -54,7 +56,7 @@ namespace System {
return GetBytes((short)value);
}
-
+
// Converts a short into an array of bytes with length
// two.
public unsafe static byte[] GetBytes(short value)
@@ -63,7 +65,7 @@ namespace System {
Contract.Ensures(Contract.Result<byte[]>().Length == 2);
byte[] bytes = new byte[2];
- fixed(byte* b = &bytes[0])
+ fixed (byte* b = &bytes[0])
*((short*)b) = value;
return bytes;
}
@@ -76,11 +78,11 @@ namespace System {
Contract.Ensures(Contract.Result<byte[]>().Length == 4);
byte[] bytes = new byte[4];
- fixed(byte* b = &bytes[0])
+ fixed (byte* b = &bytes[0])
*((int*)b) = value;
return bytes;
}
-
+
// Converts a long into an array of bytes with length
// eight.
public unsafe static byte[] GetBytes(long value)
@@ -89,41 +91,44 @@ namespace System {
Contract.Ensures(Contract.Result<byte[]>().Length == 8);
byte[] bytes = new byte[8];
- fixed(byte* b = &bytes[0])
+ fixed (byte* b = &bytes[0])
*((long*)b) = 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);
return GetBytes((short)value);
}
-
+
// 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);
return GetBytes((int)value);
}
-
+
// 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);
return GetBytes((long)value);
}
-
+
// Converts a float into an array of bytes with length
// four.
public unsafe static byte[] GetBytes(float value)
@@ -133,7 +138,7 @@ namespace System {
return GetBytes(*(int*)&value);
}
-
+
// Converts a double into an array of bytes with length
// eight.
public unsafe static byte[] GetBytes(double value)
@@ -147,118 +152,147 @@ namespace System {
// Converts an array of bytes into a char.
public static char ToChar(byte[] value, int startIndex)
{
- if (value == null) {
+ if (value == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
}
- if ((uint)startIndex >= value.Length) {
+ if ((uint)startIndex >= value.Length)
+ {
ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
}
- if (startIndex > value.Length - 2) {
+ if (startIndex > value.Length - 2)
+ {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
Contract.EndContractBlock();
return (char)ToInt16(value, startIndex);
}
-
+
// Converts an array of bytes into a short.
- public static unsafe short ToInt16(byte[] value, int startIndex) {
- if( value == null) {
+ public static unsafe short ToInt16(byte[] value, int startIndex)
+ {
+ if (value == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
}
-
- if ((uint) startIndex >= value.Length) {
+
+ if ((uint)startIndex >= value.Length)
+ {
ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
}
-
- if (startIndex > value.Length -2) {
+
+ if (startIndex > value.Length - 2)
+ {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
Contract.EndContractBlock();
- fixed( byte * pbyte = &value[startIndex]) {
- if( startIndex % 2 == 0) { // data is aligned
- return *((short *) pbyte);
+ 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
+ {
+ if (IsLittleEndian)
+ {
+ return (short)((*pbyte) | (*(pbyte + 1) << 8));
}
- else {
- return (short)((*pbyte << 8) | (*(pbyte + 1)));
+ else
+ {
+ return (short)((*pbyte << 8) | (*(pbyte + 1)));
}
}
}
-
}
-
+
// Converts an array of bytes into an int.
- public static unsafe int ToInt32 (byte[] value, int startIndex) {
- if( value == null) {
+ public static unsafe int ToInt32(byte[] value, int startIndex)
+ {
+ if (value == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
}
-
- if ((uint) startIndex >= value.Length) {
+
+ if ((uint)startIndex >= value.Length)
+ {
ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
}
-
- if (startIndex > value.Length -4) {
+
+ if (startIndex > value.Length - 4)
+ {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
Contract.EndContractBlock();
- fixed( byte * pbyte = &value[startIndex]) {
- if( startIndex % 4 == 0) { // data is aligned
- return *((int *) pbyte);
+ 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
+ {
+ 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));
+ else
+ {
+ return (*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | (*(pbyte + 3));
}
}
}
}
-
+
// Converts an array of bytes into a long.
- public static unsafe long ToInt64 (byte[] value, int startIndex) {
- if (value == null) {
+ public static unsafe long ToInt64(byte[] value, int startIndex)
+ {
+ if (value == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
}
-
- if ((uint) startIndex >= value.Length) {
+
+ if ((uint)startIndex >= value.Length)
+ {
ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
}
-
- if (startIndex > value.Length -8) {
+
+ if (startIndex > value.Length - 8)
+ {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
Contract.EndContractBlock();
- fixed( byte * pbyte = &value[startIndex]) {
- if( startIndex % 8 == 0) { // data is aligned
- return *((long *) pbyte);
+ 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);
+ 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));
+ 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)]
@@ -274,7 +308,7 @@ namespace System {
return (ushort)ToInt16(value, startIndex);
}
-
+
// Converts an array of bytes into an uint.
//
[CLSCompliant(false)]
@@ -290,7 +324,7 @@ namespace System {
return (uint)ToInt32(value, startIndex);
}
-
+
// Converts an array of bytes into an unsigned long.
//
[CLSCompliant(false)]
@@ -306,9 +340,9 @@ namespace System {
return (ulong)ToInt64(value, startIndex);
}
-
+
// Converts an array of bytes into a float.
- unsafe public static float ToSingle (byte[] value, int startIndex)
+ unsafe public static float ToSingle(byte[] value, int startIndex)
{
if (value == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
@@ -321,9 +355,9 @@ namespace System {
int val = ToInt32(value, startIndex);
return *(float*)&val;
}
-
+
// Converts an array of bytes into a double.
- unsafe public static double ToDouble (byte[] value, int startIndex)
+ unsafe public static double ToDouble(byte[] value, int startIndex)
{
if (value == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
@@ -336,78 +370,90 @@ namespace System {
long val = ToInt64(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) {
+ 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 (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) {
+ if (length < 0)
+ {
throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
}
- if (startIndex > value.Length - length) {
+ if (startIndex > value.Length - length)
+ {
throw new ArgumentException(Environment.GetResourceString("Arg_ArrayPlusOffTooSmall"));
}
Contract.EndContractBlock();
- if (length == 0) {
+ if (length == 0)
+ {
return string.Empty;
}
- if (length > (Int32.MaxValue / 3)) {
+ if (length > (Int32.MaxValue / 3))
+ {
// (Int32.MaxValue / 3) == 715,827,882 Bytes == 699 MB
throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_LengthTooLarge", (Int32.MaxValue / 3)));
}
int chArrayLength = length * 3;
-
+
char[] chArray = new char[chArrayLength];
int i = 0;
int index = startIndex;
- for (i = 0; i < chArrayLength; i += 3) {
+ 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] = '-';
+ chArray[i] = GetHexValue(b / 16);
+ chArray[i + 1] = GetHexValue(b % 16);
+ chArray[i + 2] = '-';
}
// We don't need the last '-' character
return new String(chArray, 0, chArray.Length - 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);
+ 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);
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 +463,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)
+ public static bool ToBoolean(byte[] value, int startIndex)
+ {
+ if (value == null)
throw new ArgumentNullException(nameof(value));
if (startIndex < 0)
throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (startIndex > value.Length - 1)
throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
-
- return (value[startIndex]==0)?false:true;
+
+ return (value[startIndex] == 0) ? false : true;
}
- 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..7a7ac0eee8 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(Environment.GetResourceString("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(Environment.GetResourceString("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,145 @@ 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) {
+ char IConvertible.ToChar(IFormatProvider provider)
+ {
throw new InvalidCastException(Environment.GetResourceString("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) {
+ DateTime IConvertible.ToDateTime(IFormatProvider provider)
+ {
throw new InvalidCastException(Environment.GetResourceString("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..8b4e98b428 100644
--- a/src/mscorlib/src/System/Buffer.cs
+++ b/src/mscorlib/src/System/Buffer.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
+{
//Only contains static methods. Does not require serialization
-
+
using System;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
@@ -57,7 +57,7 @@ namespace System {
if (count == 0)
return -1;
else if (*pByte == value)
- return (int) (pByte - src);
+ return (int)(pByte - src);
count--;
pByte++;
@@ -87,7 +87,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 +100,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 +115,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)]
@@ -175,7 +174,7 @@ namespace System {
_SetByte(array, index, value);
}
-
+
// Gets a particular byte out of the array. The array must be an
// array of primitives.
//
@@ -200,31 +199,34 @@ namespace System {
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 +246,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);
}
@@ -271,196 +274,196 @@ namespace System {
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:
+ 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;
+ *(long*)dest = *(long*)src;
#else
*(int*)dest = *(int*)src;
*(int*)(dest + 4) = *(int*)(src + 4);
#endif
- return;
- case 9:
+ return;
+ case 9:
#if BIT64
- *(long*)dest = *(long*)src;
+ *(long*)dest = *(long*)src;
#else
*(int*)dest = *(int*)src;
*(int*)(dest + 4) = *(int*)(src + 4);
#endif
- *(dest + 8) = *(src + 8);
- return;
- case 10:
+ *(dest + 8) = *(src + 8);
+ return;
+ case 10:
#if BIT64
- *(long*)dest = *(long*)src;
+ *(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:
+ *(short*)(dest + 8) = *(short*)(src + 8);
+ return;
+ case 11:
#if BIT64
- *(long*)dest = *(long*)src;
+ *(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:
+ *(short*)(dest + 8) = *(short*)(src + 8);
+ *(dest + 10) = *(src + 10);
+ return;
+ case 12:
#if BIT64
- *(long*)dest = *(long*)src;
+ *(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:
+ *(int*)(dest + 8) = *(int*)(src + 8);
+ return;
+ case 13:
#if BIT64
- *(long*)dest = *(long*)src;
+ *(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:
+ *(int*)(dest + 8) = *(int*)(src + 8);
+ *(dest + 12) = *(src + 12);
+ return;
+ case 14:
#if BIT64
- *(long*)dest = *(long*)src;
+ *(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:
+ *(int*)(dest + 8) = *(int*)(src + 8);
+ *(short*)(dest + 12) = *(short*)(src + 12);
+ return;
+ case 15:
#if BIT64
- *(long*)dest = *(long*)src;
+ *(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:
+ *(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);
+ *(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:
+ return;
+ case 17:
#if BIT64
- *(long*)dest = *(long*)src;
- *(long*)(dest + 8) = *(long*)(src + 8);
+ *(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:
+ *(dest + 16) = *(src + 16);
+ return;
+ case 18:
#if BIT64
- *(long*)dest = *(long*)src;
- *(long*)(dest + 8) = *(long*)(src + 8);
+ *(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
- *(short*)(dest + 16) = *(short*)(src + 16);
- return;
- case 19:
+ *(short*)(dest + 16) = *(short*)(src + 16);
+ return;
+ case 19:
#if BIT64
- *(long*)dest = *(long*)src;
- *(long*)(dest + 8) = *(long*)(src + 8);
+ *(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
- *(short*)(dest + 16) = *(short*)(src + 16);
- *(dest + 18) = *(src + 18);
- return;
- case 20:
+ *(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);
+ *(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
- *(int*)(dest + 16) = *(int*)(src + 16);
- return;
- case 21:
+ *(int*)(dest + 16) = *(int*)(src + 16);
+ return;
+ case 21:
#if BIT64
- *(long*)dest = *(long*)src;
- *(long*)(dest + 8) = *(long*)(src + 8);
+ *(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
- *(int*)(dest + 16) = *(int*)(src + 16);
- *(dest + 20) = *(src + 20);
- return;
- case 22:
+ *(int*)(dest + 16) = *(int*)(src + 16);
+ *(dest + 20) = *(src + 20);
+ return;
+ case 22:
#if BIT64
- *(long*)dest = *(long*)src;
- *(long*)(dest + 8) = *(long*)(src + 8);
+ *(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
- *(int*)(dest + 16) = *(int*)(src + 16);
- *(short*)(dest + 20) = *(short*)(src + 20);
- return;
+ *(int*)(dest + 16) = *(int*)(src + 16);
+ *(short*)(dest + 20) = *(short*)(src + 20);
+ return;
}
// P/Invoke into the native version for large lengths
@@ -481,7 +484,7 @@ namespace System {
i += 2;
}
- IntAligned:
+ IntAligned:
#if BIT64
// On 64-bit IntPtr.Size == 8, so we want to advance to the next 8-aligned address. If
@@ -510,7 +513,7 @@ namespace System {
// 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;
+ nuint counter;
do
{
@@ -534,7 +537,7 @@ namespace System {
#endif
i = counter;
-
+
// See notes above for why this wasn't used instead
// i += 16;
}
@@ -550,12 +553,12 @@ namespace System {
#endif
i += 8;
}
- if ((len & 4) != 0)
+ if ((len & 4) != 0)
{
*(int*)(dest + i) = *(int*)(src + i);
i += 4;
}
- if ((len & 2) != 0)
+ if ((len & 2) != 0)
{
*(short*)(dest + i) = *(short*)(src + i);
i += 2;
@@ -569,9 +572,8 @@ namespace System {
return;
- PInvoke:
+ PInvoke:
_Memmove(dest, src, len);
-
}
// Non-inlinable wrapper around the QCall that avoids poluting the fast path
diff --git a/src/mscorlib/src/System/Byte.cs b/src/mscorlib/src/System/Byte.cs
index 666fdda75b..9d603600fc 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)) {
+ if (!(value is Byte))
+ {
throw new ArgumentException(Environment.GetResourceString("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,42 +79,50 @@ 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) {
+ catch (OverflowException e)
+ {
throw new OverflowException(Environment.GetResourceString("Overflow_Byte"), e);
}
@@ -115,133 +130,158 @@ namespace System {
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) {
+ DateTime IConvertible.ToDateTime(IFormatProvider provider)
+ {
throw new InvalidCastException(Environment.GetResourceString("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..98fe6f3b51 100644
--- a/src/mscorlib/src/System/CLRConfig.cs
+++ b/src/mscorlib/src/System/CLRConfig.cs
@@ -7,8 +7,8 @@ using System.Runtime.Versioning;
using System.Runtime.InteropServices;
using System.Security;
-namespace System {
-
+namespace System
+{
} // namespace System
// file CLRConfig
diff --git a/src/mscorlib/src/System/Char.cs b/src/mscorlib/src/System/Char.cs
index 7fe1c08715..bf3818f985 100644
--- a/src/mscorlib/src/System/Char.cs
+++ b/src/mscorlib/src/System/Char.cs
@@ -11,32 +11,34 @@
**
**
===========================================================*/
-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>
+
+using System;
+using System.Globalization;
+using System.Runtime;
+using System.Runtime.InteropServices;
+using System.Runtime.CompilerServices;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+
+namespace System
+{
+ [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;
+ //
+ // 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 = {
@@ -75,174 +77,199 @@ namespace System {
};
// Return true for all characters below or equal U+00ff, which is ASCII + Latin-1 Supplement.
- private static bool IsLatin1(char ch) {
+ 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) {
+ private static bool IsAscii(char ch)
+ {
return (ch <= '\x007f');
}
// Return the Unicode category for Unicode character <= 0x00ff.
- private static UnicodeCategory GetLatin1UnicodeCategory(char ch) {
+ 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) {
+
+ //
+ // 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) {
+ if (s == null)
+ {
return false;
- }
- if (s.Length != 1) {
+ }
+ 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) {
+ //
+ // 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
@@ -250,271 +277,312 @@ namespace System {
// 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') {
+ 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);
- }
-
-
+
+ /*===============================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)) {
+ public static bool IsUpper(char c)
+ {
+ if (IsLatin1(c))
+ {
+ if (IsAscii(c))
+ {
return (c >= 'A' && c <= 'Z');
}
- return (GetLatin1UnicodeCategory(c)== UnicodeCategory.UppercaseLetter);
+ 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)) {
+ 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);
- }
-
-
+ 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)));
+ 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);
- }
-
+
+ /*=================================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)) {
+ 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;
- }
+
+ /*===================================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/>
- sbyte IConvertible.ToSByte(IFormatProvider provider) {
+ 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) {
+ 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)
+ {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Char", "Single"));
}
/// <internalonly/>
- double IConvertible.ToDouble(IFormatProvider provider) {
+ double IConvertible.ToDouble(IFormatProvider provider)
+ {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Char", "Double"));
}
/// <internalonly/>
- Decimal IConvertible.ToDecimal(IFormatProvider provider) {
+ Decimal IConvertible.ToDecimal(IFormatProvider provider)
+ {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Char", "Decimal"));
}
/// <internalonly/>
- DateTime IConvertible.ToDateTime(IFormatProvider provider) {
+ DateTime IConvertible.ToDateTime(IFormatProvider provider)
+ {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Char", "DateTime"));
}
/// <internalonly/>
- Object IConvertible.ToType(Type type, IFormatProvider provider) {
+ Object IConvertible.ToType(Type type, IFormatProvider provider)
+ {
return Convert.DefaultToType((IConvertible)this, type, provider);
}
public static bool IsControl(char c)
{
- if (IsLatin1(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)
+
+ public static bool IsControl(String s, int index)
+ {
+ 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();
char c = s[index];
- if (IsLatin1(c)) {
+ if (IsLatin1(c))
+ {
return (GetLatin1UnicodeCategory(c) == UnicodeCategory.Control);
}
return (CharUnicodeInfo.GetUnicodeCategory(s, index) == UnicodeCategory.Control);
@@ -523,69 +591,79 @@ namespace System {
public static bool IsDigit(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();
char c = s[index];
- if (IsLatin1(c)) {
+ if (IsLatin1(c))
+ {
return (c >= '0' && c <= '9');
}
- return (CharUnicodeInfo.GetUnicodeCategory(s, index) == UnicodeCategory.DecimalDigitNumber);
+ return (CharUnicodeInfo.GetUnicodeCategory(s, index) == UnicodeCategory.DecimalDigitNumber);
}
public static bool IsLetter(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();
char c = s[index];
- if (IsLatin1(c)) {
- if (IsAscii(c)) {
- c |=(char)0x20;
- return ((c >= 'a' && c <= 'z'));
- }
- return (CheckLetter(GetLatin1UnicodeCategory(c)));
+ 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)
+ {
+ 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();
char c = s[index];
- if (IsLatin1(c)) {
- return CheckLetterOrDigit(GetLatin1UnicodeCategory(c));
+ if (IsLatin1(c))
+ {
+ return CheckLetterOrDigit(GetLatin1UnicodeCategory(c));
}
return CheckLetterOrDigit(CharUnicodeInfo.GetUnicodeCategory(s, index));
}
public static bool IsLower(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();
char c = s[index];
- if (IsLatin1(c)) {
- if (IsAscii(c)) {
+ if (IsLatin1(c))
+ {
+ if (IsAscii(c))
+ {
return (c >= 'a' && c <= 'z');
}
- return (GetLatin1UnicodeCategory(c)== UnicodeCategory.LowercaseLetter);
+ return (GetLatin1UnicodeCategory(c) == UnicodeCategory.LowercaseLetter);
}
-
+
return (CharUnicodeInfo.GetUnicodeCategory(s, index) == UnicodeCategory.LowercaseLetter);
}
@@ -593,8 +671,10 @@ namespace System {
** Check if the specified UnicodeCategory belongs to the number categories.
==============================================================================*/
- internal static bool CheckNumber(UnicodeCategory uc) {
- switch (uc) {
+ internal static bool CheckNumber(UnicodeCategory uc)
+ {
+ switch (uc)
+ {
case (UnicodeCategory.DecimalDigitNumber):
case (UnicodeCategory.LetterNumber):
case (UnicodeCategory.OtherNumber):
@@ -605,26 +685,31 @@ namespace System {
public static bool IsNumber(char c)
{
- if (IsLatin1(c)) {
- if (IsAscii(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)
+ 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();
char c = s[index];
- if (IsLatin1(c)) {
- if (IsAscii(c)) {
+ if (IsLatin1(c))
+ {
+ if (IsAscii(c))
+ {
return (c >= '0' && c <= '9');
}
return (CheckNumber(GetLatin1UnicodeCategory(c)));
@@ -639,18 +724,20 @@ namespace System {
// Determines if the given character is a punctuation character.
//
////////////////////////////////////////////////////////////////////////
-
- public static bool IsPunctuation (String s, int index)
+
+ public static bool IsPunctuation(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();
char c = s[index];
- if (IsLatin1(c)) {
- return (CheckPunctuation(GetLatin1UnicodeCategory(c)));
+ if (IsLatin1(c))
+ {
+ return (CheckPunctuation(GetLatin1UnicodeCategory(c)));
}
return (CheckPunctuation(CharUnicodeInfo.GetUnicodeCategory(s, index)));
}
@@ -662,7 +749,8 @@ namespace System {
internal static bool CheckSeparator(UnicodeCategory uc)
{
- switch (uc) {
+ switch (uc)
+ {
case UnicodeCategory.SpaceSeparator:
case UnicodeCategory.LineSeparator:
case UnicodeCategory.ParagraphSeparator:
@@ -671,7 +759,8 @@ namespace System {
return (false);
}
- private static bool IsSeparatorLatin1(char c) {
+ 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');
@@ -679,7 +768,8 @@ namespace System {
public static bool IsSeparator(char c)
{
- if (IsLatin1(c)) {
+ if (IsLatin1(c))
+ {
return (IsSeparatorLatin1(c));
}
return (CheckSeparator(CharUnicodeInfo.GetUnicodeCategory(c)));
@@ -687,14 +777,16 @@ namespace System {
public static bool IsSeparator(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();
char c = s[index];
- if (IsLatin1(c)) {
+ if (IsLatin1(c))
+ {
return (IsSeparatorLatin1(c));
}
return (CheckSeparator(CharUnicodeInfo.GetUnicodeCategory(s, index)));
@@ -709,34 +801,39 @@ namespace System {
[Pure]
public static bool IsSurrogate(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 (IsSurrogate(s[index]));
}
- /*================================= CheckSymbol ============================
- ** Check if the specified UnicodeCategory belongs to the symbol categories.
- ==============================================================================*/
+ /*================================= CheckSymbol ============================
+ ** Check if the specified UnicodeCategory belongs to the symbol categories.
+ ==============================================================================*/
- internal static bool CheckSymbol(UnicodeCategory uc) {
- switch (uc) {
+ internal static bool CheckSymbol(UnicodeCategory uc)
+ {
+ switch (uc)
+ {
case (UnicodeCategory.MathSymbol):
- case (UnicodeCategory.CurrencySymbol):
- case (UnicodeCategory.ModifierSymbol):
- case (UnicodeCategory.OtherSymbol):
+ case (UnicodeCategory.CurrencySymbol):
+ case (UnicodeCategory.ModifierSymbol):
+ case (UnicodeCategory.OtherSymbol):
return (true);
}
return (false);
}
-
+
public static bool IsSymbol(char c)
{
- if (IsLatin1(c)) {
+ if (IsLatin1(c))
+ {
return (CheckSymbol(GetLatin1UnicodeCategory(c)));
}
return (CheckSymbol(CharUnicodeInfo.GetUnicodeCategory(c)));
@@ -744,57 +841,65 @@ namespace System {
public static bool IsSymbol(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();
- if (IsLatin1(s[index])) {
+ 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)
+ {
+ 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();
char c = s[index];
- if (IsLatin1(c)) {
- if (IsAscii(c)) {
+ if (IsLatin1(c))
+ {
+ if (IsAscii(c))
+ {
return (c >= 'A' && c <= 'Z');
}
- return (GetLatin1UnicodeCategory(c)== UnicodeCategory.UppercaseLetter);
+ return (GetLatin1UnicodeCategory(c) == UnicodeCategory.UppercaseLetter);
}
-
+
return (CharUnicodeInfo.GetUnicodeCategory(s, index) == UnicodeCategory.UppercaseLetter);
}
public static bool IsWhiteSpace(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();
- if (IsLatin1(s[index])) {
+ if (IsLatin1(s[index]))
+ {
return IsWhiteSpaceLatin1(s[index]);
- }
-
+ }
+
return CharUnicodeInfo.IsWhiteSpace(s, index);
}
-
+
public static UnicodeCategory GetUnicodeCategory(char c)
{
- if (IsLatin1(c)) {
+ if (IsLatin1(c))
+ {
return (GetLatin1UnicodeCategory(c));
}
return CharUnicodeInfo.InternalGetUnicodeCategory(c);
@@ -802,13 +907,15 @@ namespace System {
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();
- if (IsLatin1(s[index])) {
+ if (IsLatin1(s[index]))
+ {
return (GetLatin1UnicodeCategory(s[index]));
}
return CharUnicodeInfo.InternalGetUnicodeCategory(s, index);
@@ -821,9 +928,10 @@ namespace System {
public static double GetNumericValue(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();
@@ -831,66 +939,79 @@ namespace System {
}
- /*================================= IsHighSurrogate ============================
- ** Check if a char is a high surrogate.
- ==============================================================================*/
+ /*================================= IsHighSurrogate ============================
+ ** Check if a char is a high surrogate.
+ ==============================================================================*/
[Pure]
- public static bool IsHighSurrogate(char c) {
+ 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) {
+ public static bool IsHighSurrogate(String s, int index)
+ {
+ if (s == null)
+ {
throw new ArgumentNullException(nameof(s));
}
- if (index < 0 || index >= s.Length) {
+ 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.
- ==============================================================================*/
+ }
+
+ /*================================= IsLowSurrogate ============================
+ ** Check if a char is a low surrogate.
+ ==============================================================================*/
[Pure]
- public static bool IsLowSurrogate(char c) {
+ 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) {
+ public static bool IsLowSurrogate(String s, int index)
+ {
+ if (s == null)
+ {
throw new ArgumentNullException(nameof(s));
}
- if (index < 0 || index >= s.Length) {
+ 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.
- ==============================================================================*/
+ /*================================= 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) {
+ public static bool IsSurrogatePair(String s, int index)
+ {
+ if (s == null)
+ {
throw new ArgumentNullException(nameof(s));
}
- if (index < 0 || index >= s.Length) {
+ 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]));
+ if (index + 1 < s.Length)
+ {
+ return (IsSurrogatePair(s[index], s[index + 1]));
}
return (false);
}
[Pure]
- public static bool IsSurrogatePair(char highSurrogate, char lowSurrogate) {
+ 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));
}
@@ -900,27 +1021,29 @@ namespace System {
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 UNICODE_PLANE16_END = 0x10ffff;
internal const int HIGH_SURROGATE_START = 0x00d800;
- internal const int LOW_SURROGATE_END = 0x00dfff;
-
+ internal const int LOW_SURROGATE_END = 0x00dfff;
- /*================================= ConvertFromUtf32 ============================
- ** Convert an UTF32 value into a surrogate pair.
- ==============================================================================*/
-
+
+ /*================================= 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)) {
+ 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) {
+ if (utf32 < UNICODE_PLANE01_START)
+ {
// This is a BMP character.
return (Char.ToString((char)utf32));
}
@@ -941,12 +1064,15 @@ namespace System {
/*=============================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"));
+
+ public static int ConvertToUtf32(char highSurrogate, char lowSurrogate)
+ {
+ if (!IsHighSurrogate(highSurrogate))
+ {
+ throw new ArgumentOutOfRangeException(nameof(highSurrogate), Environment.GetResourceString("ArgumentOutOfRange_InvalidHighSurrogate"));
}
- if (!IsLowSurrogate(lowSurrogate)) {
+ if (!IsLowSurrogate(lowSurrogate))
+ {
throw new ArgumentOutOfRangeException(nameof(lowSurrogate), Environment.GetResourceString("ArgumentOutOfRange_InvalidLowSurrogate"));
}
Contract.EndContractBlock();
@@ -960,37 +1086,50 @@ namespace System {
** 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) {
+
+ public static int ConvertToUtf32(String s, int index)
+ {
+ if (s == null)
+ {
throw new ArgumentNullException(nameof(s));
}
- if (index < 0 || index >= s.Length) {
+ 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) {
+ if (temp1 >= 0 && temp1 <= 0x7ff)
+ {
// Found a surrogate char.
- if (temp1 <= 0x3ff) {
+ 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) {
+ 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 {
+ 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));
+ throw new ArgumentException(Environment.GetResourceString("Argument_InvalidHighSurrogate", index), nameof(s));
}
- } else {
+ }
+ else
+ {
// Find a low surrogate at the character pointed by index.
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidLowSurrogate", index), nameof(s));
+ 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.
diff --git a/src/mscorlib/src/System/Collections/ArrayList.cs b/src/mscorlib/src/System/Collections/ArrayList.cs
index 53746e224e..96aca31bad 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,37 +44,40 @@ 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 = EmptyArray<Object>.Value;
// 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), Environment.GetResourceString("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)
+ public ArrayList(ICollection c)
+ {
+ if (c == null)
throw new ArgumentNullException(nameof(c), Environment.GetResourceString("ArgumentNull_Collection"));
Contract.EndContractBlock();
@@ -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) {
+ set
+ {
+ if (value < _size)
+ {
throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("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 {
+ public virtual Object this[int index]
+ {
+ get
+ {
if (index < 0 || index >= _size) throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
return _items[index];
}
- set {
+ set
+ {
if (index < 0 || index >= _size) throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("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,7 +266,8 @@ 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"));
Contract.EndContractBlock();
@@ -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"));
//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)
+ 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"));
//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) {
+ public virtual void RemoveAt(int index)
+ {
if (index < 0 || index >= _size) throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("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 {
+ set
+ {
throw new NotSupportedException(Environment.GetResourceString("NotSupported_ReadOnlyCollection"));
}
}
-
- public virtual Object SyncRoot {
+
+ public virtual Object SyncRoot
+ {
get { return _list.SyncRoot; }
}
-
- public virtual int Add(Object obj) {
+
+ public virtual int Add(Object obj)
+ {
throw new NotSupportedException(Environment.GetResourceString("NotSupported_ReadOnlyCollection"));
}
-
- public virtual void Clear() {
+
+ public virtual void Clear()
+ {
throw new NotSupportedException(Environment.GetResourceString("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) {
+
+ public virtual void Insert(int index, Object obj)
+ {
throw new NotSupportedException(Environment.GetResourceString("NotSupported_ReadOnlyCollection"));
}
- public virtual void Remove(Object value) {
+ public virtual void Remove(Object value)
+ {
throw new NotSupportedException(Environment.GetResourceString("NotSupported_ReadOnlyCollection"));
}
-
- public virtual void RemoveAt(int index) {
+
+ public virtual void RemoveAt(int index)
+ {
throw new NotSupportedException(Environment.GetResourceString("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) {
+
+ public bool MoveNext()
+ {
+ if (version != list._version)
+ {
throw new InvalidOperationException(Environment.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) {
+ if (dummyObject == temp)
+ { // check if enumeration has not started or has terminated
+ if (index == -1)
+ {
throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumNotStarted));
}
- else {
- throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumEnded));
+ else
+ {
+ throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumEnded));
}
}
return temp;
}
}
-
- public void Reset() {
- if (version != list._version) {
+
+ public void Reset()
+ {
+ if (version != list._version)
+ {
throw new InvalidOperationException(Environment.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
index a3dd88a7b3..a0df2bbbbf 100644
--- a/src/mscorlib/src/System/Collections/CollectionBase.cs
+++ b/src/mscorlib/src/System/Collections/CollectionBase.cs
@@ -6,45 +6,55 @@
//------------------------------------------------------------------------------
//
-namespace System.Collections {
- using System;
- using System.Diagnostics.Contracts;
+using System;
+using System.Diagnostics.Contracts;
+namespace System.Collections
+{
// Useful base class for typed read/write collections where items derive from object
[Serializable]
- public abstract class CollectionBase : IList {
+ public abstract class CollectionBase : IList
+ {
private ArrayList list;
- protected CollectionBase() {
+ protected CollectionBase()
+ {
list = new ArrayList();
}
- internal ArrayList InnerList {
- get {
+ internal ArrayList InnerList
+ {
+ get
+ {
if (list == null)
list = new ArrayList();
return list;
}
}
- protected IList List {
+ protected IList List
+ {
get { return (IList)this; }
}
- public int Count {
- get {
+ public int Count
+ {
+ get
+ {
return list == null ? 0 : list.Count;
}
}
- public void Clear() {
+ public void Clear()
+ {
OnClear();
InnerList.Clear();
OnClearComplete();
}
- public void RemoveAt(int index) {
+ public void RemoveAt(int index)
+ {
if (index < 0 || index >= Count)
throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
Contract.EndContractBlock();
@@ -52,148 +62,178 @@ namespace System.Collections {
OnValidate(temp);
OnRemove(index, temp);
InnerList.RemoveAt(index);
- try {
+ try
+ {
OnRemoveComplete(index, temp);
}
- catch {
+ catch
+ {
InnerList.Insert(index, temp);
throw;
}
-
}
- bool IList.IsReadOnly {
+ bool IList.IsReadOnly
+ {
get { return InnerList.IsReadOnly; }
}
- bool IList.IsFixedSize {
+ bool IList.IsFixedSize
+ {
get { return InnerList.IsFixedSize; }
}
- bool ICollection.IsSynchronized {
+ bool ICollection.IsSynchronized
+ {
get { return InnerList.IsSynchronized; }
}
- Object ICollection.SyncRoot {
+ Object ICollection.SyncRoot
+ {
get { return InnerList.SyncRoot; }
}
- void ICollection.CopyTo(Array array, int index) {
+ void ICollection.CopyTo(Array array, int index)
+ {
InnerList.CopyTo(array, index);
}
- Object IList.this[int index] {
- get {
+ 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];
+ return InnerList[index];
}
- set {
+ 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 {
+ OnSet(index, temp, value);
+ InnerList[index] = value;
+ try
+ {
OnSetComplete(index, temp, value);
}
- catch {
- InnerList[index] = temp;
+ catch
+ {
+ InnerList[index] = temp;
throw;
}
}
}
- bool IList.Contains(Object value) {
+ bool IList.Contains(Object value)
+ {
return InnerList.Contains(value);
}
- int IList.Add(Object value) {
+ int IList.Add(Object value)
+ {
OnValidate(value);
OnInsert(InnerList.Count, value);
int index = InnerList.Add(value);
- try {
+ try
+ {
OnInsertComplete(index, value);
}
- catch {
+ catch
+ {
InnerList.RemoveAt(index);
throw;
}
return index;
}
-
- void IList.Remove(Object value) {
+
+ 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{
+ try
+ {
OnRemoveComplete(index, value);
}
- catch {
+ catch
+ {
InnerList.Insert(index, value);
throw;
}
}
- int IList.IndexOf(Object value) {
+ int IList.IndexOf(Object value)
+ {
return InnerList.IndexOf(value);
}
- void IList.Insert(int index, Object 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 {
+ try
+ {
OnInsertComplete(index, value);
}
- catch {
+ catch
+ {
InnerList.RemoveAt(index);
throw;
}
}
- public IEnumerator GetEnumerator() {
+ public IEnumerator GetEnumerator()
+ {
return InnerList.GetEnumerator();
}
- protected virtual void OnSet(int index, Object oldValue, Object newValue) {
+ protected virtual void OnSet(int index, Object oldValue, Object newValue)
+ {
}
- protected virtual void OnInsert(int index, Object value) {
+ protected virtual void OnInsert(int index, Object value)
+ {
}
- protected virtual void OnClear() {
+ protected virtual void OnClear()
+ {
}
- protected virtual void OnRemove(int index, Object value) {
+ protected virtual void OnRemove(int index, Object value)
+ {
}
- protected virtual void OnValidate(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 OnSetComplete(int index, Object oldValue, Object newValue)
+ {
}
- protected virtual void OnInsertComplete(int index, Object value) {
+ protected virtual void OnInsertComplete(int index, Object value)
+ {
}
- protected virtual void OnClearComplete() {
+ protected virtual void OnClearComplete()
+ {
}
- protected virtual void OnRemoveComplete(int index, Object value) {
+ 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..f1480e1f4f 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)
@@ -81,15 +90,18 @@ namespace System.Collections {
throw new ArgumentException(Environment.GetResourceString("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..54c9132449 100644
--- a/src/mscorlib/src/System/Collections/CompatibleComparer.cs
+++ b/src/mscorlib/src/System/Collections/CompatibleComparer.cs
@@ -6,26 +6,29 @@
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);
@@ -33,12 +36,15 @@ namespace System.Collections {
throw new ArgumentException(Environment.GetResourceString("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 a0030e153e..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.
@@ -709,7 +709,6 @@ namespace System.Collections.Concurrent
{
count += m_tables.m_countPerLock[i];
}
-
}
finally
{
@@ -1408,7 +1407,6 @@ namespace System.Collections.Concurrent
/// </summary>
private static int DefaultConcurrencyLevel
{
-
get { return DEFAULT_CONCURRENCY_MULTIPLIER * PlatformHelper.ProcessorCount; }
}
@@ -1563,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..991e17d6dc 100644
--- a/src/mscorlib/src/System/Collections/Concurrent/ConcurrentQueue.cs
+++ b/src/mscorlib/src/System/Collections/Concurrent/ConcurrentQueue.cs
@@ -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 3cc100e7d1..7b2bb9c74e 100644
--- a/src/mscorlib/src/System/Collections/Concurrent/ConcurrentStack.cs
+++ b/src/mscorlib/src/System/Collections/Concurrent/ConcurrentStack.cs
@@ -306,7 +306,6 @@ namespace System.Collections.Concurrent
result = default(T);
return false;
-
}
/// <summary>
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
index 0c5d8b2387..d9fa7fa526 100644
--- a/src/mscorlib/src/System/Collections/DictionaryEntry.cs
+++ b/src/mscorlib/src/System/Collections/DictionaryEntry.cs
@@ -13,10 +13,12 @@
**
**
===========================================================*/
-namespace System.Collections {
-
- using System;
- using System.ComponentModel;
+
+using System;
+using System.ComponentModel;
+
+namespace System.Collections
+{
// A DictionaryEntry holds a key and a value from a dictionary.
// It is returned by IDictionaryEnumerator::GetEntry().
[Serializable]
@@ -24,30 +26,37 @@ namespace System.Collections {
{
private Object _key;
private Object _value;
-
+
// Constructs a new DictionaryEnumerator by setting the Key
// and Value fields appropriately.
- public DictionaryEntry(Object key, Object value) {
+ public DictionaryEntry(Object key, Object value)
+ {
_key = key;
_value = value;
}
- public Object Key {
- get {
+ public Object Key
+ {
+ get
+ {
return _key;
}
-
- set {
+
+ set
+ {
_key = value;
}
}
- public Object Value {
- get {
+ public Object Value
+ {
+ get
+ {
return _value;
}
- set {
+ set
+ {
_value = value;
}
}
diff --git a/src/mscorlib/src/System/Collections/EmptyReadOnlyDictionaryInternal.cs b/src/mscorlib/src/System/Collections/EmptyReadOnlyDictionaryInternal.cs
index a610fce016..a0ce919ce5 100644
--- a/src/mscorlib/src/System/Collections/EmptyReadOnlyDictionaryInternal.cs
+++ b/src/mscorlib/src/System/Collections/EmptyReadOnlyDictionaryInternal.cs
@@ -15,27 +15,31 @@
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)
@@ -44,148 +48,184 @@ namespace System.Collections {
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("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(Environment.GetResourceString("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) {
+ public Object this[Object key]
+ {
+ get
+ {
+ if (key == null)
+ {
throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key"));
}
Contract.EndContractBlock();
return null;
}
- set {
- if (key == null) {
+ set
+ {
+ if (key == null)
+ {
throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key"));
}
- if (!key.GetType().IsSerializable)
- throw new ArgumentException(Environment.GetResourceString("Argument_NotSerializable"), nameof(key));
+ if (!key.GetType().IsSerializable)
+ throw new ArgumentException(Environment.GetResourceString("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(Environment.GetResourceString("Argument_NotSerializable"), nameof(value));
Contract.EndContractBlock();
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
}
}
- public ICollection Keys {
- get {
+ public ICollection Keys
+ {
+ get
+ {
return EmptyArray<Object>.Value;
}
}
- public ICollection Values {
- get {
+ public ICollection Values
+ {
+ get
+ {
return EmptyArray<Object>.Value;
}
}
- public bool Contains(Object key) {
+ public bool Contains(Object key)
+ {
return false;
}
- public void Add(Object key, Object value) {
- if (key == null) {
+ public void Add(Object key, Object value)
+ {
+ if (key == null)
+ {
throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key"));
}
- if (!key.GetType().IsSerializable)
- throw new ArgumentException(Environment.GetResourceString("Argument_NotSerializable"), nameof(key) );
+ if (!key.GetType().IsSerializable)
+ throw new ArgumentException(Environment.GetResourceString("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(Environment.GetResourceString("Argument_NotSerializable"), nameof(value));
Contract.EndContractBlock();
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
}
- public void Clear() {
+ public void Clear()
+ {
throw new InvalidOperationException(Environment.GetResourceString("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) {
+ public void Remove(Object key)
+ {
throw new InvalidOperationException(Environment.GetResourceString("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 {
+ public Object Current
+ {
+ get
+ {
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen"));
}
}
- public void Reset() {
+ public void Reset()
+ {
}
// IDictionaryEnumerator members
- public Object Key {
- get {
+ public Object Key
+ {
+ get
+ {
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen"));
}
}
- public Object Value {
- get {
+ public Object Value
+ {
+ get
+ {
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen"));
}
}
- public DictionaryEntry Entry {
- get {
+ public DictionaryEntry Entry
+ {
+ get
+ {
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen"));
}
}
diff --git a/src/mscorlib/src/System/Collections/Generic/ArraySortHelper.cs b/src/mscorlib/src/System/Collections/Generic/ArraySortHelper.cs
index 0f4a2b9b78..d3284bec1f 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>
@@ -47,18 +48,18 @@ namespace System.Collections.Generic
return result;
}
- internal static void ThrowOrIgnoreBadComparer(Object comparer) {
+ internal static void ThrowOrIgnoreBadComparer(Object comparer)
+ {
throw new ArgumentException(Environment.GetResourceString("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
@@ -69,8 +70,8 @@ namespace System.Collections.Generic
return sorter;
}
- }
-
+ }
+
private static IArraySortHelper<T> CreateArraySortHelper()
{
if (typeof(IComparable<T>).IsAssignableFrom(typeof(T)))
@@ -79,7 +80,7 @@ namespace System.Collections.Generic
}
else
{
- defaultArraySortHelper = new ArraySortHelper<T>();
+ defaultArraySortHelper = new ArraySortHelper<T>();
}
return defaultArraySortHelper;
}
@@ -89,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.
@@ -239,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;
}
@@ -373,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)
@@ -483,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];
@@ -527,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;
}
@@ -660,7 +661,7 @@ namespace System.Collections.Generic
}
}
-#endregion
+ #endregion
#region ArraySortHelper for paired key and value arrays
@@ -673,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
{
@@ -753,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];
@@ -808,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;
}
@@ -911,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;
}
@@ -940,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;
}
}
@@ -958,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
@@ -972,7 +973,7 @@ namespace System.Collections.Generic
{
ArraySortHelper<TKey, TValue>.IntrospectiveSort(keys, values, index, length, comparer);
}
- }
+ }
catch (IndexOutOfRangeException)
{
IntrospectiveSortUtilities.ThrowOrIgnoreBadComparer(comparer);
@@ -1004,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];
@@ -1057,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;
}
@@ -1104,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
{
@@ -1165,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;
}
@@ -1189,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 714b386e3e..a9b4b3f0dd 100644
--- a/src/mscorlib/src/System/Collections/Generic/Comparer.cs
+++ b/src/mscorlib/src/System/Collections/Generic/Comparer.cs
@@ -15,9 +15,9 @@ 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>
{
// To minimize generic instantiation overhead of creating the comparer per type, we keep the generic portion of the code as small
@@ -36,7 +36,8 @@ namespace System.Collections.Generic
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);
@@ -44,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;
}
@@ -74,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;
}
@@ -94,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);
}
@@ -111,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);
}
}
@@ -133,10 +141,10 @@ namespace System.Collections.Generic
{
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);
@@ -168,10 +176,10 @@ namespace System.Collections.Generic
{
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);
@@ -199,7 +207,7 @@ namespace System.Collections.Generic
{
Debug.Assert(typeof(T).IsEnum);
}
-
+
public override int Compare(T x, T y)
{
long lx = JitHelpers.UnsafeEnumCastLong(x);
@@ -227,10 +235,10 @@ namespace System.Collections.Generic
{
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/DebugView.cs b/src/mscorlib/src/System/Collections/Generic/DebugView.cs
index 27c5011147..c6b58de627 100644
--- a/src/mscorlib/src/System/Collections/Generic/DebugView.cs
+++ b/src/mscorlib/src/System/Collections/Generic/DebugView.cs
@@ -13,116 +13,138 @@
**
=============================================================================*/
-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;
- internal sealed class Mscorlib_DictionaryKeyCollectionDebugView<TKey, TValue> {
- private ICollection<TKey> collection;
-
- public Mscorlib_DictionaryKeyCollectionDebugView(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;
- internal sealed class Mscorlib_DictionaryValueCollectionDebugView<TKey, TValue> {
- private ICollection<TValue> collection;
-
- public Mscorlib_DictionaryValueCollectionDebugView(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;
-
- public Mscorlib_DictionaryDebugView(IDictionary<K, V> dictionary) {
+ internal sealed class Mscorlib_DictionaryDebugView<K, V>
+ {
+ private IDictionary<K, V> dict;
+
+ 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;
- internal sealed class Mscorlib_KeyedCollectionDebugView<K, T> {
- private KeyedCollection<K, T> kc;
-
- public Mscorlib_KeyedCollectionDebugView(KeyedCollection<K, T> keyedCollection) {
- if (keyedCollection == null) {
+ 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 {
+ 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..c48c16c0e1 100644
--- a/src/mscorlib/src/System/Collections/Generic/Dictionary.cs
+++ b/src/mscorlib/src/System/Collections/Generic/Dictionary.cs
@@ -41,8 +41,9 @@
** 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;
@@ -52,9 +53,10 @@ namespace System.Collections.Generic {
[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,20 +73,21 @@ 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;
@@ -92,17 +95,18 @@ namespace System.Collections.Generic {
#if FEATURE_RANDOMIZED_STRING_HASHING
if (HashHelpers.s_UseRandomizedStringHashing && 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) : this(dictionary, null) { }
- public Dictionary(IDictionary<TKey,TValue> dictionary, IEqualityComparer<TKey> comparer):
- this(dictionary != null? dictionary.Count: 0, comparer) {
-
- 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 +114,172 @@ 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 {
+ set
+ {
Insert(key, value, false);
}
}
- public void Add(TKey key, TValue value) {
+ public void Add(TKey key, TValue value)
+ {
Insert(key, value, true);
}
- 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,57 +289,73 @@ 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);
@@ -313,28 +367,34 @@ namespace System.Collections.Generic {
#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 +402,10 @@ namespace System.Collections.Generic {
freeList = -1;
}
- private void Insert(TKey key, TValue value, bool add) {
-
- if( key == null ) {
+ private void Insert(TKey key, TValue value, bool add)
+ {
+ if (key == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
@@ -356,27 +417,32 @@ 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 (add)
+ {
ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException(key);
}
entries[i].value = value;
version++;
return;
- }
+ }
#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 +465,59 @@ 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
}
- 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);
}
}
- else {
+ else
+ {
buckets = null;
}
@@ -452,25 +525,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 +560,28 @@ namespace System.Collections.Generic {
entries = newEntries;
}
- public bool Remove(TKey key) {
- if(key == null) {
+ 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 +598,11 @@ namespace System.Collections.Generic {
return false;
}
- public bool TryGetValue(TKey key, out TValue value) {
+ 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 +625,244 @@ namespace System.Collections.Generic {
return defaultValue;
}
- bool ICollection<KeyValuePair<TKey,TValue>>.IsReadOnly {
+ 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 +870,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 +895,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 +1135,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 +1170,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 +1363,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 +1397,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 7178ddc663..a717558fbf 100644
--- a/src/mscorlib/src/System/Collections/Generic/EqualityComparer.cs
+++ b/src/mscorlib/src/System/Collections/Generic/EqualityComparer.cs
@@ -7,13 +7,13 @@ 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>
@@ -27,30 +27,36 @@ namespace System.Collections.Generic
[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);
@@ -62,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;
}
@@ -77,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;
}
}
@@ -121,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;
}
@@ -133,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;
}
}
@@ -172,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;
}
@@ -187,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;
}
}
@@ -232,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();
}
@@ -254,20 +301,23 @@ 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"));
@@ -277,14 +327,17 @@ namespace System.Collections.Generic
throw new ArgumentException(Environment.GetResourceString("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;
@@ -295,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();
}
@@ -354,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();
}
@@ -366,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();
}
@@ -376,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
index 741e8cc79b..6f38832362 100644
--- a/src/mscorlib/src/System/Collections/Generic/ICollection.cs
+++ b/src/mscorlib/src/System/Collections/Generic/ICollection.cs
@@ -13,11 +13,13 @@
**
**
===========================================================*/
-namespace System.Collections.Generic {
- using System;
- using System.Runtime.CompilerServices;
- using System.Diagnostics.Contracts;
+using System;
+using System.Runtime.CompilerServices;
+using System.Diagnostics.Contracts;
+
+namespace System.Collections.Generic
+{
// Base interface for all collections, defining enumerators, size, and
// synchronization methods.
@@ -38,13 +40,13 @@ namespace System.Collections.Generic {
void Clear();
- bool Contains(T item);
-
+ 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
index 7b9e97ff0e..aa743855be 100644
--- a/src/mscorlib/src/System/Collections/Generic/IComparer.cs
+++ b/src/mscorlib/src/System/Collections/Generic/IComparer.cs
@@ -13,9 +13,11 @@
**
**
===========================================================*/
-namespace System.Collections.Generic {
-
- using System;
+
+using System;
+
+namespace System.Collections.Generic
+{
// The generic IComparer interface implements a method that compares
// two objects. It is used in conjunction with the Sort and
// BinarySearch methods on the Array, List, and SortedList classes.
diff --git a/src/mscorlib/src/System/Collections/Generic/IDictionary.cs b/src/mscorlib/src/System/Collections/Generic/IDictionary.cs
index 2a2da944d3..273a7d36a0 100644
--- a/src/mscorlib/src/System/Collections/Generic/IDictionary.cs
+++ b/src/mscorlib/src/System/Collections/Generic/IDictionary.cs
@@ -13,10 +13,12 @@
**
**
===========================================================*/
-namespace System.Collections.Generic {
- using System;
- using System.Diagnostics.Contracts;
+using System;
+using System.Diagnostics.Contracts;
+
+namespace System.Collections.Generic
+{
// An IDictionary is a possibly unordered set of key-value pairs.
// Keys can be any non-null object. Values can be any object.
// You can look up a value in an IDictionary via the default indexed
@@ -26,29 +28,32 @@ namespace System.Collections.Generic {
// Interfaces are not serializable
// The Item property provides methods to read and edit entries
// in the Dictionary.
- TValue this[TKey key] {
+ TValue this[TKey key]
+ {
get;
set;
}
-
+
// Returns a collections of the keys in this dictionary.
- ICollection<TKey> Keys {
+ ICollection<TKey> Keys
+ {
get;
}
-
+
// Returns a collections of the values in this dictionary.
- ICollection<TValue> Values {
+ 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);
diff --git a/src/mscorlib/src/System/Collections/Generic/IEnumerable.cs b/src/mscorlib/src/System/Collections/Generic/IEnumerable.cs
index 67f35ce675..e3c72f518c 100644
--- a/src/mscorlib/src/System/Collections/Generic/IEnumerable.cs
+++ b/src/mscorlib/src/System/Collections/Generic/IEnumerable.cs
@@ -13,13 +13,15 @@
**
**
===========================================================*/
-namespace System.Collections.Generic {
- using System;
- using System.Collections;
- using System.Runtime.InteropServices;
- using System.Runtime.CompilerServices;
- using System.Diagnostics.Contracts;
+using System;
+using System.Collections;
+using System.Runtime.InteropServices;
+using System.Runtime.CompilerServices;
+using System.Diagnostics.Contracts;
+
+namespace System.Collections.Generic
+{
// Implement this interface if you need to support foreach semantics.
// Note that T[] : IList<T>, and we want to ensure that if you use
diff --git a/src/mscorlib/src/System/Collections/Generic/IEnumerator.cs b/src/mscorlib/src/System/Collections/Generic/IEnumerator.cs
index 335616757b..a80f28d3f2 100644
--- a/src/mscorlib/src/System/Collections/Generic/IEnumerator.cs
+++ b/src/mscorlib/src/System/Collections/Generic/IEnumerator.cs
@@ -13,14 +13,16 @@
**
**
===========================================================*/
-namespace System.Collections.Generic {
- using System;
- using System.Runtime.InteropServices;
+using System;
+using System.Runtime.InteropServices;
+
+namespace System.Collections.Generic
+{
// Base interface for all generic enumerators, providing a simple approach
// to iterating over a collection.
public interface IEnumerator<out T> : IDisposable, IEnumerator
- {
+ {
// Returns the current element of the enumeration. The returned value is
// undefined before the first call to MoveNext and following a
// call to MoveNext that returned false. Multiple calls to
@@ -28,8 +30,9 @@ namespace System.Collections.Generic {
// will return the same object.
//
/// <include file='doc\IEnumerator.uex' path='docs/doc[@for="IEnumerator.Current"]/*' />
- new T Current {
- get;
+ new T Current
+ {
+ get;
}
}
}
diff --git a/src/mscorlib/src/System/Collections/Generic/IEqualityComparer.cs b/src/mscorlib/src/System/Collections/Generic/IEqualityComparer.cs
index b6ac3be006..cdcc674e71 100644
--- a/src/mscorlib/src/System/Collections/Generic/IEqualityComparer.cs
+++ b/src/mscorlib/src/System/Collections/Generic/IEqualityComparer.cs
@@ -4,16 +4,17 @@
//
-namespace System.Collections.Generic {
- using System;
+using System;
+namespace System.Collections.Generic
+{
// The generic IEqualityComparer interface implements methods to if check two objects are equal
// and generate Hashcode for an object.
// It is use in Dictionary class.
public interface IEqualityComparer<in T>
{
bool Equals(T x, T y);
- int GetHashCode(T obj);
+ int GetHashCode(T obj);
}
}
diff --git a/src/mscorlib/src/System/Collections/Generic/IList.cs b/src/mscorlib/src/System/Collections/Generic/IList.cs
index 75ca0a9b00..75f8ec460b 100644
--- a/src/mscorlib/src/System/Collections/Generic/IList.cs
+++ b/src/mscorlib/src/System/Collections/Generic/IList.cs
@@ -13,13 +13,14 @@
**
**
===========================================================*/
-namespace System.Collections.Generic {
-
- using System;
- using System.Collections;
- using System.Runtime.CompilerServices;
- using System.Diagnostics.Contracts;
+using System;
+using System.Collections;
+using System.Runtime.CompilerServices;
+using System.Diagnostics.Contracts;
+
+namespace System.Collections.Generic
+{
// An IList is an ordered collection of objects. The exact ordering
// is up to the implementation of the list, ranging from a sorted
// order to insertion order.
@@ -33,21 +34,22 @@ namespace System.Collections.Generic {
public interface IList<T> : ICollection<T>
{
// The Item property provides methods to read and edit entries in the List.
- T this[int index] {
+ 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
index 13bc718760..9b5ca78ee2 100644
--- a/src/mscorlib/src/System/Collections/Generic/IReadOnlyCollection.cs
+++ b/src/mscorlib/src/System/Collections/Generic/IReadOnlyCollection.cs
@@ -11,13 +11,13 @@
** 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
diff --git a/src/mscorlib/src/System/Collections/Generic/IReadOnlyDictionary.cs b/src/mscorlib/src/System/Collections/Generic/IReadOnlyDictionary.cs
index 3603b9a4ea..768de95b61 100644
--- a/src/mscorlib/src/System/Collections/Generic/IReadOnlyDictionary.cs
+++ b/src/mscorlib/src/System/Collections/Generic/IReadOnlyDictionary.cs
@@ -11,6 +11,7 @@
** Purpose: Base interface for read-only generic dictionaries.
**
===========================================================*/
+
using System;
using System.Diagnostics.Contracts;
diff --git a/src/mscorlib/src/System/Collections/Generic/IReadOnlyList.cs b/src/mscorlib/src/System/Collections/Generic/IReadOnlyList.cs
index 77366f0b2f..6917608d38 100644
--- a/src/mscorlib/src/System/Collections/Generic/IReadOnlyList.cs
+++ b/src/mscorlib/src/System/Collections/Generic/IReadOnlyList.cs
@@ -11,13 +11,13 @@
** 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
diff --git a/src/mscorlib/src/System/Collections/Generic/KeyNotFoundException.cs b/src/mscorlib/src/System/Collections/Generic/KeyNotFoundException.cs
index 1cd18cf808..7b552d1192 100644
--- a/src/mscorlib/src/System/Collections/Generic/KeyNotFoundException.cs
+++ b/src/mscorlib/src/System/Collections/Generic/KeyNotFoundException.cs
@@ -13,32 +13,37 @@
**
=============================================================================*/
-namespace System.Collections.Generic {
-
- using System;
- using System.Runtime.Remoting;
- using System.Runtime.Serialization;
+using System;
+using System.Runtime.Remoting;
+using System.Runtime.Serialization;
+
+namespace System.Collections.Generic
+{
[Serializable]
- public class KeyNotFoundException : SystemException, ISerializable {
-
- public KeyNotFoundException ()
- : base(Environment.GetResourceString("Arg_KeyNotFound")) {
+ public class KeyNotFoundException : SystemException, ISerializable
+ {
+ public KeyNotFoundException()
+ : base(Environment.GetResourceString("Arg_KeyNotFound"))
+ {
SetErrorCode(System.__HResults.COR_E_KEYNOTFOUND);
}
-
- public KeyNotFoundException(String message)
- : base(message) {
+
+ public KeyNotFoundException(String message)
+ : base(message)
+ {
SetErrorCode(System.__HResults.COR_E_KEYNOTFOUND);
}
-
- public KeyNotFoundException(String message, Exception innerException)
- : base(message, innerException) {
+
+ public KeyNotFoundException(String message, Exception innerException)
+ : base(message, innerException)
+ {
SetErrorCode(System.__HResults.COR_E_KEYNOTFOUND);
}
- protected KeyNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) {
- }
+ 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
index ba98adad7d..6c611a88e3 100644
--- a/src/mscorlib/src/System/Collections/Generic/KeyValuePair.cs
+++ b/src/mscorlib/src/System/Collections/Generic/KeyValuePair.cs
@@ -13,12 +13,13 @@
**
**
===========================================================*/
-namespace System.Collections.Generic {
-
- using System;
- using System.ComponentModel;
- using System.Text;
+using System;
+using System.ComponentModel;
+using System.Text;
+
+namespace System.Collections.Generic
+{
// Provides the Create factory method for KeyValuePair<TKey, TValue>.
public static class KeyValuePair
{
@@ -33,32 +34,39 @@ namespace System.Collections.Generic {
// It is used by the IEnumerable<T> implementation for both IDictionary<TKey, TValue>
// and IReadOnlyDictionary<TKey, TValue>.
[Serializable]
- public struct KeyValuePair<TKey, TValue> {
+ public struct KeyValuePair<TKey, TValue>
+ {
private TKey key;
private TValue value;
- public KeyValuePair(TKey key, TValue value) {
+ public KeyValuePair(TKey key, TValue value)
+ {
this.key = key;
this.value = value;
}
- public TKey Key {
+ public TKey Key
+ {
get { return key; }
}
- public TValue Value {
+ public TValue Value
+ {
get { return value; }
}
- public override string ToString() {
+ public override string ToString()
+ {
StringBuilder s = StringBuilderCache.Acquire();
s.Append('[');
- if( Key != null) {
+ if (Key != null)
+ {
s.Append(Key.ToString());
}
s.Append(", ");
- if( Value != null) {
- s.Append(Value.ToString());
+ if (Value != null)
+ {
+ s.Append(Value.ToString());
}
s.Append(']');
return StringBuilderCache.GetStringAndRelease(s);
diff --git a/src/mscorlib/src/System/Collections/Generic/List.cs b/src/mscorlib/src/System/Collections/Generic/List.cs
index d654cd265c..fc47b936e0 100644
--- a/src/mscorlib/src/System/Collections/Generic/List.cs
+++ b/src/mscorlib/src/System/Collections/Generic/List.cs
@@ -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));
}
}
}
@@ -238,11 +272,13 @@ namespace System.Collections.Generic
{
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;
@@ -253,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
@@ -284,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)
@@ -296,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);
@@ -309,7 +348,7 @@ namespace System.Collections.Generic
return BinarySearch(0, Count, item, comparer);
}
-
+
// Clears the contents of List.
public void Clear()
{
@@ -329,7 +368,7 @@ namespace System.Collections.Generic
_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().
@@ -349,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;
@@ -373,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);
}
@@ -418,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;
@@ -428,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);
@@ -491,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]);
@@ -582,36 +670,43 @@ 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;
}
@@ -625,7 +720,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);
@@ -633,7 +729,8 @@ namespace System.Collections.Generic
int System.Collections.IList.IndexOf(Object item)
{
- if(IsCompatibleObject(item)) {
+ if (IsCompatibleObject(item))
+ {
return IndexOf((T)item);
}
return -1;
@@ -648,7 +745,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);
@@ -666,46 +764,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));
}
}
@@ -714,44 +818,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
@@ -759,9 +874,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
@@ -774,10 +889,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);
}
}
@@ -810,39 +927,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;
}
@@ -852,33 +977,38 @@ 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++];
}
@@ -898,8 +1028,10 @@ 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();
@@ -914,26 +1046,31 @@ namespace System.Collections.Generic
}
_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);
}
@@ -944,23 +1081,27 @@ namespace System.Collections.Generic
}
}
}
-
+
// 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);
}
@@ -968,12 +1109,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()
@@ -996,32 +1138,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++;
@@ -1029,7 +1178,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);
@@ -1042,7 +1192,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
@@ -1052,21 +1202,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;
}
}
@@ -1106,23 +1262,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;
}
@@ -1130,40 +1288,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..3a8d2630b4 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,13 +200,14 @@ 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"));
if (!(loadFactor >= 0.1f && loadFactor <= 1.0f))
throw new ArgumentOutOfRangeException(nameof(loadFactor), Environment.GetResourceString("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;
@@ -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,63 +278,71 @@ 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) {
+ public virtual bool ContainsKey(Object key)
+ {
+ if (key == null)
+ {
throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key"));
}
Contract.EndContractBlock();
@@ -334,56 +352,64 @@ 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)
@@ -392,7 +418,7 @@ namespace System.Collections {
throw new ArgumentNullException(nameof(array), Environment.GetResourceString("ArgumentNull_Array"));
if (array.Rank != 1)
throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported"));
- if (arrayIndex < 0)
+ if (arrayIndex < 0)
throw new ArgumentOutOfRangeException(nameof(arrayIndex), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (array.Length - arrayIndex < Count)
throw new ArgumentException(Environment.GetResourceString("Arg_ArrayPlusOffTooSmall"));
@@ -404,25 +430,31 @@ 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) {
+ public virtual Object this[Object key]
+ {
+ get
+ {
+ if (key == null)
+ {
throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key"));
}
Contract.EndContractBlock();
@@ -430,14 +462,14 @@ namespace System.Collections {
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) {
+ private void Insert(Object key, Object nvalue, bool add)
+ {
+ if (key == null)
+ {
throw new ArgumentNullException(nameof(key), Environment.GetResourceString("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) {
+ 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));
}
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;
}
@@ -747,37 +806,41 @@ namespace System.Collections {
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"));
}
-
- 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) {
+ public virtual void Remove(Object key)
+ {
+ if (key == null)
+ {
throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key"));
}
Contract.EndContractBlock();
@@ -788,124 +851,141 @@ 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"));
}
-
+
// 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.
+ //
+ // Also, if the Hashtable is using randomized hashing, serialize the old
+ // view of the _keycomparer so perevious frameworks don't see the new types
#pragma warning disable 618
#if FEATURE_RANDOMIZED_STRING_HASHING
- IEqualityComparer keyComparerForSerilization = (IEqualityComparer) HashHelpers.GetEqualityComparerForSerialization(_keycomparer);
+ IEqualityComparer keyComparerForSerilization = (IEqualityComparer)HashHelpers.GetEqualityComparerForSerialization(_keycomparer);
#else
IEqualityComparer keyComparerForSerilization = _keycomparer;
#endif
- 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));
+ }
}
- }
-
+
//
// 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,7 +993,8 @@ namespace System.Collections {
SerializationInfo siInfo;
HashHelpers.SerializationInfoTable.TryGetValue(this, out siInfo);
- if (siInfo==null) {
+ if (siInfo == null)
+ {
throw new SerializationException(Environment.GetResourceString("Serialization_InvalidOnDeser"));
}
@@ -924,14 +1005,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 +1020,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 +1040,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) {
+
+ if (serKeys == null)
+ {
throw new SerializationException(Environment.GetResourceString("Serialization_MissingKeys"));
}
- if (serValues==null) {
+ if (serValues == null)
+ {
throw new SerializationException(Environment.GetResourceString("Serialization_MissingValues"));
}
- if (serKeys.Length!=serValues.Length) {
+ if (serKeys.Length != serValues.Length)
+ {
throw new SerializationException(Environment.GetResourceString("Serialization_KeyValueDifferentSizes"));
}
- for (int i=0; i<serKeys.Length; i++) {
- if (serKeys[i]==null) {
+ for (int i = 0; i < serKeys.Length; i++)
+ {
+ if (serKeys[i] == null)
+ {
throw new SerializationException(Environment.GetResourceString("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)
+ if (arrayIndex < 0)
throw new ArgumentOutOfRangeException(nameof(arrayIndex), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
if (array.Length - arrayIndex < _hashtable.count)
throw new ArgumentException(Environment.GetResourceString("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)
+ if (arrayIndex < 0)
throw new ArgumentOutOfRangeException(nameof(arrayIndex), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
if (array.Length - arrayIndex < _hashtable.count)
throw new ArgumentException(Environment.GetResourceString("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 +1193,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) {
+
+ public override bool ContainsKey(Object key)
+ {
+ if (key == null)
+ {
throw new ArgumentNullException(nameof(key), Environment.GetResourceString("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 +1343,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 +1363,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 +1377,29 @@ namespace System.Collections {
getObjectRetType = getObjRetType;
}
- public Object Clone() {
+ public Object Clone()
+ {
return MemberwiseClone();
}
-
- public virtual Object Key {
- get {
+
+ public virtual Object Key
+ {
+ get
+ {
if (current == false) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumNotStarted));
return currentKey;
}
}
-
- public virtual bool MoveNext() {
+
+ public virtual bool MoveNext()
+ {
if (version != hashtable.version) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumFailedVersion));
- while (bucket > 0) {
+ 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,36 +1409,43 @@ namespace System.Collections {
current = false;
return false;
}
-
- public virtual DictionaryEntry Entry {
- get {
+
+ public virtual DictionaryEntry Entry
+ {
+ get
+ {
if (current == false) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumOpCantHappen));
return new DictionaryEntry(currentKey, currentValue);
}
}
-
-
- public virtual Object Current {
- get {
+
+
+ public virtual Object Current
+ {
+ get
+ {
if (current == false) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumOpCantHappen));
-
- if (getObjectRetType==Keys)
+
+ 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 {
+
+ public virtual Object Value
+ {
+ get
+ {
if (current == false) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumOpCantHappen));
return currentValue;
}
}
-
- public virtual void Reset() {
+
+ public virtual void Reset()
+ {
if (version != hashtable.version) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumFailedVersion));
current = false;
bucket = hashtable.buckets.Length;
@@ -1306,17 +1453,17 @@ namespace System.Collections {
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 +1491,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 +1503,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 +1520,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"));
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 +1534,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 +1551,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;
}
@@ -1420,14 +1566,14 @@ namespace System.Collections {
public static object GetEqualityComparerForSerialization(object comparer)
{
- if(comparer == null)
+ if (comparer == null)
{
return null;
}
IWellKnownStringEqualityComparer cmp = comparer as IWellKnownStringEqualityComparer;
- if(cmp != null)
+ if (cmp != null)
{
return cmp.GetEqualityComparerForSerialization();
}
diff --git a/src/mscorlib/src/System/Collections/ICollection.cs b/src/mscorlib/src/System/Collections/ICollection.cs
index 088928a0ef..49108e013e 100644
--- a/src/mscorlib/src/System/Collections/ICollection.cs
+++ b/src/mscorlib/src/System/Collections/ICollection.cs
@@ -13,10 +13,12 @@
**
**
===========================================================*/
-namespace System.Collections {
- using System;
- using System.Diagnostics.Contracts;
+using System;
+using System.Diagnostics.Contracts;
+
+namespace System.Collections
+{
// Base interface for all collections, defining enumerators, size, and
// synchronization methods.
public interface ICollection : IEnumerable
@@ -26,12 +28,12 @@ namespace System.Collections {
// 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
@@ -67,7 +69,7 @@ namespace System.Collections {
// 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
diff --git a/src/mscorlib/src/System/Collections/IComparer.cs b/src/mscorlib/src/System/Collections/IComparer.cs
index 574af1a768..181d102bcb 100644
--- a/src/mscorlib/src/System/Collections/IComparer.cs
+++ b/src/mscorlib/src/System/Collections/IComparer.cs
@@ -13,15 +13,18 @@
**
**
===========================================================*/
-namespace System.Collections {
-
- using System;
+
+using System;
+
+namespace System.Collections
+{
// The IComparer interface implements a method that compares two objects. It is
// used in conjunction with the Sort and BinarySearch methods on
// the Array and List classes.
//
// Interfaces are not serializable
- public interface IComparer {
+ 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.
diff --git a/src/mscorlib/src/System/Collections/IDictionary.cs b/src/mscorlib/src/System/Collections/IDictionary.cs
index 519d53ed55..e28cf3b2a4 100644
--- a/src/mscorlib/src/System/Collections/IDictionary.cs
+++ b/src/mscorlib/src/System/Collections/IDictionary.cs
@@ -13,10 +13,12 @@
**
**
===========================================================*/
-namespace System.Collections {
- using System;
- using System.Diagnostics.Contracts;
+using System;
+using System.Diagnostics.Contracts;
+
+namespace System.Collections
+{
// An IDictionary is a possibly unordered set of key-value pairs.
// Keys can be any non-null object. Values can be any object.
// You can look up a value in an IDictionary via the default indexed
@@ -26,33 +28,36 @@ namespace System.Collections {
// Interfaces are not serializable
// The Item property provides methods to read and edit entries
// in the Dictionary.
- Object this[Object key] {
+ Object this[Object key]
+ {
get;
set;
}
-
+
// Returns a collections of the keys in this dictionary.
- ICollection Keys {
+ ICollection Keys
+ {
get;
}
-
+
// Returns a collections of the values in this dictionary.
- ICollection Values {
+ 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
+
+ bool IsReadOnly
{ get; }
bool IsFixedSize
@@ -60,7 +65,7 @@ namespace System.Collections {
// 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
index 2f1add682c..c8d305a8ff 100644
--- a/src/mscorlib/src/System/Collections/IDictionaryEnumerator.cs
+++ b/src/mscorlib/src/System/Collections/IDictionaryEnumerator.cs
@@ -13,10 +13,12 @@
**
**
===========================================================*/
-namespace System.Collections {
- // Interfaces are not serializable
-
- using System;
+// Interfaces are not serializable
+
+using System;
+
+namespace System.Collections
+{
// This interface represents an enumerator that allows sequential access to the
// elements of a dictionary. Upon creation, an enumerator is conceptually
// positioned before the first element of the enumeration. The first call to the
@@ -52,27 +54,30 @@ namespace System.Collections {
// GetKey with no intervening calls to GetNext will return
// the same object.
//
- Object Key {
- get;
+ 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 {
+ 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;
+ DictionaryEntry Entry
+ {
+ get;
}
}
}
diff --git a/src/mscorlib/src/System/Collections/IEnumerable.cs b/src/mscorlib/src/System/Collections/IEnumerable.cs
index 1d8e71cf07..a48d1e5d90 100644
--- a/src/mscorlib/src/System/Collections/IEnumerable.cs
+++ b/src/mscorlib/src/System/Collections/IEnumerable.cs
@@ -13,11 +13,13 @@
**
**
===========================================================*/
-namespace System.Collections {
- using System;
- using System.Diagnostics.Contracts;
- using System.Runtime.InteropServices;
+using System;
+using System.Diagnostics.Contracts;
+using System.Runtime.InteropServices;
+
+namespace System.Collections
+{
// 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")]
diff --git a/src/mscorlib/src/System/Collections/IEnumerator.cs b/src/mscorlib/src/System/Collections/IEnumerator.cs
index 4c4fc085e8..bc57ddb6a0 100644
--- a/src/mscorlib/src/System/Collections/IEnumerator.cs
+++ b/src/mscorlib/src/System/Collections/IEnumerator.cs
@@ -13,10 +13,12 @@
**
**
===========================================================*/
-namespace System.Collections {
- using System;
- using System.Runtime.InteropServices;
+using System;
+using System.Runtime.InteropServices;
+
+namespace System.Collections
+{
// Base interface for all enumerators, providing a simple approach
// to iterating over a collection.
[Guid("496B0ABF-CDEE-11d3-88E8-00902754C43A")]
@@ -30,17 +32,18 @@ namespace System.Collections {
// 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;
+ 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
diff --git a/src/mscorlib/src/System/Collections/IEqualityComparer.cs b/src/mscorlib/src/System/Collections/IEqualityComparer.cs
index f591b11152..622bec14a6 100644
--- a/src/mscorlib/src/System/Collections/IEqualityComparer.cs
+++ b/src/mscorlib/src/System/Collections/IEqualityComparer.cs
@@ -14,13 +14,16 @@
**
**
===========================================================*/
-namespace System.Collections {
-
- using System;
+
+using System;
+
+namespace System.Collections
+{
// An IEqualityComparer is a mechanism to consume custom performant comparison infrastructure
// that can be consumed by some of the common collections.
- public interface IEqualityComparer {
+ public interface IEqualityComparer
+ {
bool Equals(Object x, Object y);
- int GetHashCode(Object obj);
+ 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
index 8b63400852..b3ee8ecbd0 100644
--- a/src/mscorlib/src/System/Collections/IList.cs
+++ b/src/mscorlib/src/System/Collections/IList.cs
@@ -13,57 +13,59 @@
**
**
===========================================================*/
-namespace System.Collections {
-
- using System;
- using System.Diagnostics.Contracts;
+using System;
+using System.Diagnostics.Contracts;
+
+namespace System.Collections
+{
// An IList is an ordered collection of objects. The exact ordering
// is up to the implementation of the list, ranging from a sorted
// order to insertion order.
public interface IList : ICollection
{
// The Item property provides methods to read and edit entries in the List.
- Object this[int index] {
+ 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
+ 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
index 1b6f3aff7a..a5e4834b9b 100644
--- a/src/mscorlib/src/System/Collections/IStructuralComparable.cs
+++ b/src/mscorlib/src/System/Collections/IStructuralComparable.cs
@@ -1,11 +1,13 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System;
-namespace System.Collections {
+using System;
- public interface IStructuralComparable {
+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
index 5a5295fc38..4e61d5e75f 100644
--- a/src/mscorlib/src/System/Collections/IStructuralEquatable.cs
+++ b/src/mscorlib/src/System/Collections/IStructuralEquatable.cs
@@ -1,9 +1,11 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace System.Collections {
- public interface IStructuralEquatable {
+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..bfd11588f3 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) {
+ public Object this[Object key]
+ {
+ get
+ {
+ if (key == null)
+ {
throw new ArgumentNullException(nameof(key), Environment.GetResourceString("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) {
+ set
+ {
+ if (key == null)
+ {
throw new ArgumentNullException(nameof(key), Environment.GetResourceString("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) {
+ public void Add(Object key, Object value)
+ {
+ if (key == null)
+ {
throw new ArgumentNullException(nameof(key), Environment.GetResourceString("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))
+ {
throw new ArgumentException(Environment.GetResourceString("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) {
+ public bool Contains(Object key)
+ {
+ if (key == null)
+ {
throw new ArgumentNullException(nameof(key), Environment.GetResourceString("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"));
if (index < 0)
- throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("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(Environment.GetResourceString("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) {
+ public void Remove(Object key)
+ {
+ if (key == null)
+ {
throw new ArgumentNullException(nameof(key), Environment.GetResourceString("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) {
+ public DictionaryEntry Entry
+ {
+ get
+ {
+ if (current == null)
+ {
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen"));
}
return new DictionaryEntry(current.key, current.value);
}
}
- public Object Key {
- get {
- if (current == null) {
+ public Object Key
+ {
+ get
+ {
+ if (current == null)
+ {
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen"));
}
return current.key;
}
}
- public Object Value {
- get {
- if (current == null) {
+ public Object Value
+ {
+ get
+ {
+ if (current == null)
+ {
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen"));
}
return current.value;
}
}
- public bool MoveNext() {
- if (version != list.version) {
+ public bool MoveNext()
+ {
+ if (version != list.version)
+ {
throw new InvalidOperationException(Environment.GetResourceString("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) {
+ public void Reset()
+ {
+ if (version != list.version)
+ {
throw new InvalidOperationException(Environment.GetResourceString("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"));
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("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(Environment.GetResourceString("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) {
+ public Object Current
+ {
+ get
+ {
+ if (current == null)
+ {
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen"));
}
return isKeys ? current.key : current.value;
}
}
- public bool MoveNext() {
- if (version != list.version) {
+ public bool MoveNext()
+ {
+ if (version != list.version)
+ {
throw new InvalidOperationException(Environment.GetResourceString("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) {
+ public void Reset()
+ {
+ if (version != list.version)
+ {
throw new InvalidOperationException(Environment.GetResourceString("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
index 3fe7716203..f94fdd8cbe 100644
--- a/src/mscorlib/src/System/Collections/ObjectModel/KeyedCollection.cs
+++ b/src/mscorlib/src/System/Collections/ObjectModel/KeyedCollection.cs
@@ -4,77 +4,90 @@
//
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+
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>
+ [DebuggerDisplay("Count = {Count}")]
+ public abstract class KeyedCollection<TKey, TItem> : Collection<TItem>
{
- const int defaultThreshold = 0;
+ private const int defaultThreshold = 0;
- IEqualityComparer<TKey> comparer;
- Dictionary<TKey,TItem> dict;
- int keyCount;
- int threshold;
+ private IEqualityComparer<TKey> comparer;
+ private Dictionary<TKey, TItem> dict;
+ private int keyCount;
+ private int threshold;
- protected KeyedCollection(): this(null, defaultThreshold) {}
+ protected KeyedCollection() : this(null, defaultThreshold) { }
- protected KeyedCollection(IEqualityComparer<TKey> comparer): this(comparer, 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) {
+ : 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) {
+ if (dictionaryCreationThreshold == -1)
+ {
dictionaryCreationThreshold = int.MaxValue;
}
- if( dictionaryCreationThreshold < -1) {
+ if (dictionaryCreationThreshold < -1)
+ {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.dictionaryCreationThreshold, ExceptionResource.ArgumentOutOfRange_InvalidThreshold);
}
this.comparer = comparer;
- this.threshold = dictionaryCreationThreshold;
+ 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 {
+ 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 IEqualityComparer<TKey> Comparer
+ {
+ get
+ {
+ return comparer;
+ }
}
- public TItem this[TKey key] {
- get {
- if( key == null) {
+ public TItem this[TKey key]
+ {
+ get
+ {
+ if (key == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
- if (dict != null) {
+ if (dict != null)
+ {
return dict[key];
}
- foreach (TItem item in Items) {
+ foreach (TItem item in Items)
+ {
if (comparer.Equals(GetKeyForItem(item), key)) return item;
}
@@ -83,50 +96,63 @@ namespace System.Collections.ObjectModel
}
}
- public bool Contains(TKey key) {
- if( key == null) {
+ public bool Contains(TKey key)
+ {
+ if (key == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
-
- if (dict != null) {
+
+ if (dict != null)
+ {
return dict.ContainsKey(key);
}
- foreach (TItem item in Items) {
+ foreach (TItem item in Items)
+ {
if (comparer.Equals(GetKeyForItem(item), key)) return true;
}
return false;
}
- private bool ContainsItem(TItem item) {
+ private bool ContainsItem(TItem item)
+ {
TKey key;
- if( (dict == null) || ((key = GetKeyForItem(item)) == null)) {
+ if ((dict == null) || ((key = GetKeyForItem(item)) == null))
+ {
return Items.Contains(item);
}
TItem itemInDict;
bool exist = dict.TryGetValue(key, out itemInDict);
- if( exist) {
+ if (exist)
+ {
return EqualityComparer<TItem>.Default.Equals(itemInDict, item);
}
return false;
}
- public bool Remove(TKey key) {
- if( key == null) {
+ public bool Remove(TKey key)
+ {
+ if (key == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
-
- if (dict != null) {
- if (dict.ContainsKey(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)) {
+ for (int i = 0; i < Items.Count; i++)
+ {
+ if (comparer.Equals(GetKeyForItem(Items[i]), key))
+ {
RemoveItem(i);
return true;
}
@@ -134,31 +160,39 @@ namespace System.Collections.ObjectModel
return false;
}
- protected IDictionary<TKey,TItem> Dictionary {
+ protected IDictionary<TKey, TItem> Dictionary
+ {
get { return dict; }
}
- protected void ChangeItemKey(TItem item, TKey newKey) {
+ protected void ChangeItemKey(TItem item, TKey newKey)
+ {
// check if the item exists in the collection
- if( !ContainsItem(item)) {
+ if (!ContainsItem(item))
+ {
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_ItemNotExist);
}
- TKey oldKey = GetKeyForItem(item);
- if (!comparer.Equals(oldKey, newKey)) {
- if (newKey != null) {
+ TKey oldKey = GetKeyForItem(item);
+ if (!comparer.Equals(oldKey, newKey))
+ {
+ if (newKey != null)
+ {
AddKey(newKey, item);
}
- if (oldKey != null) {
+ if (oldKey != null)
+ {
RemoveKey(oldKey);
}
}
}
- protected override void ClearItems() {
+ protected override void ClearItems()
+ {
base.ClearItems();
- if (dict != null) {
+ if (dict != null)
+ {
dict.Clear();
}
@@ -167,53 +201,68 @@ namespace System.Collections.ObjectModel
protected abstract TKey GetKeyForItem(TItem item);
- protected override void InsertItem(int index, TItem item) {
+ protected override void InsertItem(int index, TItem item)
+ {
TKey key = GetKeyForItem(item);
- if (key != null) {
+ if (key != null)
+ {
AddKey(key, item);
}
base.InsertItem(index, item);
}
- protected override void RemoveItem(int index) {
+ protected override void RemoveItem(int index)
+ {
TKey key = GetKeyForItem(Items[index]);
- if (key != null) {
+ if (key != null)
+ {
RemoveKey(key);
}
base.RemoveItem(index);
}
- protected override void SetItem(int index, TItem item) {
+ 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) {
+ if (comparer.Equals(oldKey, newKey))
+ {
+ if (newKey != null && dict != null)
+ {
dict[newKey] = item;
}
}
- else {
- if (newKey != null) {
+ else
+ {
+ if (newKey != null)
+ {
AddKey(newKey, item);
}
- if (oldKey != null) {
+ if (oldKey != null)
+ {
RemoveKey(oldKey);
}
}
base.SetItem(index, item);
}
- private void AddKey(TKey key, TItem item) {
- if (dict != null) {
+ private void AddKey(TKey key, TItem item)
+ {
+ if (dict != null)
+ {
dict.Add(key, item);
}
- else if (keyCount == threshold) {
+ else if (keyCount == threshold)
+ {
CreateDictionary();
dict.Add(key, item);
}
- else {
- if (Contains(key)) {
+ else
+ {
+ if (Contains(key))
+ {
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate);
}
@@ -221,22 +270,28 @@ namespace System.Collections.ObjectModel
}
}
- private void CreateDictionary() {
- dict = new Dictionary<TKey,TItem>(comparer);
- foreach (TItem item in Items) {
+ private void CreateDictionary()
+ {
+ dict = new Dictionary<TKey, TItem>(comparer);
+ foreach (TItem item in Items)
+ {
TKey key = GetKeyForItem(item);
- if (key != null) {
+ if (key != null)
+ {
dict.Add(key, item);
}
}
}
- private void RemoveKey(TKey key) {
+ private void RemoveKey(TKey key)
+ {
Debug.Assert(key != null, "key shouldn't be null!");
- if (dict != null) {
+ if (dict != null)
+ {
dict.Remove(key);
}
- else {
+ 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..d94d9fd944 100644
--- a/src/mscorlib/src/System/Collections/ObjectModel/ReadOnlyDictionary.cs
+++ b/src/mscorlib/src/System/Collections/ObjectModel/ReadOnlyDictionary.cs
@@ -11,14 +11,14 @@
**
===========================================================*/
+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}")]
@@ -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
index 685af59c4b..bcd805dc29 100644
--- a/src/mscorlib/src/System/Collections/StructuralComparisons.cs
+++ b/src/mscorlib/src/System/Collections/StructuralComparisons.cs
@@ -6,16 +6,20 @@
using System;
-namespace System.Collections {
- public static class StructuralComparisons {
-
+namespace System.Collections
+{
+ public static class StructuralComparisons
+ {
private static volatile IComparer s_StructuralComparer;
private static volatile IEqualityComparer s_StructuralEqualityComparer;
- public static IComparer StructuralComparer {
- get {
+ public static IComparer StructuralComparer
+ {
+ get
+ {
IComparer comparer = s_StructuralComparer;
- if (comparer == null) {
+ if (comparer == null)
+ {
comparer = new StructuralComparer();
s_StructuralComparer = comparer;
}
@@ -23,10 +27,13 @@ namespace System.Collections {
}
}
- public static IEqualityComparer StructuralEqualityComparer {
- get {
+ public static IEqualityComparer StructuralEqualityComparer
+ {
+ get
+ {
IEqualityComparer comparer = s_StructuralEqualityComparer;
- if (comparer == null) {
+ if (comparer == null)
+ {
comparer = new StructuralEqualityComparer();
s_StructuralEqualityComparer = comparer;
}
@@ -36,19 +43,25 @@ namespace System.Collections {
}
[Serializable]
- internal class StructuralEqualityComparer : IEqualityComparer {
- public new bool Equals(Object x, Object y) {
- if (x != null) {
-
+ internal class StructuralEqualityComparer : IEqualityComparer
+ {
+ public new bool Equals(Object x, Object y)
+ {
+ if (x != null)
+ {
IStructuralEquatable seObj = x as IStructuralEquatable;
- if (seObj != null){
+ if (seObj != null)
+ {
return seObj.Equals(y, this);
}
- if (y != null) {
+ if (y != null)
+ {
return x.Equals(y);
- } else {
+ }
+ else
+ {
return false;
}
}
@@ -56,12 +69,14 @@ namespace System.Collections {
return true;
}
- public int GetHashCode(Object obj) {
+ public int GetHashCode(Object obj)
+ {
if (obj == null) return 0;
IStructuralEquatable seObj = obj as IStructuralEquatable;
- if (seObj != null) {
+ if (seObj != null)
+ {
return seObj.GetHashCode(this);
}
@@ -70,20 +85,21 @@ namespace System.Collections {
}
[Serializable]
- internal class StructuralComparer : IComparer {
- public int Compare(Object x, Object y) {
-
+ 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) {
+ 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
index a7946f8203..9b4d6e626e 100644
--- a/src/mscorlib/src/System/ComponentModel/EditorBrowsableAttribute.cs
+++ b/src/mscorlib/src/System/ComponentModel/EditorBrowsableAttribute.cs
@@ -14,7 +14,7 @@ namespace System.ComponentModel
browsableState = state;
}
- public EditorBrowsableAttribute () : this(EditorBrowsableState.Always) { }
+ public EditorBrowsableAttribute() : this(EditorBrowsableState.Always) { }
public EditorBrowsableState State
{
diff --git a/src/mscorlib/src/System/Configuration/Assemblies/AssemblyHashAlgorithm.cs b/src/mscorlib/src/System/Configuration/Assemblies/AssemblyHashAlgorithm.cs
index a19d0344b1..b3e6b21435 100644
--- a/src/mscorlib/src/System/Configuration/Assemblies/AssemblyHashAlgorithm.cs
+++ b/src/mscorlib/src/System/Configuration/Assemblies/AssemblyHashAlgorithm.cs
@@ -10,11 +10,14 @@
**
**
===========================================================*/
+
using System.Runtime.InteropServices;
-namespace System.Configuration.Assemblies {
-
- using System;
+
+using System;
+
+namespace System.Configuration.Assemblies
+{
[Serializable]
public enum AssemblyHashAlgorithm
{
diff --git a/src/mscorlib/src/System/Configuration/Assemblies/AssemblyVersionCompatibility.cs b/src/mscorlib/src/System/Configuration/Assemblies/AssemblyVersionCompatibility.cs
index b7e9c30c62..f1d5ff0221 100644
--- a/src/mscorlib/src/System/Configuration/Assemblies/AssemblyVersionCompatibility.cs
+++ b/src/mscorlib/src/System/Configuration/Assemblies/AssemblyVersionCompatibility.cs
@@ -10,14 +10,16 @@
**
**
===========================================================*/
-namespace System.Configuration.Assemblies {
-
- using System;
- [Serializable]
+
+using System;
+
+namespace System.Configuration.Assemblies
+{
+ [Serializable]
public enum AssemblyVersionCompatibility
{
- SameMachine = 1,
- SameProcess = 2,
- SameDomain = 3,
+ SameMachine = 1,
+ SameProcess = 2,
+ SameDomain = 3,
}
}
diff --git a/src/mscorlib/src/System/Convert.cs b/src/mscorlib/src/System/Convert.cs
index 0cd3c5d715..7228e229d7 100644
--- a/src/mscorlib/src/System/Convert.cs
+++ b/src/mscorlib/src/System/Convert.cs
@@ -23,10 +23,11 @@ using System.Diagnostics;
using System.Diagnostics.Contracts;
-namespace System {
-
+namespace System
+{
[Flags]
- public enum Base64FormattingOptions {
+ public enum Base64FormattingOptions
+ {
None = 0,
InsertLineBreaks = 1
}
@@ -91,7 +92,7 @@ namespace System {
// 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
@@ -106,8 +107,8 @@ namespace System {
// When passed Value.DBNull, the Value.ToXXX() methods all throw an
// InvalidCastException.
- public static class Convert {
-
+ 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.
@@ -140,20 +141,21 @@ namespace System {
'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','+','/','=' };
+ '8','9','+','/','=' };
- private const Int32 base64LineBreakPosition = 76;
+ private const Int32 base64LineBreakPosition = 76;
#if _DEBUG
private static bool TriggerAsserts = DoAsserts();
- private static bool DoAsserts() {
- Debug.Assert(ConvertTypes!=null, "[Convert.cctor]ConvertTypes!=null");
+ 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),
+ 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),
+ 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),
+ Debug.Assert(ConvertTypes[(int)TypeCode.Int32] == typeof(int),
"[Convert.cctor]ConvertTypes[(int)TypeCode.Int32]==typeof(int)");
return true;
}
@@ -167,7 +169,8 @@ namespace System {
// 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) {
+ public static TypeCode GetTypeCode(object value)
+ {
if (value == null) return TypeCode.Empty;
IConvertible temp = value as IConvertible;
if (temp != null)
@@ -180,10 +183,11 @@ namespace System {
// 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) {
+ 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;
+ return convertible != null ? convertible.GetTypeCode() == TypeCode.DBNull : false;
}
// Converts the given object to the given type. In general, this method is
@@ -198,68 +202,75 @@ namespace System {
// 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) {
+ 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)) {
+ 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) {
+ 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"));
+ 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) {
+ internal static Object DefaultToType(IConvertible value, Type targetType, IFormatProvider provider)
+ {
Contract.Requires(value != null, "[Convert.DefaultToType]value!=null");
- if (targetType==null) {
+ if (targetType == null)
+ {
throw new ArgumentNullException(nameof(targetType));
}
Contract.EndContractBlock();
@@ -317,26 +328,33 @@ namespace System {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", value.GetType().FullName, targetType.FullName));
}
- public static Object ChangeType(Object value, Type conversionType) {
+ 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) {
+ 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) {
+ if (value == null)
+ {
+ if (conversionType.IsValueType)
+ {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_CannotCastNullToValueType"));
}
- return null;
+ return null;
}
IConvertible ic = value as IConvertible;
- if (ic == null) {
- if ( value.GetType() == conversionType) {
+ if (ic == null)
+ {
+ if (value.GetType() == conversionType)
+ {
return value;
}
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_IConvertible"));
@@ -344,37 +362,37 @@ namespace System {
RuntimeType rtConversionType = conversionType as RuntimeType;
- if (rtConversionType==ConvertTypes[(int)TypeCode.Boolean])
+ if (rtConversionType == ConvertTypes[(int)TypeCode.Boolean])
return ic.ToBoolean(provider);
- if (rtConversionType==ConvertTypes[(int)TypeCode.Char])
+ if (rtConversionType == ConvertTypes[(int)TypeCode.Char])
return ic.ToChar(provider);
- if (rtConversionType==ConvertTypes[(int)TypeCode.SByte])
+ if (rtConversionType == ConvertTypes[(int)TypeCode.SByte])
return ic.ToSByte(provider);
- if (rtConversionType==ConvertTypes[(int)TypeCode.Byte])
+ if (rtConversionType == ConvertTypes[(int)TypeCode.Byte])
return ic.ToByte(provider);
- if (rtConversionType==ConvertTypes[(int)TypeCode.Int16])
+ if (rtConversionType == ConvertTypes[(int)TypeCode.Int16])
return ic.ToInt16(provider);
- if (rtConversionType==ConvertTypes[(int)TypeCode.UInt16])
+ if (rtConversionType == ConvertTypes[(int)TypeCode.UInt16])
return ic.ToUInt16(provider);
- if (rtConversionType==ConvertTypes[(int)TypeCode.Int32])
+ if (rtConversionType == ConvertTypes[(int)TypeCode.Int32])
return ic.ToInt32(provider);
- if (rtConversionType==ConvertTypes[(int)TypeCode.UInt32])
+ if (rtConversionType == ConvertTypes[(int)TypeCode.UInt32])
return ic.ToUInt32(provider);
- if (rtConversionType==ConvertTypes[(int)TypeCode.Int64])
+ if (rtConversionType == ConvertTypes[(int)TypeCode.Int64])
return ic.ToInt64(provider);
- if (rtConversionType==ConvertTypes[(int)TypeCode.UInt64])
+ if (rtConversionType == ConvertTypes[(int)TypeCode.UInt64])
return ic.ToUInt64(provider);
- if (rtConversionType==ConvertTypes[(int)TypeCode.Single])
+ if (rtConversionType == ConvertTypes[(int)TypeCode.Single])
return ic.ToSingle(provider);
- if (rtConversionType==ConvertTypes[(int)TypeCode.Double])
+ if (rtConversionType == ConvertTypes[(int)TypeCode.Double])
return ic.ToDouble(provider);
- if (rtConversionType==ConvertTypes[(int)TypeCode.Decimal])
+ if (rtConversionType == ConvertTypes[(int)TypeCode.Decimal])
return ic.ToDecimal(provider);
- if (rtConversionType==ConvertTypes[(int)TypeCode.DateTime])
+ if (rtConversionType == ConvertTypes[(int)TypeCode.DateTime])
return ic.ToDateTime(provider);
- if (rtConversionType==ConvertTypes[(int)TypeCode.String])
+ if (rtConversionType == ConvertTypes[(int)TypeCode.String])
return ic.ToString(provider);
- if (rtConversionType==ConvertTypes[(int)TypeCode.Object])
+ if (rtConversionType == ConvertTypes[(int)TypeCode.Object])
return (Object)value;
return ic.ToType(conversionType, provider);
@@ -408,69 +426,83 @@ namespace System {
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)
+ {
+ 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(Object value, IFormatProvider provider)
+ {
+ return value == null ? false : ((IConvertible)value).ToBoolean(provider);
}
- public static bool ToBoolean(bool value) {
+ public static bool ToBoolean(bool value)
+ {
return value;
}
[CLSCompliant(false)]
- public static bool ToBoolean(sbyte value) {
+ 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) {
+ public static bool ToBoolean(char value)
+ {
return ((IConvertible)value).ToBoolean(null);
}
- public static bool ToBoolean(byte value) {
+ public static bool ToBoolean(byte value)
+ {
return value != 0;
}
- public static bool ToBoolean(short value) {
+ public static bool ToBoolean(short value)
+ {
return value != 0;
}
- [CLSCompliant(false)]
- public static bool ToBoolean(ushort value) {
+ [CLSCompliant(false)]
+ public static bool ToBoolean(ushort value)
+ {
return value != 0;
}
- public static bool ToBoolean(int value) {
+ public static bool ToBoolean(int value)
+ {
return value != 0;
}
- [CLSCompliant(false)]
- public static bool ToBoolean(uint value) {
+ [CLSCompliant(false)]
+ public static bool ToBoolean(uint value)
+ {
return value != 0;
}
- public static bool ToBoolean(long value) {
+ public static bool ToBoolean(long value)
+ {
return value != 0;
}
- [CLSCompliant(false)]
- public static bool ToBoolean(ulong value) {
+ [CLSCompliant(false)]
+ public static bool ToBoolean(ulong value)
+ {
return value != 0;
}
- public static bool ToBoolean(String value) {
+ public static bool ToBoolean(String value)
+ {
if (value == null)
return false;
return Boolean.Parse(value);
}
- public static bool ToBoolean(String value, IFormatProvider provider) {
+ public static bool ToBoolean(String value, IFormatProvider provider)
+ {
if (value == null)
return false;
return Boolean.Parse(value);
@@ -480,7 +512,7 @@ namespace System {
{
return value != 0;
}
-
+
public static bool ToBoolean(double value)
{
return value != 0;
@@ -495,72 +527,84 @@ namespace System {
{
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)
+ {
+ 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(object value, IFormatProvider provider)
+ {
+ return value == null ? (char)0 : ((IConvertible)value).ToChar(provider);
}
- public static char ToChar(bool value) {
+ public static char ToChar(bool value)
+ {
return ((IConvertible)value).ToChar(null);
}
- public static char ToChar(char value) {
+ public static char ToChar(char value)
+ {
return value;
}
[CLSCompliant(false)]
- public static char ToChar(sbyte value) {
+ public static char ToChar(sbyte value)
+ {
if (value < 0) ThrowCharOverflowException();
Contract.EndContractBlock();
return (char)value;
}
- public static char ToChar(byte value) {
+ public static char ToChar(byte value)
+ {
return (char)value;
}
- public static char ToChar(short value) {
+ public static char ToChar(short value)
+ {
if (value < 0) ThrowCharOverflowException();
Contract.EndContractBlock();
return (char)value;
}
- [CLSCompliant(false)]
- public static char ToChar(ushort value) {
+ [CLSCompliant(false)]
+ public static char ToChar(ushort value)
+ {
return (char)value;
}
- public static char ToChar(int 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) {
+ [CLSCompliant(false)]
+ public static char ToChar(uint value)
+ {
if (value > Char.MaxValue) ThrowCharOverflowException();
Contract.EndContractBlock();
return (char)value;
}
- public static char ToChar(long 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) {
+ [CLSCompliant(false)]
+ public static char ToChar(ulong value)
+ {
if (value > Char.MaxValue) ThrowCharOverflowException();
Contract.EndContractBlock();
return (char)value;
@@ -570,16 +614,18 @@ namespace System {
// @VariantSwitch
// Remove FormatExceptions;
//
- public static char ToChar(String value) {
+ public static char ToChar(String value)
+ {
return ToChar(value, null);
}
- public static char ToChar(String value, IFormatProvider provider) {
- if (value == null)
+ public static char ToChar(String value, IFormatProvider provider)
+ {
+ if (value == null)
throw new ArgumentNullException(nameof(value));
Contract.EndContractBlock();
-
- if (value.Length != 1)
+
+ if (value.Length != 1)
throw new FormatException(Environment.GetResourceString(ResId.Format_NeedSingleChar));
return value[0];
@@ -614,109 +660,126 @@ namespace System {
// 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);
+ 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);
+ 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;
+ public static sbyte ToSByte(bool value)
+ {
+ return value ? (sbyte)Boolean.True : (sbyte)Boolean.False;
}
[CLSCompliant(false)]
- public static sbyte ToSByte(sbyte value) {
+ public static sbyte ToSByte(sbyte value)
+ {
return value;
}
[CLSCompliant(false)]
- public static sbyte ToSByte(char value) {
+ public static sbyte ToSByte(char value)
+ {
if (value > SByte.MaxValue) ThrowSByteOverflowException();
Contract.EndContractBlock();
return (sbyte)value;
}
[CLSCompliant(false)]
- public static sbyte ToSByte(byte value) {
+ public static sbyte ToSByte(byte value)
+ {
if (value > SByte.MaxValue) ThrowSByteOverflowException();
Contract.EndContractBlock();
return (sbyte)value;
}
[CLSCompliant(false)]
- public static sbyte ToSByte(short value) {
+ 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) {
+ [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) {
+ 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) {
+ [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) {
+ 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) {
+ [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) {
+ public static sbyte ToSByte(float value)
+ {
return ToSByte((double)value);
}
[CLSCompliant(false)]
- public static sbyte ToSByte(double value) {
+ public static sbyte ToSByte(double value)
+ {
return ToSByte(ToInt32(value));
}
[CLSCompliant(false)]
- public static sbyte ToSByte(decimal value) {
+ public static sbyte ToSByte(decimal value)
+ {
return Decimal.ToSByte(Decimal.Round(value, 0));
}
[CLSCompliant(false)]
- public static sbyte ToSByte(String value) {
+ 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) {
+ public static sbyte ToSByte(String value, IFormatProvider provider)
+ {
return SByte.Parse(value, NumberStyles.Integer, provider);
}
@@ -731,93 +794,110 @@ namespace System {
// Conversions to Byte
- public static byte ToByte(object value) {
- return value == null? (byte)0: ((IConvertible)value).ToByte(null);
+ 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(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(bool value)
+ {
+ return value ? (byte)Boolean.True : (byte)Boolean.False;
}
- public static byte ToByte(byte value) {
+ public static byte ToByte(byte value)
+ {
return value;
}
- public static byte ToByte(char 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) {
+ public static byte ToByte(sbyte value)
+ {
if (value < Byte.MinValue) ThrowByteOverflowException();
Contract.EndContractBlock();
return (byte)value;
}
- public static byte ToByte(short 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) {
+ [CLSCompliant(false)]
+ public static byte ToByte(ushort value)
+ {
if (value > Byte.MaxValue) ThrowByteOverflowException();
Contract.EndContractBlock();
return (byte)value;
}
- public static byte ToByte(int 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) {
+ [CLSCompliant(false)]
+ public static byte ToByte(uint value)
+ {
if (value > Byte.MaxValue) ThrowByteOverflowException();
Contract.EndContractBlock();
return (byte)value;
}
- public static byte ToByte(long 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) {
+ [CLSCompliant(false)]
+ public static byte ToByte(ulong value)
+ {
if (value > Byte.MaxValue) ThrowByteOverflowException();
Contract.EndContractBlock();
return (byte)value;
}
- public static byte ToByte(float value) {
+ public static byte ToByte(float value)
+ {
return ToByte((double)value);
}
- public static byte ToByte(double value) {
+ public static byte ToByte(double value)
+ {
return ToByte(ToInt32(value));
}
- public static byte ToByte(decimal value) {
+ public static byte ToByte(decimal value)
+ {
return Decimal.ToByte(Decimal.Round(value, 0));
}
- public static byte ToByte(String value) {
+ 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) {
+ public static byte ToByte(String value, IFormatProvider provider)
+ {
if (value == null)
return 0;
return Byte.Parse(value, NumberStyles.Integer, provider);
@@ -834,89 +914,106 @@ namespace System {
// Conversions to Int16
- public static short ToInt16(object value) {
- return value == null? (short)0: ((IConvertible)value).ToInt16(null);
+ 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(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(bool value)
+ {
+ return value ? (short)Boolean.True : (short)Boolean.False;
}
- public static short ToInt16(char value) {
+ public static short ToInt16(char value)
+ {
if (value > Int16.MaxValue) ThrowInt16OverflowException();
Contract.EndContractBlock();
return (short)value;
}
[CLSCompliant(false)]
- public static short ToInt16(sbyte value) {
+ public static short ToInt16(sbyte value)
+ {
return value;
}
- public static short ToInt16(byte value) {
+ public static short ToInt16(byte value)
+ {
return value;
}
- [CLSCompliant(false)]
- public static short ToInt16(ushort 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) {
+ 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) {
+ [CLSCompliant(false)]
+ public static short ToInt16(uint value)
+ {
if (value > Int16.MaxValue) ThrowInt16OverflowException();
Contract.EndContractBlock();
return (short)value;
}
- public static short ToInt16(short value) {
+ public static short ToInt16(short value)
+ {
return value;
}
- public static short ToInt16(long 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) {
+ [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) {
+ public static short ToInt16(float value)
+ {
return ToInt16((double)value);
}
- public static short ToInt16(double value) {
+ public static short ToInt16(double value)
+ {
return ToInt16(ToInt32(value));
}
- public static short ToInt16(decimal value) {
+ public static short ToInt16(decimal value)
+ {
return Decimal.ToInt16(Decimal.Round(value, 0));
}
- public static short ToInt16(String value) {
+ 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) {
+ public static short ToInt16(String value, IFormatProvider provider)
+ {
if (value == null)
return 0;
return Int16.Parse(value, NumberStyles.Integer, provider);
@@ -933,104 +1030,121 @@ namespace System {
// 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)
+ {
+ 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(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(bool value)
+ {
+ return value ? (ushort)Boolean.True : (ushort)Boolean.False;
}
- [CLSCompliant(false)]
- public static ushort ToUInt16(char value) {
+ [CLSCompliant(false)]
+ public static ushort ToUInt16(char value)
+ {
return value;
}
- [CLSCompliant(false)]
- public static ushort ToUInt16(sbyte 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) {
+ [CLSCompliant(false)]
+ public static ushort ToUInt16(byte value)
+ {
return value;
}
- [CLSCompliant(false)]
- public static ushort ToUInt16(short 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) {
+ [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) {
+ [CLSCompliant(false)]
+ public static ushort ToUInt16(ushort value)
+ {
return value;
}
- [CLSCompliant(false)]
- public static ushort ToUInt16(uint 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) {
+
+ [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) {
+ [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) {
+ [CLSCompliant(false)]
+ public static ushort ToUInt16(float value)
+ {
return ToUInt16((double)value);
}
- [CLSCompliant(false)]
- public static ushort ToUInt16(double value) {
+ [CLSCompliant(false)]
+ public static ushort ToUInt16(double value)
+ {
return ToUInt16(ToInt32(value));
}
- [CLSCompliant(false)]
- public static ushort ToUInt16(decimal value) {
+ [CLSCompliant(false)]
+ public static ushort ToUInt16(decimal value)
+ {
return Decimal.ToUInt16(Decimal.Round(value, 0));
}
- [CLSCompliant(false)]
- public static ushort ToUInt16(String value) {
+ [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) {
+ public static ushort ToUInt16(String value, IFormatProvider provider)
+ {
if (value == null)
return 0;
return UInt16.Parse(value, NumberStyles.Integer, provider);
@@ -1047,80 +1161,98 @@ namespace System {
// Conversions to Int32
- public static int ToInt32(object value) {
- return value == null? 0: ((IConvertible)value).ToInt32(null);
+ 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(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(bool value)
+ {
+ return value ? Boolean.True : Boolean.False;
}
- public static int ToInt32(char value) {
+ public static int ToInt32(char value)
+ {
return value;
}
[CLSCompliant(false)]
- public static int ToInt32(sbyte value) {
+ public static int ToInt32(sbyte value)
+ {
return value;
}
- public static int ToInt32(byte value) {
+ public static int ToInt32(byte value)
+ {
return value;
}
- public static int ToInt32(short value) {
+ public static int ToInt32(short value)
+ {
return value;
}
- [CLSCompliant(false)]
- public static int ToInt32(ushort value) {
+ [CLSCompliant(false)]
+ public static int ToInt32(ushort value)
+ {
return value;
}
- [CLSCompliant(false)]
- public static int ToInt32(uint 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) {
+ public static int ToInt32(int value)
+ {
return value;
}
- public static int ToInt32(long 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) {
+ [CLSCompliant(false)]
+ public static int ToInt32(ulong value)
+ {
if (value > Int32.MaxValue) ThrowInt32OverflowException();
Contract.EndContractBlock();
return (int)value;
}
- public static int ToInt32(float value) {
+ public static int ToInt32(float value)
+ {
return ToInt32((double)value);
}
- public static int ToInt32(double value) {
- if (value >= 0) {
- if (value < 2147483647.5) {
+ 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) {
+ else
+ {
+ if (value >= -2147483648.5)
+ {
int result = (int)value;
double dif = value - result;
if (dif < -0.5 || dif == -0.5 && (result & 1) != 0) result--;
@@ -1130,17 +1262,20 @@ namespace System {
throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
}
- public static int ToInt32(decimal value) {
+ public static int ToInt32(decimal value)
+ {
return Decimal.FCallToInt32(value);
}
- public static int ToInt32(String 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) {
+ public static int ToInt32(String value, IFormatProvider provider)
+ {
if (value == null)
return 0;
return Int32.Parse(value, NumberStyles.Integer, provider);
@@ -1157,85 +1292,100 @@ namespace System {
// 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)
+ {
+ 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(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(bool value)
+ {
+ return value ? (uint)Boolean.True : (uint)Boolean.False;
}
- [CLSCompliant(false)]
- public static uint ToUInt32(char value) {
+ [CLSCompliant(false)]
+ public static uint ToUInt32(char value)
+ {
return value;
}
- [CLSCompliant(false)]
- public static uint ToUInt32(sbyte 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) {
+ [CLSCompliant(false)]
+ public static uint ToUInt32(byte value)
+ {
return value;
}
- [CLSCompliant(false)]
- public static uint ToUInt32(short 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) {
+ [CLSCompliant(false)]
+ public static uint ToUInt32(ushort value)
+ {
return value;
}
- [CLSCompliant(false)]
- public static uint ToUInt32(int 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) {
+ [CLSCompliant(false)]
+ public static uint ToUInt32(uint value)
+ {
return value;
}
- [CLSCompliant(false)]
- public static uint ToUInt32(long 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) {
+ [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) {
+ [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) {
+ [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++;
@@ -1244,20 +1394,23 @@ namespace System {
throw new OverflowException(Environment.GetResourceString("Overflow_UInt32"));
}
- [CLSCompliant(false)]
- public static uint ToUInt32(decimal value) {
+ [CLSCompliant(false)]
+ public static uint ToUInt32(decimal value)
+ {
return Decimal.ToUInt32(Decimal.Round(value, 0));
}
- [CLSCompliant(false)]
- public static uint ToUInt32(String value) {
+ [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) {
+ public static uint ToUInt32(String value, IFormatProvider provider)
+ {
if (value == null)
return 0;
return UInt32.Parse(value, NumberStyles.Integer, provider);
@@ -1274,81 +1427,98 @@ namespace System {
// Conversions to Int64
- public static long ToInt64(object value) {
- return value == null? 0: ((IConvertible)value).ToInt64(null);
+ 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(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(bool value)
+ {
+ return value ? Boolean.True : Boolean.False;
}
- public static long ToInt64(char value) {
+ public static long ToInt64(char value)
+ {
return value;
}
[CLSCompliant(false)]
- public static long ToInt64(sbyte value) {
+ public static long ToInt64(sbyte value)
+ {
return value;
}
- public static long ToInt64(byte value) {
+ public static long ToInt64(byte value)
+ {
return value;
}
- public static long ToInt64(short value) {
+ public static long ToInt64(short value)
+ {
return value;
}
- [CLSCompliant(false)]
- public static long ToInt64(ushort value) {
+ [CLSCompliant(false)]
+ public static long ToInt64(ushort value)
+ {
return value;
}
- public static long ToInt64(int value) {
+ public static long ToInt64(int value)
+ {
return value;
}
- [CLSCompliant(false)]
- public static long ToInt64(uint value) {
+ [CLSCompliant(false)]
+ public static long ToInt64(uint value)
+ {
return value;
}
- [CLSCompliant(false)]
- public static long ToInt64(ulong 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) {
+ public static long ToInt64(long value)
+ {
return value;
}
- public static long ToInt64(float value) {
+ public static long ToInt64(float value)
+ {
return ToInt64((double)value);
}
- public static long ToInt64(double value) {
+ public static long ToInt64(double value)
+ {
return checked((long)Math.Round(value));
}
- public static long ToInt64(decimal value) {
+ public static long ToInt64(decimal value)
+ {
return Decimal.ToInt64(Decimal.Round(value, 0));
}
- public static long ToInt64(string value) {
+ 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) {
+ public static long ToInt64(String value, IFormatProvider provider)
+ {
if (value == null)
return 0;
return Int64.Parse(value, NumberStyles.Integer, provider);
@@ -1364,99 +1534,116 @@ namespace System {
// 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)
+ {
+ 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(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(bool value)
+ {
+ return value ? (ulong)Boolean.True : (ulong)Boolean.False;
}
- [CLSCompliant(false)]
- public static ulong ToUInt64(char value) {
+ [CLSCompliant(false)]
+ public static ulong ToUInt64(char value)
+ {
return value;
}
-
- [CLSCompliant(false)]
- public static ulong ToUInt64(sbyte 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) {
+ [CLSCompliant(false)]
+ public static ulong ToUInt64(byte value)
+ {
return value;
}
- [CLSCompliant(false)]
- public static ulong ToUInt64(short 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) {
+ [CLSCompliant(false)]
+ public static ulong ToUInt64(ushort value)
+ {
return value;
}
- [CLSCompliant(false)]
- public static ulong ToUInt64(int 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) {
+ [CLSCompliant(false)]
+ public static ulong ToUInt64(uint value)
+ {
return value;
}
- [CLSCompliant(false)]
- public static ulong ToUInt64(long 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) {
+ [CLSCompliant(false)]
+ public static ulong ToUInt64(UInt64 value)
+ {
return value;
}
- [CLSCompliant(false)]
- public static ulong ToUInt64(float value) {
+ [CLSCompliant(false)]
+ public static ulong ToUInt64(float value)
+ {
return ToUInt64((double)value);
}
- [CLSCompliant(false)]
- public static ulong 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) {
+ [CLSCompliant(false)]
+ public static ulong ToUInt64(decimal value)
+ {
return Decimal.ToUInt64(Decimal.Round(value, 0));
}
- [CLSCompliant(false)]
- public static ulong ToUInt64(String value) {
+ [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) {
+ public static ulong ToUInt64(String value, IFormatProvider provider)
+ {
if (value == null)
return 0;
return UInt64.Parse(value, NumberStyles.Integer, provider);
@@ -1473,73 +1660,89 @@ namespace System {
// Conversions to Single
- public static float ToSingle(object value) {
- return value == null? 0: ((IConvertible)value).ToSingle(null);
+ 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);
+ public static float ToSingle(object value, IFormatProvider provider)
+ {
+ return value == null ? 0 : ((IConvertible)value).ToSingle(provider);
}
[CLSCompliant(false)]
- public static float ToSingle(sbyte value) {
+ public static float ToSingle(sbyte value)
+ {
return value;
}
- public static float ToSingle(byte value) {
+ public static float ToSingle(byte value)
+ {
return value;
}
- public static float ToSingle(char value) {
+ public static float ToSingle(char value)
+ {
return ((IConvertible)value).ToSingle(null);
}
- public static float ToSingle(short value) {
+ public static float ToSingle(short value)
+ {
return value;
}
- [CLSCompliant(false)]
- public static float ToSingle(ushort value) {
+ [CLSCompliant(false)]
+ public static float ToSingle(ushort value)
+ {
return value;
}
- public static float ToSingle(int value) {
+ public static float ToSingle(int value)
+ {
return value;
}
- [CLSCompliant(false)]
- public static float ToSingle(uint value) {
+ [CLSCompliant(false)]
+ public static float ToSingle(uint value)
+ {
return value;
}
- public static float ToSingle(long value) {
+ public static float ToSingle(long value)
+ {
return value;
}
- [CLSCompliant(false)]
- public static float ToSingle(ulong value) {
+ [CLSCompliant(false)]
+ public static float ToSingle(ulong value)
+ {
return value;
}
- public static float ToSingle(float value) {
+ public static float ToSingle(float value)
+ {
return value;
}
- public static float ToSingle(double value) {
+ public static float ToSingle(double value)
+ {
return (float)value;
}
- public static float ToSingle(decimal value) {
+ public static float ToSingle(decimal value)
+ {
return (float)value;
}
- public static float ToSingle(String 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) {
+ public static float ToSingle(String value, IFormatProvider provider)
+ {
if (value == null)
return 0;
return Single.Parse(value, NumberStyles.Float | NumberStyles.AllowThousands, provider);
@@ -1548,7 +1751,7 @@ namespace System {
public static float ToSingle(bool value)
{
- return value? Boolean.True: Boolean.False;
+ return value ? Boolean.True : Boolean.False;
}
public static float ToSingle(DateTime value)
@@ -1561,81 +1764,98 @@ namespace System {
// Conversions to Double
- public static double ToDouble(object value) {
- return value == null? 0: ((IConvertible)value).ToDouble(null);
+ 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);
+ public static double ToDouble(object value, IFormatProvider provider)
+ {
+ return value == null ? 0 : ((IConvertible)value).ToDouble(provider);
}
[CLSCompliant(false)]
- public static double ToDouble(sbyte value) {
+ public static double ToDouble(sbyte value)
+ {
return value;
}
- public static double ToDouble(byte value) {
+ public static double ToDouble(byte value)
+ {
return value;
}
- public static double ToDouble(short value) {
+ public static double ToDouble(short value)
+ {
return value;
}
- public static double ToDouble(char value) {
+ public static double ToDouble(char value)
+ {
return ((IConvertible)value).ToDouble(null);
}
- [CLSCompliant(false)]
- public static double ToDouble(ushort value) {
+ [CLSCompliant(false)]
+ public static double ToDouble(ushort value)
+ {
return value;
}
- public static double ToDouble(int value) {
+ public static double ToDouble(int value)
+ {
return value;
}
- [CLSCompliant(false)]
- public static double ToDouble(uint value) {
+ [CLSCompliant(false)]
+ public static double ToDouble(uint value)
+ {
return value;
}
- public static double ToDouble(long value) {
+ public static double ToDouble(long value)
+ {
return value;
}
- [CLSCompliant(false)]
- public static double ToDouble(ulong value) {
+ [CLSCompliant(false)]
+ public static double ToDouble(ulong value)
+ {
return value;
}
- public static double ToDouble(float value) {
+ public static double ToDouble(float value)
+ {
return value;
}
- public static double ToDouble(double value) {
+ public static double ToDouble(double value)
+ {
return value;
}
- public static double ToDouble(decimal value) {
+ public static double ToDouble(decimal value)
+ {
return (double)value;
}
- public static double ToDouble(String 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) {
+ 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(bool value)
+ {
+ return value ? Boolean.True : Boolean.False;
}
public static double ToDouble(DateTime value)
@@ -1648,80 +1868,97 @@ namespace System {
// Conversions to Decimal
- public static decimal ToDecimal(object value) {
- return value == null? 0: ((IConvertible)value).ToDecimal(null);
+ 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);
+ public static decimal ToDecimal(object value, IFormatProvider provider)
+ {
+ return value == null ? 0 : ((IConvertible)value).ToDecimal(provider);
}
[CLSCompliant(false)]
- public static decimal ToDecimal(sbyte value) {
+ public static decimal ToDecimal(sbyte value)
+ {
return value;
}
- public static decimal ToDecimal(byte value) {
+ public static decimal ToDecimal(byte value)
+ {
return value;
}
- public static decimal ToDecimal(char value) {
+ public static decimal ToDecimal(char value)
+ {
return ((IConvertible)value).ToDecimal(null);
}
- public static decimal ToDecimal(short value) {
+ public static decimal ToDecimal(short value)
+ {
return value;
}
- [CLSCompliant(false)]
- public static decimal ToDecimal(ushort value) {
+ [CLSCompliant(false)]
+ public static decimal ToDecimal(ushort value)
+ {
return value;
}
- public static decimal ToDecimal(int value) {
+ public static decimal ToDecimal(int value)
+ {
return value;
}
- [CLSCompliant(false)]
- public static decimal ToDecimal(uint value) {
+ [CLSCompliant(false)]
+ public static decimal ToDecimal(uint value)
+ {
return value;
}
- public static decimal ToDecimal(long value) {
+ public static decimal ToDecimal(long value)
+ {
return value;
}
- [CLSCompliant(false)]
- public static decimal ToDecimal(ulong value) {
+ [CLSCompliant(false)]
+ public static decimal ToDecimal(ulong value)
+ {
return value;
}
- public static decimal ToDecimal(float value) {
+ public static decimal ToDecimal(float value)
+ {
return (decimal)value;
}
- public static decimal ToDecimal(double value) {
+ public static decimal ToDecimal(double value)
+ {
return (decimal)value;
}
- public static decimal ToDecimal(String 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) {
+ 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) {
+ public static decimal ToDecimal(decimal value)
+ {
return value;
}
- public static decimal ToDecimal(bool value) {
- return value? Boolean.True: Boolean.False;
+ public static decimal ToDecimal(bool value)
+ {
+ return value ? Boolean.True : Boolean.False;
}
public static decimal ToDecimal(DateTime value)
@@ -1734,83 +1971,101 @@ namespace System {
// Conversions to DateTime
- public static DateTime ToDateTime(DateTime value) {
+ 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)
+ {
+ 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(object value, IFormatProvider provider)
+ {
+ return value == null ? DateTime.MinValue : ((IConvertible)value).ToDateTime(provider);
}
- public static DateTime ToDateTime(String value) {
+ 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) {
+ 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) {
+ [CLSCompliant(false)]
+ public static DateTime ToDateTime(sbyte value)
+ {
return ((IConvertible)value).ToDateTime(null);
}
- public static DateTime ToDateTime(byte value) {
+ public static DateTime ToDateTime(byte value)
+ {
return ((IConvertible)value).ToDateTime(null);
}
- public static DateTime ToDateTime(short value) {
+ public static DateTime ToDateTime(short value)
+ {
return ((IConvertible)value).ToDateTime(null);
}
[CLSCompliant(false)]
- public static DateTime ToDateTime(ushort value) {
+ public static DateTime ToDateTime(ushort value)
+ {
return ((IConvertible)value).ToDateTime(null);
}
- public static DateTime ToDateTime(int value) {
+ public static DateTime ToDateTime(int value)
+ {
return ((IConvertible)value).ToDateTime(null);
}
[CLSCompliant(false)]
- public static DateTime ToDateTime(uint value) {
+ public static DateTime ToDateTime(uint value)
+ {
return ((IConvertible)value).ToDateTime(null);
}
- public static DateTime ToDateTime(long value) {
+ public static DateTime ToDateTime(long value)
+ {
return ((IConvertible)value).ToDateTime(null);
}
[CLSCompliant(false)]
- public static DateTime ToDateTime(ulong value) {
+ public static DateTime ToDateTime(ulong value)
+ {
return ((IConvertible)value).ToDateTime(null);
}
- public static DateTime ToDateTime(bool value) {
+ public static DateTime ToDateTime(bool value)
+ {
return ((IConvertible)value).ToDateTime(null);
}
- public static DateTime ToDateTime(char value) {
+ public static DateTime ToDateTime(char value)
+ {
return ((IConvertible)value).ToDateTime(null);
}
- public static DateTime ToDateTime(float value) {
+ public static DateTime ToDateTime(float value)
+ {
return ((IConvertible)value).ToDateTime(null);
}
- public static DateTime ToDateTime(double value) {
+ public static DateTime ToDateTime(double value)
+ {
return ((IConvertible)value).ToDateTime(null);
}
- public static DateTime ToDateTime(decimal value) {
+ public static DateTime ToDateTime(decimal value)
+ {
return ((IConvertible)value).ToDateTime(null);
}
@@ -1819,174 +2074,206 @@ namespace System {
// Conversions to String
- public static string ToString(Object value) {
- return ToString(value,null);
+ public static string ToString(Object value)
+ {
+ return ToString(value, null);
}
- public static string ToString(Object value, IFormatProvider provider) {
+ public static string ToString(Object value, IFormatProvider provider)
+ {
IConvertible ic = value as IConvertible;
- if (ic != null)
+ if (ic != null)
return ic.ToString(provider);
IFormattable formattable = value as IFormattable;
- if (formattable != null)
+ if (formattable != null)
return formattable.ToString(null, provider);
- return value == null? String.Empty: value.ToString();
+ return value == null ? String.Empty : value.ToString();
}
- public static string ToString(bool value) {
+ public static string ToString(bool value)
+ {
Contract.Ensures(Contract.Result<string>() != null);
return value.ToString();
}
- public static string ToString(bool value, IFormatProvider provider) {
+ public static string ToString(bool value, IFormatProvider provider)
+ {
Contract.Ensures(Contract.Result<string>() != null);
return value.ToString(provider);
}
- public static string ToString(char value) {
+ public static string ToString(char value)
+ {
Contract.Ensures(Contract.Result<string>() != null);
return Char.ToString(value);
}
- public static string ToString(char value, IFormatProvider provider) {
+ 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) {
+ 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) {
+ public static string ToString(sbyte value, IFormatProvider provider)
+ {
Contract.Ensures(Contract.Result<string>() != null);
return value.ToString(provider);
}
- public static string ToString(byte value) {
+ 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) {
+ public static string ToString(byte value, IFormatProvider provider)
+ {
Contract.Ensures(Contract.Result<string>() != null);
return value.ToString(provider);
}
- public static string ToString(short value) {
+ 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) {
+ 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) {
+ [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) {
+ public static string ToString(ushort value, IFormatProvider provider)
+ {
Contract.Ensures(Contract.Result<string>() != null);
return value.ToString(provider);
}
- public static string ToString(int value) {
+ 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) {
+ 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) {
+ [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) {
+ public static string ToString(uint value, IFormatProvider provider)
+ {
Contract.Ensures(Contract.Result<string>() != null);
return value.ToString(provider);
}
- public static string ToString(long value) {
+ 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) {
+ 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) {
+ [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) {
+ public static string ToString(ulong value, IFormatProvider provider)
+ {
Contract.Ensures(Contract.Result<string>() != null);
return value.ToString(provider);
}
- public static string ToString(float value) {
+ 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) {
+ public static string ToString(float value, IFormatProvider provider)
+ {
Contract.Ensures(Contract.Result<string>() != null);
return value.ToString(provider);
}
- public static string ToString(double value) {
+ 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) {
+ public static string ToString(double value, IFormatProvider provider)
+ {
Contract.Ensures(Contract.Result<string>() != null);
return value.ToString(provider);
}
- public static string ToString(decimal value) {
+ 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) {
+ public static string ToString(Decimal value, IFormatProvider provider)
+ {
Contract.Ensures(Contract.Result<string>() != null);
return value.ToString(provider);
}
- public static string ToString(DateTime value) {
+ public static string ToString(DateTime value)
+ {
Contract.Ensures(Contract.Result<string>() != null);
return value.ToString();
}
- public static string ToString(DateTime value, IFormatProvider provider) {
+ public static string ToString(DateTime value, IFormatProvider provider)
+ {
Contract.Ensures(Contract.Result<string>() != null);
return value.ToString(provider);
}
- public static String ToString(String value) {
+ 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) {
+ 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
}
@@ -1999,15 +2286,17 @@ namespace System {
// 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) {
+ 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);
+ int r = ParseNumbers.StringToInt(value, fromBase, ParseNumbers.IsTight | ParseNumbers.TreatAsUnsigned);
if (r < Byte.MinValue || r > Byte.MaxValue)
ThrowByteOverflowException();
- return (byte) r;
+ return (byte)r;
}
// Parses value in base fromBase. fromBase can only
@@ -2015,36 +2304,40 @@ namespace System {
// 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) {
+ 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);
+ 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;
+ 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) {
+ 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);
+ 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;
+ return (short)r;
}
// Parses value in base fromBase. fromBase can only
@@ -2052,27 +2345,31 @@ namespace System {
// 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) {
+ 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);
+ int r = ParseNumbers.StringToInt(value, fromBase, ParseNumbers.IsTight | ParseNumbers.TreatAsUnsigned);
if (r < UInt16.MinValue || r > UInt16.MaxValue)
ThrowUInt16OverflowException();
- return (ushort) r;
+ 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) {
+ 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);
+ return ParseNumbers.StringToInt(value, fromBase, ParseNumbers.IsTight);
}
// Parses value in base fromBase. fromBase can only
@@ -2080,24 +2377,28 @@ namespace System {
// 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) {
+ 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);
+ 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) {
+ 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);
+ return ParseNumbers.StringToLong(value, fromBase, ParseNumbers.IsTight);
}
// Parses value in base fromBase. fromBase can only
@@ -2105,17 +2406,21 @@ namespace System {
// 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) {
+ 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);
+ 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) {
+ 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();
@@ -2123,8 +2428,10 @@ namespace System {
}
// 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) {
+ 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();
@@ -2132,8 +2439,10 @@ namespace System {
}
// 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) {
+ 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();
@@ -2141,16 +2450,20 @@ namespace System {
}
// 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) {
+ 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) {
+ public static String ToBase64String(byte[] inArray)
+ {
+ if (inArray == null)
+ {
throw new ArgumentNullException(nameof(inArray));
}
Contract.Ensures(Contract.Result<string>() != null);
@@ -2158,8 +2471,10 @@ namespace System {
return ToBase64String(inArray, 0, inArray.Length, Base64FormattingOptions.None);
}
- public static String ToBase64String(byte[] inArray, Base64FormattingOptions options) {
- if (inArray==null) {
+ public static String ToBase64String(byte[] inArray, Base64FormattingOptions options)
+ {
+ if (inArray == null)
+ {
throw new ArgumentNullException(nameof(inArray));
}
Contract.Ensures(Contract.Result<string>() != null);
@@ -2167,17 +2482,19 @@ namespace System {
return ToBase64String(inArray, 0, inArray.Length, options);
}
- public static String ToBase64String(byte[] inArray, int offset, int length) {
+ 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) {
+ public static unsafe String ToBase64String(byte[] inArray, int offset, int length, Base64FormattingOptions options)
+ {
//Do data verfication
- if (inArray==null)
+ if (inArray == null)
throw new ArgumentNullException(nameof(inArray));
- if (length<0)
+ if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- if (offset<0)
+ 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));
@@ -2190,7 +2507,7 @@ namespace System {
inArrayLength = inArray.Length;
if (offset > (inArrayLength - length))
throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_OffsetLength"));
-
+
if (inArrayLength == 0)
return String.Empty;
@@ -2199,37 +2516,42 @@ namespace System {
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);
+ 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) {
+ 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) {
+
+ public static unsafe int ToBase64CharArray(byte[] inArray, int offsetIn, int length, char[] outArray, int offsetOut, Base64FormattingOptions options)
+ {
//Do data verfication
- if (inArray==null)
+ if (inArray == null)
throw new ArgumentNullException(nameof(inArray));
- if (outArray==null)
+ if (outArray == null)
throw new ArgumentNullException(nameof(outArray));
- if (length<0)
+ if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- if (offsetIn<0)
+ if (offsetIn < 0)
throw new ArgumentOutOfRangeException(nameof(offsetIn), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
- if (offsetOut<0)
+ if (offsetOut < 0)
throw new ArgumentOutOfRangeException(nameof(offsetOut), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
- if( options < Base64FormattingOptions.None || options > Base64FormattingOptions.InsertLineBreaks) {
+ if (options < Base64FormattingOptions.None || options > Base64FormattingOptions.InsertLineBreaks)
+ {
throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)options));
}
Contract.Ensures(Contract.Result<int>() >= 0);
@@ -2257,87 +2579,97 @@ namespace System {
// Length of the char buffer required
numElementsToCopy = ToBase64_CalculateAndValidateOutputLength(length, insertLineBreaks);
-
- if (offsetOut > (int)(outArrayLength - numElementsToCopy))
+
+ 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);
+ 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;
+ 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 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)
+ fixed (char* base64 = &base64Table[0])
+ {
+ for (i = offset; i < calcLength; i += 3)
{
- if (insertLineBreaks) {
- if (charcount == base64LineBreakPosition) {
+ 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)];
+ 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;
+ i = calcLength;
- if (insertLineBreaks && (lengthmod3 !=0) && (charcount == base64LineBreakPosition)) {
+ if (insertLineBreaks && (lengthmod3 != 0) && (charcount == base64LineBreakPosition))
+ {
outChars[j++] = '\r';
outChars[j++] = '\n';
}
-
- switch(lengthmod3)
+
+ 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;
+ 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) {
+ 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) {
+ if (insertLineBreaks)
+ {
long newLines = outlen / base64LineBreakPosition;
- if ((outlen % base64LineBreakPosition) == 0) {
- --newLines;
+ if ((outlen % base64LineBreakPosition) == 0)
+ {
+ --newLines;
}
outlen += newLines * 2; // the number of line break chars we'll add, "\r\n"
}
@@ -2349,15 +2681,15 @@ namespace System {
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) {
-
+ public static Byte[] FromBase64String(String s)
+ {
// "s" is an unfortunate parameter name, but we need to keep it for backward compat.
if (s == null)
@@ -2365,9 +2697,10 @@ namespace System {
Contract.EndContractBlock();
- unsafe {
- fixed (Char* sPtr = s) {
-
+ unsafe
+ {
+ fixed (Char* sPtr = s)
+ {
return FromBase64CharPtr(sPtr, s.Length);
}
}
@@ -2381,8 +2714,8 @@ namespace System {
/// <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) {
-
+ public static Byte[] FromBase64CharArray(Char[] inArray, Int32 offset, Int32 length)
+ {
if (inArray == null)
throw new ArgumentNullException(nameof(inArray));
@@ -2397,13 +2730,14 @@ namespace System {
Contract.EndContractBlock();
- unsafe {
- fixed (Char* inArrayPtr = inArray) {
-
+ unsafe
+ {
+ fixed (Char* inArrayPtr = inArray)
+ {
return FromBase64CharPtr(inArrayPtr + offset, length);
}
}
- }
+ }
@@ -2416,8 +2750,8 @@ namespace System {
/// <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) {
-
+ 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);
@@ -2426,9 +2760,9 @@ namespace System {
// 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;
+ Int32 lastChar = inputPtr[inputLength - 1];
+ if (lastChar != (Int32)' ' && lastChar != (Int32)'\n' && lastChar != (Int32)'\r' && lastChar != (Int32)'\t')
+ break;
inputLength--;
}
@@ -2439,7 +2773,7 @@ namespace System {
// 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];
@@ -2469,23 +2803,23 @@ namespace System {
/// <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) {
-
+ 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');
+ 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;
@@ -2496,90 +2830,98 @@ namespace System {
// 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;
+ unchecked
+ {
+ while (true)
+ {
+ // break when done:
+ if (inputPtr >= endInputPtr)
+ goto _AllInputConsumed;
- // 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;
+ // Get current char:
+ currCode = (UInt32)(*inputPtr);
+ inputPtr++;
- // Other chars are illegal:
- default:
- throw new FormatException(Environment.GetResourceString("Format_BadBase64Char"));
+ // 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) {
+ // Ok, we got the code. Save it:
+ currBlockCodes = (currBlockCodes << 6) | currCode;
- if ((Int32) (endDestPtr - destPtr) < 3)
- return -1;
+ // 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;
+ *(destPtr) = (Byte)(currBlockCodes >> 16);
+ *(destPtr + 1) = (Byte)(currBlockCodes >> 8);
+ *(destPtr + 2) = (Byte)(currBlockCodes);
+ destPtr += 3;
- currBlockCodes = 0x000000FFu;
+ currBlockCodes = 0x000000FFu;
+ }
}
+ } // unchecked while
- }} // 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.");
- // '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:
+ // 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) {
-
+ if (inputPtr == endInputPtr)
+ {
// Code is zero for trailing '=':
currBlockCodes <<= 6;
@@ -2591,25 +2933,25 @@ namespace System {
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;
+ *(destPtr++) = (Byte)(currBlockCodes >> 16);
+ *(destPtr++) = (Byte)(currBlockCodes >> 8);
- } else { // '=' can also be at the pre-last position iff the last is also a '=' excluding the white spaces:
-
+ 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;
+ Int32 lastChar = *(inputPtr);
+ if (lastChar != (Int32)' ' && lastChar != (Int32)'\n' && lastChar != (Int32)'\r' && lastChar != (Int32)'\t')
+ break;
inputPtr++;
}
- if (inputPtr == (endInputPtr - 1) && *(inputPtr) == '=') {
-
+ if (inputPtr == (endInputPtr - 1) && *(inputPtr) == '=')
+ {
// Code is zero for each of the two '=':
currBlockCodes <<= 12;
@@ -2617,29 +2959,27 @@ namespace System {
if ((currBlockCodes & 0x80000000u) == 0u)
throw new FormatException(Environment.GetResourceString("Format_BadBase64CharArrayLength"));
- if ((Int32) (endDestPtr - destPtr) < 1) // Autch! We underestimated the output length!
+ 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);
+ *(destPtr++) = (Byte)(currBlockCodes >> 16);
currBlockCodes = 0x000000FFu;
-
- } else // '=' is not ok at places other than the end:
+ }
+ 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:
+
+ // 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);
-
+ return (Int32)(destPtr - startDestPtr);
} // Int32 FromBase64_Decode(...)
@@ -2648,10 +2988,10 @@ namespace System {
/// 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) ' ';
+ private static unsafe Int32 FromBase64_ComputeResultLength(Char* inputPtr, Int32 inputLength)
+ {
+ const UInt32 intEq = (UInt32)'=';
+ const UInt32 intSpace = (UInt32)' ';
Debug.Assert(0 <= inputLength);
@@ -2659,9 +2999,9 @@ namespace System {
Int32 usefulInputLength = inputLength;
Int32 padding = 0;
- while (inputPtr < inputEndPtr) {
-
- UInt32 c = (UInt32) (*inputPtr);
+ 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.
@@ -2670,34 +3010,34 @@ namespace System {
if (c <= intSpace)
usefulInputLength--;
- else if (c == intEq) {
+ 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 != 0)
+ {
if (padding == 1)
padding = 2;
else if (padding == 2)
padding = 1;
else
- throw new FormatException(Environment.GetResourceString("Format_BadBase64Char"));
+ 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/CurrentTimeZone.cs b/src/mscorlib/src/System/CurrentTimeZone.cs
index 804bbcccc4..d55df27a12 100644
--- a/src/mscorlib/src/System/CurrentTimeZone.cs
+++ b/src/mscorlib/src/System/CurrentTimeZone.cs
@@ -4,7 +4,6 @@
/*============================================================
**
-** Class: CurrentTimeZone
**
**
** Purpose:
@@ -17,15 +16,17 @@
**
**
============================================================*/
-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;
+using System;
+using System.Diagnostics.Contracts;
+using System.Text;
+using System.Collections;
+using System.Globalization;
+using System.Runtime.CompilerServices;
+using System.Runtime.Versioning;
+
+namespace System
+{
[Obsolete("System.CurrentSystemTimeZone has been deprecated. Please investigate the use of System.TimeZoneInfo.Local instead.")]
[Serializable]
internal class CurrentSystemTimeZone : TimeZone
@@ -38,10 +39,10 @@ namespace System {
// 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 long m_ticksOffset;
private String m_standardName;
private String m_daylightName;
-
+
internal CurrentSystemTimeZone()
{
TimeZoneInfo local = TimeZoneInfo.Local;
@@ -50,13 +51,13 @@ namespace System {
m_standardName = local.StandardName;
m_daylightName = local.DaylightName;
}
-
+
public override String StandardName
{
- get
+ get
{
return m_standardName;
- }
+ }
}
public override String DaylightName
@@ -71,14 +72,14 @@ namespace System {
{
// Get the daylight changes for the year of the specified time.
TimeSpan offset = new TimeSpan(m_ticksOffset);
- DaylightTime daylightTime = GetDaylightChanges(time.Year);
- isAmbiguousLocalDst= false;
-
+ 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.
@@ -86,7 +87,7 @@ namespace System {
DateTime endTime = daylightTime.End - offset - daylightTime.Delta;
DateTime ambiguousStart;
DateTime ambiguousEnd;
-
+
if (daylightTime.Delta.Ticks > 0)
{
ambiguousStart = endTime - daylightTime.Delta;
@@ -110,21 +111,21 @@ namespace System {
// 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 )
+ if (time >= ambiguousStart && time < ambiguousEnd)
{
isAmbiguousLocalDst = true;
}
}
return offset.Ticks;
}
-
+
public override DateTime ToLocalTime(DateTime time)
{
if (time.Kind == DateTimeKind.Local)
@@ -153,7 +154,7 @@ namespace System {
}
Contract.EndContractBlock();
- Object objYear = (Object) year;
+ Object objYear = (Object)year;
if (!m_CachedDaylightChanges.Contains(objYear))
{
@@ -181,7 +182,7 @@ namespace System {
if (currentDaylightChanges == null)
{
- currentDaylightChanges = new DaylightTime(DateTime.MinValue, DateTime.MinValue, TimeSpan.Zero);
+ currentDaylightChanges = new DaylightTime(DateTime.MinValue, DateTime.MinValue, TimeSpan.Zero);
}
lock (m_CachedDaylightChanges)
@@ -191,7 +192,7 @@ namespace System {
m_CachedDaylightChanges.Add(objYear, currentDaylightChanges);
}
}
- }
+ }
DaylightTime result = (DaylightTime)m_CachedDaylightChanges[objYear];
@@ -206,9 +207,8 @@ namespace System {
}
else
{
- return new TimeSpan(TimeZone.CalculateUtcOffset(time, GetDaylightChanges(time.Year)).Ticks + m_ticksOffset);
+ 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
index 65c85ba968..817f6e547f 100644
--- a/src/mscorlib/src/System/DBNull.cs
+++ b/src/mscorlib/src/System/DBNull.cs
@@ -6,112 +6,135 @@
// Void
// This class represents a Missing Variant
////////////////////////////////////////////////////////////////////////////////
-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]
- public sealed class DBNull : ISerializable, IConvertible {
-
+ public sealed class DBNull : ISerializable, IConvertible
+ {
//Package private constructor
- private DBNull(){
+ private DBNull()
+ {
}
- private DBNull(SerializationInfo info, StreamingContext context) {
+ 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) {
+ public void GetObjectData(SerializationInfo info, StreamingContext context)
+ {
UnitySerializationHolder.GetUnitySerializationInfo(info, UnitySerializationHolder.NullUnity, null, null);
}
-
- public override String ToString() {
+
+ public override String ToString()
+ {
return String.Empty;
}
- public String ToString(IFormatProvider provider) {
+ public String ToString(IFormatProvider provider)
+ {
return String.Empty;
}
- public TypeCode GetTypeCode() {
+ public TypeCode GetTypeCode()
+ {
return TypeCode.DBNull;
}
/// <internalonly/>
- bool IConvertible.ToBoolean(IFormatProvider provider) {
+ bool IConvertible.ToBoolean(IFormatProvider provider)
+ {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
}
/// <internalonly/>
- char IConvertible.ToChar(IFormatProvider provider) {
+ char IConvertible.ToChar(IFormatProvider provider)
+ {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
}
/// <internalonly/>
- sbyte IConvertible.ToSByte(IFormatProvider provider) {
+ sbyte IConvertible.ToSByte(IFormatProvider provider)
+ {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
}
/// <internalonly/>
- byte IConvertible.ToByte(IFormatProvider provider) {
+ byte IConvertible.ToByte(IFormatProvider provider)
+ {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
}
/// <internalonly/>
- short IConvertible.ToInt16(IFormatProvider provider) {
+ short IConvertible.ToInt16(IFormatProvider provider)
+ {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
}
/// <internalonly/>
- ushort IConvertible.ToUInt16(IFormatProvider provider) {
+ ushort IConvertible.ToUInt16(IFormatProvider provider)
+ {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
}
/// <internalonly/>
- int IConvertible.ToInt32(IFormatProvider provider) {
+ int IConvertible.ToInt32(IFormatProvider provider)
+ {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
}
/// <internalonly/>
- uint IConvertible.ToUInt32(IFormatProvider provider) {
+ uint IConvertible.ToUInt32(IFormatProvider provider)
+ {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
}
/// <internalonly/>
- long IConvertible.ToInt64(IFormatProvider provider) {
+ long IConvertible.ToInt64(IFormatProvider provider)
+ {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
}
/// <internalonly/>
- ulong IConvertible.ToUInt64(IFormatProvider provider) {
+ ulong IConvertible.ToUInt64(IFormatProvider provider)
+ {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
}
/// <internalonly/>
- float IConvertible.ToSingle(IFormatProvider provider) {
+ float IConvertible.ToSingle(IFormatProvider provider)
+ {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
}
/// <internalonly/>
- double IConvertible.ToDouble(IFormatProvider provider) {
+ double IConvertible.ToDouble(IFormatProvider provider)
+ {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
}
/// <internalonly/>
- decimal IConvertible.ToDecimal(IFormatProvider provider) {
+ decimal IConvertible.ToDecimal(IFormatProvider provider)
+ {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
}
/// <internalonly/>
- DateTime IConvertible.ToDateTime(IFormatProvider provider) {
+ DateTime IConvertible.ToDateTime(IFormatProvider provider)
+ {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
}
/// <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/DataMisalignedException.cs b/src/mscorlib/src/System/DataMisalignedException.cs
index a3653e7219..b1991a048e 100644
--- a/src/mscorlib/src/System/DataMisalignedException.cs
+++ b/src/mscorlib/src/System/DataMisalignedException.cs
@@ -14,7 +14,7 @@ using System.Runtime.Serialization;
namespace System
{
[Serializable]
- public sealed class DataMisalignedException : SystemException
+ public sealed class DataMisalignedException : SystemException
{
public DataMisalignedException()
: base(SR.Arg_DataMisalignedException)
diff --git a/src/mscorlib/src/System/DateTime.cs b/src/mscorlib/src/System/DateTime.cs
index 3de50336a9..360aceee90 100644
--- a/src/mscorlib/src/System/DateTime.cs
+++ b/src/mscorlib/src/System/DateTime.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.Threading;
using System.Globalization;
@@ -54,20 +54,19 @@ namespace System {
[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
@@ -76,7 +75,7 @@ namespace System {
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
@@ -85,11 +84,11 @@ namespace System {
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).
@@ -99,33 +98,33 @@ namespace System {
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 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";
-
+
+ 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
@@ -135,88 +134,103 @@ namespace System {
// 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) {
+ public DateTime(long ticks)
+ {
if (ticks < MinTicks || ticks > MaxTicks)
throw new ArgumentOutOfRangeException(nameof(ticks), Environment.GetResourceString("ArgumentOutOfRange_DateTimeBadTicks"));
Contract.EndContractBlock();
- dateData = (UInt64)ticks;
+ dateData = (UInt64)ticks;
}
-
- private DateTime(UInt64 dateData) {
+
+ private DateTime(UInt64 dateData)
+ {
this.dateData = dateData;
- }
+ }
- public DateTime(long ticks, DateTimeKind kind) {
- if (ticks < MinTicks || ticks > MaxTicks) {
+ 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) {
+ 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));
+ dateData = ((UInt64)ticks | ((UInt64)kind << KindShift));
}
- internal DateTime(long ticks, DateTimeKind kind, Boolean isAmbiguousDst) {
- if (ticks < MinTicks || ticks > MaxTicks) {
+ 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);
+ public DateTime(int year, int month, int day)
+ {
+ dateData = (UInt64)DateToTicks(year, month, day);
}
-
+
// Constructs a DateTime from a given year, month, and day for
// the specified calendar. The
// time-of-day of the resulting DateTime is always midnight.
//
- public DateTime(int year, int month, int day, Calendar calendar)
- : this(year, month, day, 0, 0, 0, calendar) {
+ 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)
+ {
+ 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) {
+ 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));
+ 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) {
+ 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;
+ 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) {
+ 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();
@@ -224,14 +238,17 @@ namespace System {
ticks += millisecond * TicksPerMillisecond;
if (ticks < MinTicks || ticks > MaxTicks)
throw new ArgumentException(Environment.GetResourceString("Arg_DateTimeRange"));
- this.dateData = (UInt64)ticks;
+ 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) {
+ 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) {
+ if (kind < DateTimeKind.Unspecified || kind > DateTimeKind.Local)
+ {
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDateTimeKind"), nameof(kind));
}
Contract.EndContractBlock();
@@ -239,16 +256,18 @@ namespace System {
ticks += millisecond * TicksPerMillisecond;
if (ticks < MinTicks || ticks > MaxTicks)
throw new ArgumentException(Environment.GetResourceString("Arg_DateTimeRange"));
- this.dateData = ((UInt64)ticks | ((UInt64)kind << KindShift));
+ 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) {
+ 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) {
+ if (millisecond < 0 || millisecond >= MillisPerSecond)
+ {
throw new ArgumentOutOfRangeException(nameof(millisecond), Environment.GetResourceString("ArgumentOutOfRange_Range", 0, MillisPerSecond - 1));
}
Contract.EndContractBlock();
@@ -256,16 +275,19 @@ namespace System {
ticks += millisecond * TicksPerMillisecond;
if (ticks < MinTicks || ticks > MaxTicks)
throw new ArgumentException(Environment.GetResourceString("Arg_DateTimeRange"));
- this.dateData = (UInt64)ticks;
+ dateData = (UInt64)ticks;
}
- public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, Calendar calendar, DateTimeKind kind) {
+ 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) {
+ if (millisecond < 0 || millisecond >= MillisPerSecond)
+ {
throw new ArgumentOutOfRangeException(nameof(millisecond), Environment.GetResourceString("ArgumentOutOfRange_Range", 0, MillisPerSecond - 1));
- }
- if (kind < DateTimeKind.Unspecified || kind > DateTimeKind.Local) {
+ }
+ if (kind < DateTimeKind.Unspecified || kind > DateTimeKind.Local)
+ {
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDateTimeKind"), nameof(kind));
}
Contract.EndContractBlock();
@@ -273,24 +295,27 @@ namespace System {
ticks += millisecond * TicksPerMillisecond;
if (ticks < MinTicks || ticks > MaxTicks)
throw new ArgumentException(Environment.GetResourceString("Arg_DateTimeRange"));
- this.dateData = ((UInt64)ticks | ((UInt64)kind << KindShift));
+ dateData = ((UInt64)ticks | ((UInt64)kind << KindShift));
}
-
- private DateTime(SerializationInfo info, StreamingContext context) {
- if (info==null)
+
+ 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) {
+ while (enumerator.MoveNext())
+ {
+ switch (enumerator.Name)
+ {
case TicksField:
serializedTicks = Convert.ToInt64(enumerator.Value, CultureInfo.InvariantCulture);
foundTicks = true;
@@ -304,91 +329,105 @@ namespace System {
break;
}
}
- if (foundDateData) {
- this.dateData = serializedDateData;
+ if (foundDateData)
+ {
+ dateData = serializedDateData;
}
- else if (foundTicks) {
- this.dateData = (UInt64)serializedTicks;
+ else if (foundTicks)
+ {
+ dateData = (UInt64)serializedTicks;
}
- else {
- throw new SerializationException(Environment.GetResourceString("Serialization_MissingDateTimeData"));
+ else
+ {
+ throw new SerializationException(Environment.GetResourceString("Serialization_MissingDateTimeData"));
}
Int64 ticks = InternalTicks;
- if (ticks < MinTicks || ticks > MaxTicks) {
+ if (ticks < MinTicks || ticks > MaxTicks)
+ {
throw new SerializationException(Environment.GetResourceString("Serialization_DateTimeTicksOutOfRange"));
- }
+ }
}
-
-
-
- internal Int64 InternalTicks {
- get {
+
+
+
+ internal Int64 InternalTicks
+ {
+ get
+ {
return (Int64)(dateData & TicksMask);
}
}
-
- private UInt64 InternalKind {
- get {
+
+ private UInt64 InternalKind
+ {
+ get
+ {
return (dateData & FlagsMask);
}
- }
-
+ }
+
// Returns the DateTime resulting from adding the given
// TimeSpan to this DateTime.
//
- public DateTime Add(TimeSpan value) {
+ 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)
+ 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) {
+ 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) {
+ 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) {
+ 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) {
+ 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
@@ -406,51 +445,58 @@ namespace System {
// or equal to d that denotes a valid day in month m1 of year
// y1.
//
- public DateTime AddMonths(int months) {
+ 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) {
+ if (i >= 0)
+ {
m = i % 12 + 1;
y = y + i / 12;
}
- else {
+ else
+ {
m = 12 + (i + 1) % 12;
y = y + (i - 11) / 12;
}
- if (y < 1 || y > 9999) {
+ 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) {
+ 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) {
+ public DateTime AddTicks(long value)
+ {
long ticks = InternalTicks;
- if (value > MaxTicks - ticks || value < MinTicks - ticks) {
+ 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
@@ -459,7 +505,8 @@ namespace System {
// 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) {
+ 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
@@ -469,43 +516,50 @@ namespace System {
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) {
+ 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) {
+ public int CompareTo(Object value)
+ {
if (value == null) return 1;
- if (!(value is DateTime)) {
+ if (!(value is DateTime))
+ {
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDateTime"));
}
-
+
return Compare(this, (DateTime)value);
}
- public int CompareTo(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]) {
+ 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;
@@ -513,47 +567,50 @@ namespace System {
}
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)
+ 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) {
+ 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;
+ 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) {
+ 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));
+ 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) {
+ if (millis < 0)
+ {
millis -= (millis % MillisPerDay) * 2;
}
-
+
millis += DoubleDateOffset / TicksPerMillisecond;
if (millis < 0 || millis >= MaxMillis) throw new ArgumentException(Environment.GetResourceString("Arg_OleAutDateScale"));
@@ -565,14 +622,17 @@ namespace System {
// is equal to the value of this DateTime. Returns false
// otherwise.
//
- public override bool Equals(Object value) {
- if (value is DateTime) {
+ public override bool Equals(Object value)
+ {
+ if (value is DateTime)
+ {
return InternalTicks == ((DateTime)value).InternalTicks;
}
return false;
}
-
- public bool Equals(DateTime value) {
+
+ public bool Equals(DateTime value)
+ {
return InternalTicks == value.InternalTicks;
}
@@ -580,90 +640,107 @@ namespace System {
// the two DateTime values are equal, or false if they are
// not equal.
//
- public static bool Equals(DateTime t1, DateTime t2) {
+ 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) {
+
+ 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) {
+ 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) {
+ if (ticks < MinTicks)
+ {
offsetTicks = TimeZoneInfo.GetLocalUtcOffset(DateTime.MinValue, TimeZoneInfoOptions.NoThrowOnInvalidTime).Ticks;
}
- else if (ticks > MaxTicks) {
+ else if (ticks > MaxTicks)
+ {
offsetTicks = TimeZoneInfo.GetLocalUtcOffset(DateTime.MaxValue, TimeZoneInfoOptions.NoThrowOnInvalidTime).Ticks;
}
- else {
+ 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) {
+ if (ticks < 0)
+ {
ticks += TicksPerDay;
- }
- if (ticks < MinTicks || ticks > MaxTicks) {
+ }
+ if (ticks < MinTicks || ticks > MaxTicks)
+ {
throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeBadBinaryData"), nameof(dateData));
}
- return new DateTime(ticks, DateTimeKind.Local, isAmbiguousLocalDst);
+ return new DateTime(ticks, DateTimeKind.Local, isAmbiguousLocalDst);
}
- else {
+ 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) {
+ 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) {
+ public static DateTime FromFileTime(long fileTime)
+ {
return FromFileTimeUtc(fileTime).ToLocalTime();
}
- public static DateTime FromFileTimeUtc(long fileTime) {
- if (fileTime < 0 || fileTime > MaxTicks - FileTimeOffset) {
+ 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;
+ long universalTicks = fileTime + FileTimeOffset;
return new DateTime(universalTicks, DateTimeKind.Utc);
}
-
+
// Creates a DateTime from an OLE Automation Date.
//
- public static DateTime FromOADate(double d) {
+ public static DateTime FromOADate(double d)
+ {
return new DateTime(DoubleDateToTicks(d), DateTimeKind.Unspecified);
- }
+ }
- void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
- if (info==null) {
+ void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
+ {
+ if (info == null)
+ {
throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
@@ -673,24 +750,29 @@ namespace System {
info.AddValue(DateDataField, dateData);
}
- public Boolean IsDaylightSavingTime() {
- if (Kind == DateTimeKind.Utc) {
+ public Boolean IsDaylightSavingTime()
+ {
+ if (Kind == DateTimeKind.Utc)
+ {
return false;
}
return TimeZoneInfo.Local.IsDaylightSavingTime(this, TimeZoneInfoOptions.NoThrowOnInvalidTime);
- }
-
- public static DateTime SpecifyKind(DateTime value, DateTimeKind kind) {
+ }
+
+ public static DateTime SpecifyKind(DateTime value, DateTimeKind kind)
+ {
return new DateTime(value.InternalTicks, kind);
- }
-
- public Int64 ToBinary() {
- if (Kind == DateTimeKind.Local) {
+ }
+
+ 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
@@ -699,30 +781,35 @@ namespace System {
TimeSpan offset = TimeZoneInfo.GetLocalUtcOffset(this, TimeZoneInfoOptions.NoThrowOnInvalidTime);
Int64 ticks = Ticks;
Int64 storedTicks = ticks - offset.Ticks;
- if (storedTicks < 0) {
+ if (storedTicks < 0)
+ {
storedTicks = TicksCeiling + storedTicks;
}
- return storedTicks | (unchecked((Int64) LocalMask));
+ return storedTicks | (unchecked((Int64)LocalMask));
}
- else {
+ 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 {
+ 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) {
+ private int GetDatePart(int part)
+ {
Int64 ticks = InternalTicks;
// n = number of days since 1/1/0001
int n = (int)(ticks / TicksPerDay);
@@ -745,7 +832,8 @@ namespace System {
// 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) {
+ if (part == DatePartYear)
+ {
return y400 * 400 + y100 * 100 + y4 * 4 + y1 + 1;
}
// n = day number within year
@@ -755,7 +843,7 @@ namespace System {
// 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;
@@ -766,142 +854,167 @@ namespace System {
// 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 {
+ 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 {
+ 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 {
+ 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() {
+ 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 {
+ public int Hour
+ {
+ get
+ {
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.Ensures(Contract.Result<int>() < 24);
- return (int)((InternalTicks / TicksPerHour) % 24);
+ return (int)((InternalTicks / TicksPerHour) % 24);
}
}
-
- internal Boolean IsAmbiguousDaylightSavingTime() {
+
+ internal Boolean IsAmbiguousDaylightSavingTime()
+ {
return (InternalKind == KindLocalAmbiguousDst);
- }
-
+ }
+
[Pure]
- public DateTimeKind Kind {
- get {
- switch (InternalKind) {
+ public DateTimeKind Kind
+ {
+ get
+ {
+ switch (InternalKind)
+ {
case KindUnspecified:
return DateTimeKind.Unspecified;
case KindUtc:
return DateTimeKind.Utc;
default:
- return DateTimeKind.Local;
+ return DateTimeKind.Local;
}
}
- }
-
+ }
+
// Returns the millisecond part of this DateTime. The returned value
// is an integer between 0 and 999.
//
- public int Millisecond {
- get {
+ public int Millisecond
+ {
+ get
+ {
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.Ensures(Contract.Result<int>() < 1000);
- return (int)((InternalTicks/ TicksPerMillisecond) % 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 {
+ public int Minute
+ {
+ get
+ {
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.Ensures(Contract.Result<int>() < 60);
- return (int)((InternalTicks / TicksPerMinute) % 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 {
+ 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 {
+ public static DateTime Now
+ {
+ get
+ {
Contract.Ensures(Contract.Result<DateTime>().Kind == DateTimeKind.Local);
- DateTime utc = UtcNow;
+ DateTime utc = UtcNow;
Boolean isAmbiguousLocalDst = false;
Int64 offset = TimeZoneInfo.GetDateTimeNowUtcOffsetFromUtc(utc, out isAmbiguousLocalDst).Ticks;
long tick = utc.Ticks + offset;
- if (tick>DateTime.MaxTicks) {
+ if (tick > DateTime.MaxTicks)
+ {
return new DateTime(DateTime.MaxTicks, DateTimeKind.Local);
}
- if (tick<DateTime.MinTicks) {
+ if (tick < DateTime.MinTicks)
+ {
return new DateTime(DateTime.MinTicks, DateTimeKind.Local);
}
- return new DateTime(tick, DateTimeKind.Local, isAmbiguousLocalDst);
+ return new DateTime(tick, DateTimeKind.Local, isAmbiguousLocalDst);
}
}
- public static DateTime UtcNow {
- get {
+ 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);
+ return new DateTime(((UInt64)(ticks + FileTimeOffset)) | KindUtc);
}
}
@@ -910,94 +1023,110 @@ namespace System {
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 {
+ public int Second
+ {
+ get
+ {
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.Ensures(Contract.Result<int>() < 60);
- return (int)((InternalTicks / TicksPerSecond) % 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;
+ 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);
+ 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 {
+ 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 {
+ 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) {
+ 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) {
+ 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) {
+ 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) {
+ 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) {
+ public static DateTime ParseExact(String s, String format, IFormatProvider provider)
+ {
return (DateTimeParse.ParseExact(s, format, DateTimeFormatInfo.GetInstance(provider), DateTimeStyles.None));
}
@@ -1005,31 +1134,37 @@ namespace System {
// 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) {
+ 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) {
+ 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) {
+ public TimeSpan Subtract(DateTime value)
+ {
return new TimeSpan(InternalTicks - value.InternalTicks);
}
-
- public DateTime Subtract(TimeSpan value) {
- long ticks = InternalTicks;
+
+ public DateTime Subtract(TimeSpan value)
+ {
+ long ticks = InternalTicks;
long valueTicks = value._ticks;
- if (ticks - MinTicks < valueTicks || ticks - MaxTicks > valueTicks) {
+ 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) {
+ 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.
@@ -1038,30 +1173,35 @@ namespace System {
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 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() {
+ public double ToOADate()
+ {
return TicksToOADate(InternalTicks);
}
- public long ToFileTime() {
+ public long ToFileTime()
+ {
// Treats the input as local if it is not specified
return ToUniversalTime().ToFileTimeUtc();
}
- public long 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) {
+ if (ticks < 0)
+ {
throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("ArgumentOutOfRange_FileTimeInvalid"));
}
return ticks;
@@ -1074,7 +1214,8 @@ namespace System {
internal DateTime ToLocalTime(bool throwOnOverflow)
{
- if (Kind == DateTimeKind.Local) {
+ if (Kind == DateTimeKind.Local)
+ {
return this;
}
Boolean isDaylightSavings = false;
@@ -1095,115 +1236,139 @@ namespace System {
else
return new DateTime(DateTime.MinTicks, DateTimeKind.Local);
}
- return new DateTime(tick, DateTimeKind.Local, isAmbiguousLocalDst);
+ return new DateTime(tick, DateTimeKind.Local, isAmbiguousLocalDst);
}
-
- public String ToLongDateString() {
+
+ public String ToLongDateString()
+ {
Contract.Ensures(Contract.Result<String>() != null);
return DateTimeFormat.Format(this, "D", DateTimeFormatInfo.CurrentInfo);
}
-
- public String ToLongTimeString() {
+
+ public String ToLongTimeString()
+ {
Contract.Ensures(Contract.Result<String>() != null);
return DateTimeFormat.Format(this, "T", DateTimeFormatInfo.CurrentInfo);
}
-
- public String ToShortDateString() {
+
+ public String ToShortDateString()
+ {
Contract.Ensures(Contract.Result<String>() != null);
return DateTimeFormat.Format(this, "d", DateTimeFormatInfo.CurrentInfo);
}
-
- public String ToShortTimeString() {
+
+ public String ToShortTimeString()
+ {
Contract.Ensures(Contract.Result<String>() != null);
return DateTimeFormat.Format(this, "t", DateTimeFormatInfo.CurrentInfo);
}
-
- public override String ToString() {
+
+ public override String ToString()
+ {
Contract.Ensures(Contract.Result<String>() != null);
return DateTimeFormat.Format(this, null, DateTimeFormatInfo.CurrentInfo);
}
- public String ToString(String format) {
+ public String ToString(String format)
+ {
Contract.Ensures(Contract.Result<String>() != null);
return DateTimeFormat.Format(this, format, DateTimeFormatInfo.CurrentInfo);
}
- public String ToString(IFormatProvider provider) {
+ 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) {
+
+ public String ToString(String format, IFormatProvider provider)
+ {
Contract.Ensures(Contract.Result<String>() != null);
return DateTimeFormat.Format(this, format, DateTimeFormatInfo.GetInstance(provider));
}
-
- public DateTime ToUniversalTime() {
+
+ public DateTime ToUniversalTime()
+ {
return TimeZoneInfo.ConvertTimeToUtc(this, TimeZoneInfoOptions.NoThrowOnInvalidTime);
}
-
- public static Boolean TryParse(String s, out DateTime result) {
+
+ 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) {
+
+ 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) {
+ }
+
+ 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) {
+ 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) {
+
+ public static DateTime operator +(DateTime d, TimeSpan t)
+ {
long ticks = d.InternalTicks;
long valueTicks = t._ticks;
- if (valueTicks > MaxTicks - ticks || valueTicks < MinTicks - 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;
+ public static DateTime operator -(DateTime d, TimeSpan t)
+ {
+ long ticks = d.InternalTicks;
long valueTicks = t._ticks;
- if (ticks - MinTicks < valueTicks || ticks - MaxTicks > valueTicks) {
+ 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) {
+
+ public static TimeSpan operator -(DateTime d1, DateTime d2)
+ {
return new TimeSpan(d1.InternalTicks - d2.InternalTicks);
}
-
- public static bool operator ==(DateTime d1, DateTime d2) {
+
+ public static bool operator ==(DateTime d1, DateTime d2)
+ {
return d1.InternalTicks == d2.InternalTicks;
}
- public static bool operator !=(DateTime d1, DateTime d2) {
+ public static bool operator !=(DateTime d1, DateTime d2)
+ {
return d1.InternalTicks != d2.InternalTicks;
}
- public static bool operator <(DateTime t1, DateTime t2) {
+ public static bool operator <(DateTime t1, DateTime t2)
+ {
return t1.InternalTicks < t2.InternalTicks;
}
- public static bool operator <=(DateTime t1, DateTime t2) {
+ public static bool operator <=(DateTime t1, DateTime t2)
+ {
return t1.InternalTicks <= t2.InternalTicks;
}
- public static bool operator >(DateTime t1, DateTime t2) {
+ public static bool operator >(DateTime t1, DateTime t2)
+ {
return t1.InternalTicks > t2.InternalTicks;
}
- public static bool operator >=(DateTime t1, DateTime t2) {
+ public static bool operator >=(DateTime t1, DateTime t2)
+ {
return t1.InternalTicks >= t2.InternalTicks;
}
@@ -1225,8 +1390,8 @@ namespace System {
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.
@@ -1235,7 +1400,7 @@ namespace System {
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.
@@ -1244,117 +1409,139 @@ namespace System {
Contract.Ensures(Contract.Result<String[]>() != null);
return (DateTimeFormat.GetAllDateTimes(this, format, DateTimeFormatInfo.GetInstance(provider)));
}
-
+
//
// IConvertible implementation
//
-
- public TypeCode GetTypeCode() {
+
+ public TypeCode GetTypeCode()
+ {
return TypeCode.DateTime;
}
/// <internalonly/>
- bool IConvertible.ToBoolean(IFormatProvider provider) {
+ bool IConvertible.ToBoolean(IFormatProvider provider)
+ {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "DateTime", "Boolean"));
}
/// <internalonly/>
- char IConvertible.ToChar(IFormatProvider provider) {
+ char IConvertible.ToChar(IFormatProvider provider)
+ {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "DateTime", "Char"));
}
/// <internalonly/>
- sbyte IConvertible.ToSByte(IFormatProvider provider) {
+ sbyte IConvertible.ToSByte(IFormatProvider provider)
+ {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "DateTime", "SByte"));
}
/// <internalonly/>
- byte IConvertible.ToByte(IFormatProvider provider) {
+ byte IConvertible.ToByte(IFormatProvider provider)
+ {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "DateTime", "Byte"));
}
/// <internalonly/>
- short IConvertible.ToInt16(IFormatProvider provider) {
+ short IConvertible.ToInt16(IFormatProvider provider)
+ {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "DateTime", "Int16"));
}
/// <internalonly/>
- ushort IConvertible.ToUInt16(IFormatProvider provider) {
+ ushort IConvertible.ToUInt16(IFormatProvider provider)
+ {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "DateTime", "UInt16"));
}
/// <internalonly/>
- int IConvertible.ToInt32(IFormatProvider provider) {
+ int IConvertible.ToInt32(IFormatProvider provider)
+ {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "DateTime", "Int32"));
}
/// <internalonly/>
- uint IConvertible.ToUInt32(IFormatProvider provider) {
+ uint IConvertible.ToUInt32(IFormatProvider provider)
+ {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "DateTime", "UInt32"));
}
/// <internalonly/>
- long IConvertible.ToInt64(IFormatProvider provider) {
+ long IConvertible.ToInt64(IFormatProvider provider)
+ {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "DateTime", "Int64"));
}
/// <internalonly/>
- ulong IConvertible.ToUInt64(IFormatProvider provider) {
+ ulong IConvertible.ToUInt64(IFormatProvider provider)
+ {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "DateTime", "UInt64"));
}
/// <internalonly/>
- float IConvertible.ToSingle(IFormatProvider provider) {
+ float IConvertible.ToSingle(IFormatProvider provider)
+ {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "DateTime", "Single"));
}
/// <internalonly/>
- double IConvertible.ToDouble(IFormatProvider provider) {
+ double IConvertible.ToDouble(IFormatProvider provider)
+ {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "DateTime", "Double"));
}
/// <internalonly/>
- Decimal IConvertible.ToDecimal(IFormatProvider provider) {
+ Decimal IConvertible.ToDecimal(IFormatProvider provider)
+ {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "DateTime", "Decimal"));
}
/// <internalonly/>
- DateTime IConvertible.ToDateTime(IFormatProvider provider) {
+ DateTime IConvertible.ToDateTime(IFormatProvider provider)
+ {
return this;
}
/// <internalonly/>
- Object IConvertible.ToType(Type type, IFormatProvider provider) {
+ 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) {
+ 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) {
+ 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]) {
+ if (day < 1 || day > days[month] - days[month - 1])
+ {
return false;
- }
- 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)
+ {
return false;
- }
- if (millisecond < 0 || millisecond >= MillisPerSecond) {
+ }
+ 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) {
+ if (ticks < MinTicks || ticks > MaxTicks)
+ {
return false;
}
result = new DateTime(ticks, DateTimeKind.Unspecified);
return true;
- }
+ }
}
}
diff --git a/src/mscorlib/src/System/DateTimeOffset.cs b/src/mscorlib/src/System/DateTimeOffset.cs
index d64ba1582e..9f85edfe75 100644
--- a/src/mscorlib/src/System/DateTimeOffset.cs
+++ b/src/mscorlib/src/System/DateTimeOffset.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.Threading;
- using System.Globalization;
- using System.Runtime.InteropServices;
- using System.Runtime.CompilerServices;
- using System.Runtime.Serialization;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
+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;
+
+namespace System
+{
// 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.
@@ -31,7 +32,7 @@ namespace System {
// 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,
@@ -50,31 +51,35 @@ namespace System {
// Static Fields
public static readonly DateTimeOffset MinValue = new DateTimeOffset(DateTime.MinTicks, TimeSpan.Zero);
- public static readonly DateTimeOffset MaxValue = new DateTimeOffset(DateTime.MaxTicks, 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) {
+ 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) {
+ public DateTimeOffset(DateTime dateTime)
+ {
TimeSpan offset;
- if (dateTime.Kind != DateTimeKind.Utc) {
+ if (dateTime.Kind != DateTimeKind.Utc)
+ {
// Local and Unspecified are both treated as Local
offset = TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime);
}
- else {
+ else
+ {
offset = new TimeSpan(0);
}
m_offsetMinutes = ValidateOffset(offset);
@@ -84,78 +89,96 @@ namespace System {
// 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)) {
+ 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) {
+ 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) {
+ 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) {
+ 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) {
+ 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 {
+ public static DateTimeOffset Now
+ {
+ get
+ {
return new DateTimeOffset(DateTime.Now);
}
- }
+ }
- public static DateTimeOffset UtcNow {
- get {
+ public static DateTimeOffset UtcNow
+ {
+ get
+ {
return new DateTimeOffset(DateTime.UtcNow);
}
}
- public DateTime DateTime {
- get {
+ public DateTime DateTime
+ {
+ get
+ {
return ClockDateTime;
}
}
- public DateTime UtcDateTime {
+ public DateTime UtcDateTime
+ {
[Pure]
- get {
+ get
+ {
Contract.Ensures(Contract.Result<DateTime>().Kind == DateTimeKind.Utc);
return DateTime.SpecifyKind(m_dateTime, DateTimeKind.Utc);
}
}
- public DateTime LocalDateTime {
+ public DateTime LocalDateTime
+ {
[Pure]
- get {
+ get
+ {
Contract.Ensures(Contract.Result<DateTime>().Kind == DateTimeKind.Local);
return UtcDateTime.ToLocalTime();
}
@@ -163,232 +186,271 @@ namespace System {
// Adjust to a given offset with the same UTC time. Can throw ArgumentException
//
- public DateTimeOffset ToOffset(TimeSpan offset) {
+ 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 {
+ 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 {
+ 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 {
+ 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 {
+ public DayOfWeek DayOfWeek
+ {
+ get
+ {
Contract.Ensures(Contract.Result<DayOfWeek>() >= DayOfWeek.Sunday);
Contract.Ensures(Contract.Result<DayOfWeek>() <= DayOfWeek.Saturday);
- return ClockDateTime.DayOfWeek;
+ 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 {
+ 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 {
+ 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 {
+ public int Millisecond
+ {
+ get
+ {
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.Ensures(Contract.Result<int>() < 1000);
- return ClockDateTime.Millisecond;
+ return ClockDateTime.Millisecond;
}
}
-
+
// Returns the minute part of this DateTimeOffset. The returned value is
// an integer between 0 and 59.
//
- public int Minute {
- get {
+ 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 {
+ public int Month
+ {
+ get
+ {
Contract.Ensures(Contract.Result<int>() >= 1);
return ClockDateTime.Month;
}
}
-
- public TimeSpan Offset {
- get {
+
+ 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 {
+ 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 Ticks
+ {
+ get
+ {
+ return ClockDateTime.Ticks;
}
}
- public long UtcTicks {
- get {
- return UtcDateTime.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 {
+ 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 {
+ 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) {
+ 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) {
+ 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) {
+ 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) {
+ 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) {
+ public DateTimeOffset AddMinutes(double minutes)
+ {
return new DateTimeOffset(ClockDateTime.AddMinutes(minutes), Offset);
}
-
- public DateTimeOffset AddMonths(int months) {
+
+ 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) {
+ 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) {
+ 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
@@ -397,28 +459,32 @@ namespace System {
// 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) {
+ 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) {
+ 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) {
+ int IComparable.CompareTo(Object obj)
+ {
if (obj == null) return 1;
- if (!(obj is DateTimeOffset)) {
+ if (!(obj is DateTimeOffset))
+ {
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDateTimeOffset"));
}
-
+
DateTime objUtc = ((DateTimeOffset)obj).UtcDateTime;
DateTime utc = UtcDateTime;
if (utc > objUtc) return 1;
@@ -426,32 +492,37 @@ namespace System {
return 0;
}
- public int CompareTo(DateTimeOffset other) {
+ 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) {
+ public override bool Equals(Object obj)
+ {
+ if (obj is DateTimeOffset)
+ {
return UtcDateTime.Equals(((DateTimeOffset)obj).UtcDateTime);
}
return false;
}
-
- public bool Equals(DateTimeOffset other) {
+
+ public bool Equals(DateTimeOffset other)
+ {
return UtcDateTime.Equals(other.UtcDateTime);
}
- public bool EqualsExact(DateTimeOffset other) {
+ public bool EqualsExact(DateTimeOffset other)
+ {
//
// returns true when the ClockDateTime, Kind, and Offset match
//
@@ -465,20 +536,24 @@ namespace System {
// the two DateTimeOffset values are equal, or false if they are
// not equal.
//
- public static bool Equals(DateTimeOffset first, DateTimeOffset second) {
+ 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) {
+ public static DateTimeOffset FromFileTime(long fileTime)
+ {
return new DateTimeOffset(DateTime.FromFileTime(fileTime));
}
- public static DateTimeOffset FromUnixTimeSeconds(long seconds) {
- if (seconds < UnixMinSeconds || seconds > UnixMaxSeconds) {
+ public static DateTimeOffset FromUnixTimeSeconds(long seconds)
+ {
+ if (seconds < UnixMinSeconds || seconds > UnixMaxSeconds)
+ {
throw new ArgumentOutOfRangeException(nameof(seconds),
string.Format(Environment.GetResourceString("ArgumentOutOfRange_Range"), UnixMinSeconds, UnixMaxSeconds));
}
@@ -487,11 +562,13 @@ namespace System {
return new DateTimeOffset(ticks, TimeSpan.Zero);
}
- public static DateTimeOffset FromUnixTimeMilliseconds(long milliseconds) {
+ 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) {
+ if (milliseconds < MinMilliseconds || milliseconds > MaxMilliseconds)
+ {
throw new ArgumentOutOfRangeException(nameof(milliseconds),
string.Format(Environment.GetResourceString("ArgumentOutOfRange_Range"), MinMilliseconds, MaxMilliseconds));
}
@@ -499,22 +576,27 @@ namespace System {
long ticks = milliseconds * TimeSpan.TicksPerMillisecond + UnixEpochTicks;
return new DateTimeOffset(ticks, TimeSpan.Zero);
}
-
+
// ----- SECTION: private serialization instance methods ----------------*
- void IDeserializationCallback.OnDeserialization(Object sender) {
- try {
+ void IDeserializationCallback.OnDeserialization(Object sender)
+ {
+ try
+ {
m_offsetMinutes = ValidateOffset(Offset);
- m_dateTime = ValidateDate(ClockDateTime, Offset);
+ m_dateTime = ValidateDate(ClockDateTime, Offset);
}
- catch (ArgumentException e) {
+ catch (ArgumentException e)
+ {
throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"), e);
}
}
- void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
- if (info == null) {
+ void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
+ {
+ if (info == null)
+ {
throw new ArgumentNullException(nameof(info));
}
@@ -522,60 +604,67 @@ namespace System {
info.AddValue("DateTime", m_dateTime);
info.AddValue("OffsetMinutes", m_offsetMinutes);
- }
+ }
- DateTimeOffset(SerializationInfo info, StreamingContext context) {
- if (info == null) {
+ private DateTimeOffset(SerializationInfo info, StreamingContext context)
+ {
+ if (info == null)
+ {
throw new ArgumentNullException(nameof(info));
}
- m_dateTime = (DateTime)info.GetValue("DateTime", typeof(DateTime));
+ 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() {
+ 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) {
+ public static DateTimeOffset Parse(String input)
+ {
TimeSpan offset;
- DateTime dateResult = DateTimeParse.Parse(input,
- DateTimeFormatInfo.CurrentInfo,
- DateTimeStyles.None,
+ 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) {
+ public static DateTimeOffset Parse(String input, IFormatProvider formatProvider)
+ {
return Parse(input, formatProvider, DateTimeStyles.None);
}
-
- public static DateTimeOffset Parse(String input, IFormatProvider formatProvider, DateTimeStyles styles) {
+
+ 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,
+ 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) {
+ public static DateTimeOffset ParseExact(String input, String format, IFormatProvider formatProvider)
+ {
return ParseExact(input, format, formatProvider, DateTimeStyles.None);
}
@@ -583,42 +672,48 @@ namespace System {
// 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) {
+ 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,
+ 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) {
+ 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,
+ DateTime dateResult = DateTimeParse.ParseExactMultiple(input,
+ formats,
+ DateTimeFormatInfo.GetInstance(formatProvider),
+ styles,
out offset);
return new DateTimeOffset(dateResult.Ticks, offset);
}
- public TimeSpan Subtract(DateTimeOffset value) {
+ public TimeSpan Subtract(DateTimeOffset value)
+ {
return UtcDateTime.Subtract(value.UtcDateTime);
}
-
- public DateTimeOffset Subtract(TimeSpan value) {
+
+ public DateTimeOffset Subtract(TimeSpan value)
+ {
return new DateTimeOffset(ClockDateTime.Subtract(value), Offset);
}
-
-
- public long ToFileTime() {
+
+
+ public long ToFileTime()
+ {
return UtcDateTime.ToFileTime();
}
- public long ToUnixTimeSeconds() {
+ 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.
//
@@ -639,14 +734,16 @@ namespace System {
return seconds - UnixEpochSeconds;
}
- public long ToUnixTimeMilliseconds() {
+ 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() {
+
+ public DateTimeOffset ToLocalTime()
+ {
return ToLocalTime(false);
}
@@ -655,176 +752,203 @@ namespace System {
return new DateTimeOffset(UtcDateTime.ToLocalTime(throwOnOverflow));
}
- public override String ToString() {
+ public override String ToString()
+ {
Contract.Ensures(Contract.Result<String>() != null);
return DateTimeFormat.Format(ClockDateTime, null, DateTimeFormatInfo.CurrentInfo, Offset);
}
- public String ToString(String format) {
+ public String ToString(String format)
+ {
Contract.Ensures(Contract.Result<String>() != null);
return DateTimeFormat.Format(ClockDateTime, format, DateTimeFormatInfo.CurrentInfo, Offset);
}
- public String ToString(IFormatProvider formatProvider) {
+ 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) {
+
+ 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() {
+
+ public DateTimeOffset ToUniversalTime()
+ {
return new DateTimeOffset(UtcDateTime);
}
-
- public static Boolean TryParse(String input, out DateTimeOffset result) {
+
+ public static Boolean TryParse(String input, out DateTimeOffset result)
+ {
TimeSpan offset;
DateTime dateResult;
- Boolean parsed = DateTimeParse.TryParse(input,
- DateTimeFormatInfo.CurrentInfo,
- DateTimeStyles.None,
- out 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) {
+
+ 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,
+ 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) {
+ out DateTimeOffset result)
+ {
styles = ValidateStyles(styles, nameof(styles));
TimeSpan offset;
DateTime dateResult;
- Boolean parsed = DateTimeParse.TryParseExact(input,
+ Boolean parsed = DateTimeParse.TryParseExact(input,
format,
- DateTimeFormatInfo.GetInstance(formatProvider),
- styles,
- out dateResult,
+ 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) {
+ out DateTimeOffset result)
+ {
styles = ValidateStyles(styles, nameof(styles));
TimeSpan offset;
DateTime dateResult;
- Boolean parsed = DateTimeParse.TryParseExactMultiple(input,
+ Boolean parsed = DateTimeParse.TryParseExactMultiple(input,
formats,
- DateTimeFormatInfo.GetInstance(formatProvider),
- styles,
- out dateResult,
+ 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) {
+ private static Int16 ValidateOffset(TimeSpan offset)
+ {
Int64 ticks = offset.Ticks;
- if (ticks % TimeSpan.TicksPerMinute != 0) {
+ if (ticks % TimeSpan.TicksPerMinute != 0)
+ {
throw new ArgumentException(Environment.GetResourceString("Argument_OffsetPrecision"), nameof(offset));
}
- if (ticks < MinOffset || ticks > MaxOffset) {
+ 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) {
+ 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"));
+ 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) {
+
+ 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)) {
+ if (((style & (DateTimeStyles.AssumeLocal)) != 0) && ((style & (DateTimeStyles.AssumeUniversal)) != 0))
+ {
throw new ArgumentException(Environment.GetResourceString("Argument_ConflictingDateTimeStyles"), parameterName);
}
- if ((style & DateTimeStyles.NoCurrentDateDefault) != 0) {
+ 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;
-
+ 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) {
+
+ public static implicit operator DateTimeOffset(DateTime dateTime)
+ {
return new DateTimeOffset(dateTime);
}
- public static DateTimeOffset operator +(DateTimeOffset dateTimeOffset, TimeSpan timeSpan) {
+ public static DateTimeOffset operator +(DateTimeOffset dateTimeOffset, TimeSpan timeSpan)
+ {
return new DateTimeOffset(dateTimeOffset.ClockDateTime + timeSpan, dateTimeOffset.Offset);
}
-
- public static DateTimeOffset operator -(DateTimeOffset dateTimeOffset, TimeSpan timeSpan) {
+
+ public static DateTimeOffset operator -(DateTimeOffset dateTimeOffset, TimeSpan timeSpan)
+ {
return new DateTimeOffset(dateTimeOffset.ClockDateTime - timeSpan, dateTimeOffset.Offset);
}
-
- public static TimeSpan operator -(DateTimeOffset left, DateTimeOffset right) {
+
+ public static TimeSpan operator -(DateTimeOffset left, DateTimeOffset right)
+ {
return left.UtcDateTime - right.UtcDateTime;
}
-
- public static bool operator ==(DateTimeOffset left, DateTimeOffset right) {
+
+ public static bool operator ==(DateTimeOffset left, DateTimeOffset right)
+ {
return left.UtcDateTime == right.UtcDateTime;
}
- public static bool operator !=(DateTimeOffset left, DateTimeOffset right) {
+ public static bool operator !=(DateTimeOffset left, DateTimeOffset right)
+ {
return left.UtcDateTime != right.UtcDateTime;
}
-
- public static bool operator <(DateTimeOffset left, DateTimeOffset right) {
+
+ public static bool operator <(DateTimeOffset left, DateTimeOffset right)
+ {
return left.UtcDateTime < right.UtcDateTime;
}
- public static bool operator <=(DateTimeOffset left, DateTimeOffset right) {
+ public static bool operator <=(DateTimeOffset left, DateTimeOffset right)
+ {
return left.UtcDateTime <= right.UtcDateTime;
}
- public static bool operator >(DateTimeOffset left, DateTimeOffset right) {
+ public static bool operator >(DateTimeOffset left, DateTimeOffset right)
+ {
return left.UtcDateTime > right.UtcDateTime;
}
- public static bool operator >=(DateTimeOffset left, DateTimeOffset right) {
+ public static bool operator >=(DateTimeOffset left, DateTimeOffset right)
+ {
return left.UtcDateTime >= right.UtcDateTime;
}
-
}
}
diff --git a/src/mscorlib/src/System/Decimal.cs b/src/mscorlib/src/System/Decimal.cs
index a01ed19753..dedcc92e18 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];
@@ -275,44 +288,55 @@ namespace System {
}
throw new ArgumentException(Environment.GetResourceString("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"));
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(Environment.GetResourceString("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(Environment.GetResourceString("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;
@@ -321,46 +345,49 @@ namespace System {
}
throw new ArgumentException(Environment.GetResourceString("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
@@ -373,8 +400,8 @@ namespace System {
return 1;
if (!(value is Decimal))
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDecimal"));
-
- Decimal other = (Decimal)value;
+
+ 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) {
+ if (mode < MidpointRounding.ToEven || mode > MidpointRounding.AwayFromZero)
+ {
throw new ArgumentException(Environment.GetResourceString("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) {
+ catch (OverflowException e)
+ {
throw new OverflowException(Environment.GetResourceString("Overflow_Byte"), e);
}
if (temp < Byte.MinValue || temp > Byte.MaxValue) throw new OverflowException(Environment.GetResourceString("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) {
+ catch (OverflowException e)
+ {
throw new OverflowException(Environment.GetResourceString("Overflow_SByte"), e);
}
if (temp < SByte.MinValue || temp > SByte.MaxValue) throw new OverflowException(Environment.GetResourceString("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) {
+ catch (OverflowException e)
+ {
throw new OverflowException(Environment.GetResourceString("Overflow_Int16"), e);
}
if (temp < Int16.MinValue || temp > Int16.MaxValue) throw new OverflowException(Environment.GetResourceString("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"));
}
-
+
// 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"));
}
-
+
// 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) {
+ catch (OverflowException e)
+ {
throw new OverflowException(Environment.GetResourceString("Overflow_UInt16"), e);
}
if (temp < UInt16.MinValue || temp > UInt16.MaxValue) throw new OverflowException(Environment.GetResourceString("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"));
}
-
+
// 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"));
}
-
+
// 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) {
+ }
+ catch (OverflowException e)
+ {
throw new OverflowException(Environment.GetResourceString("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,99 @@ 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) {
+ char IConvertible.ToChar(IFormatProvider provider)
+ {
throw new InvalidCastException(Environment.GetResourceString("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) {
+ DateTime IConvertible.ToDateTime(IFormatProvider provider)
+ {
throw new InvalidCastException(Environment.GetResourceString("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.cs b/src/mscorlib/src/System/DefaultBinder.cs
index b4681c406d..789698f77e 100644
--- a/src/mscorlib/src/System/DefaultBinder.cs
+++ b/src/mscorlib/src/System/DefaultBinder.cs
@@ -8,8 +8,9 @@
// This class represents the Default COM+ binder.
//
//
-namespace System {
+namespace System
+{
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
@@ -35,18 +36,18 @@ namespace System {
// The most specific match will be selected.
//
public override MethodBase BindToMethod(
- BindingFlags bindingAttr, MethodBase[] match, ref Object[] args,
+ 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();
+ MethodBase[] candidates = (MethodBase[])match.Clone();
int i;
int j;
-
+
state = null;
#region Map named parameters to candidate parameter postions
@@ -57,37 +58,37 @@ namespace System {
// is not provided, then we assume the default mapping (0,1,...)
int[][] paramOrder = new int[candidates.Length][];
- for (i = 0; i < candidates.Length; i++)
+ 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)
+ if (names == null)
{
// Default mapping
for (j = 0; j < args.Length; j++)
paramOrder[i][j] = j;
}
- else
+ 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;
- }
+ 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++)
+ for (i = 0; i < args.Length; i++)
{
if (args[i] != null)
{
@@ -96,7 +97,7 @@ namespace System {
}
#endregion
-
+
// Find the method that matches...
int CurIdx = 0;
bool defaultValueBinding = ((bindingAttr & BindingFlags.OptionalParamBinding) != 0);
@@ -104,24 +105,24 @@ namespace System {
Type paramArrayType = null;
#region Filter methods by parameter count and type
- for (i = 0; i < candidates.Length; i++)
+ 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)
+ if (par.Length == 0)
{
#region No formal parameters
if (args.Length != 0)
{
- if ((candidates[i].CallingConvention & CallingConventions.VarArgs) == 0)
+ if ((candidates[i].CallingConvention & CallingConventions.VarArgs) == 0)
continue;
}
@@ -132,51 +133,51 @@ namespace System {
continue;
#endregion
}
- else if (par.Length > args.Length)
+ 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++)
+ for (j = args.Length; j < par.Length - 1; j++)
{
if (par[j].DefaultValue == System.DBNull.Value)
- break;
+ break;
}
if (j != par.Length - 1)
- continue;
+ continue;
- if (par[j].DefaultValue == System.DBNull.Value)
+ if (par[j].DefaultValue == System.DBNull.Value)
{
- if (!par[j].ParameterType.IsArray)
+ if (!par[j].ParameterType.IsArray)
continue;
- if (!par[j].IsDefined(typeof(ParamArrayAttribute), true))
+ if (!par[j].IsDefined(typeof(ParamArrayAttribute), true))
continue;
paramArrayType = par[j].ParameterType.GetElementType();
}
#endregion
}
- else if (par.Length < args.Length)
+ 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)
+ if (!par[lastArgPos].ParameterType.IsArray)
continue;
- if (!par[lastArgPos].IsDefined(typeof(ParamArrayAttribute), true))
+ if (!par[lastArgPos].IsDefined(typeof(ParamArrayAttribute), true))
continue;
if (paramOrder[i][lastArgPos] != lastArgPos)
- continue;
+ continue;
paramArrayType = par[lastArgPos].ParameterType.GetElementType();
#endregion
}
- else
+ else
{
#region Test for paramArray, save paramArray type
int lastArgPos = par.Length - 1;
@@ -196,7 +197,7 @@ namespace System {
int argsToCheck = (paramArrayType != null) ? par.Length - 1 : args.Length;
#region Match method by parameter type
- for (j = 0; j < argsToCheck; j++)
+ for (j = 0; j < argsToCheck; j++)
{
#region Classic argument coersion checks
// get the formal type
@@ -211,7 +212,7 @@ namespace System {
// a default value is available
if (defaultValueBinding && args[paramOrder[i][j]] == Type.Missing)
- continue;
+ continue;
// the argument was null, so it matches with everything
if (args[paramOrder[i][j]] == null)
@@ -222,21 +223,21 @@ namespace System {
continue;
// now do a "classic" type check
- if (pCls.IsPrimitive)
+ if (pCls.IsPrimitive)
{
- if (argTypes[paramOrder[i][j]] == null || !CanConvertPrimitiveObjectToType(args[paramOrder[i][j]],(RuntimeType)pCls))
+ if (argTypes[paramOrder[i][j]] == null || !CanConvertPrimitiveObjectToType(args[paramOrder[i][j]], (RuntimeType)pCls))
{
break;
}
}
- else
+ else
{
if (argTypes[paramOrder[i][j]] == null)
continue;
- if (!pCls.IsAssignableFrom(argTypes[paramOrder[i][j]]))
+ if (!pCls.IsAssignableFrom(argTypes[paramOrder[i][j]]))
{
- if (argTypes[paramOrder[i][j]].IsCOMObject)
+ if (argTypes[paramOrder[i][j]].IsCOMObject)
{
if (pCls.IsInstanceOfType(args[paramOrder[i][j]]))
continue;
@@ -247,24 +248,24 @@ namespace System {
#endregion
}
- if (paramArrayType != null && j == par.Length - 1)
+ if (paramArrayType != null && j == par.Length - 1)
{
#region Check that excess arguments can be placed in the param array
- for (; j < args.Length; j++)
+ for (; j < args.Length; j++)
{
- if (paramArrayType.IsPrimitive)
+ if (paramArrayType.IsPrimitive)
{
if (argTypes[j] == null || !CanConvertPrimitiveObjectToType(args[j], (RuntimeType)paramArrayType))
break;
}
- else
+ else
{
if (argTypes[j] == null)
continue;
- if (!paramArrayType.IsAssignableFrom(argTypes[j]))
+ if (!paramArrayType.IsAssignableFrom(argTypes[j]))
{
- if (argTypes[j].IsCOMObject)
+ if (argTypes[j].IsCOMObject)
{
if (paramArrayType.IsInstanceOfType(args[j]))
continue;
@@ -278,7 +279,7 @@ namespace System {
}
#endregion
- if (j == args.Length)
+ if (j == args.Length)
{
#region This is a valid routine so we move it up the candidates list
paramOrder[CurIdx] = paramOrder[i];
@@ -293,39 +294,39 @@ namespace System {
if (CurIdx == 0)
throw new MissingMethodException(Environment.GetResourceString("MissingMember"));
- if (CurIdx == 1)
+ if (CurIdx == 1)
{
#region Found only one method
- if (names != null)
+ if (names != null)
{
state = new BinderState((int[])paramOrder[0].Clone(), args.Length, paramArrayTypes[0] != null);
- ReorderParams(paramOrder[0],args);
+ 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();
+ ParameterInfo[] parms = candidates[0].GetParametersNoCopy();
- if (parms.Length == args.Length)
+ if (parms.Length == args.Length)
{
- if (paramArrayTypes[0] != null)
+ 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);
+ objs[lastPos] = Array.UnsafeCreateInstance(paramArrayTypes[0], 1);
((Array)objs[lastPos]).SetValue(args[lastPos], 0);
args = objs;
}
}
- else if (parms.Length > args.Length)
+ else if (parms.Length > args.Length)
{
Object[] objs = new Object[parms.Length];
- for (i=0;i<args.Length;i++)
+ for (i = 0; i < args.Length; i++)
objs[i] = args[i];
- for (;i<parms.Length - 1;i++)
+ for (; i < parms.Length - 1; i++)
objs[i] = parms[i].DefaultValue;
if (paramArrayTypes[0] != null)
@@ -336,14 +337,14 @@ namespace System {
args = objs;
}
- else
+ else
{
- if ((candidates[0].CallingConvention & CallingConventions.VarArgs) == 0)
+ 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);
+ objs[paramArrayPos] = Array.UnsafeCreateInstance(paramArrayTypes[0], args.Length - paramArrayPos);
Array.Copy(args, paramArrayPos, (System.Array)objs[paramArrayPos], 0, args.Length - paramArrayPos);
args = objs;
}
@@ -352,10 +353,10 @@ namespace System {
return candidates[0];
}
-
+
int currentMin = 0;
bool ambig = false;
- for (i = 1; i < CurIdx; i++)
+ 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],
@@ -365,7 +366,7 @@ namespace System {
{
ambig = true;
}
- else if (newMin == 2)
+ else if (newMin == 2)
{
currentMin = i;
ambig = false;
@@ -377,37 +378,38 @@ namespace System {
throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException"));
// Reorder (if needed)
- if (names != null) {
+ 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 (parameters.Length == args.Length)
{
- if (paramArrayTypes[currentMin] != null)
+ 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);
+ objs[lastPos] = Array.UnsafeCreateInstance(paramArrayTypes[currentMin], 1);
((Array)objs[lastPos]).SetValue(args[lastPos], 0);
args = objs;
}
}
- else if (parameters.Length > args.Length)
+ else if (parameters.Length > args.Length)
{
Object[] objs = new Object[parameters.Length];
- for (i=0;i<args.Length;i++)
+ for (i = 0; i < args.Length; i++)
objs[i] = args[i];
- for (;i<parameters.Length - 1;i++)
+ for (; i < parameters.Length - 1; i++)
objs[i] = parameters[i].DefaultValue;
- if (paramArrayTypes[currentMin] != null)
+ if (paramArrayTypes[currentMin] != null)
{
objs[i] = Array.UnsafeCreateInstance(paramArrayTypes[currentMin], 0);
}
@@ -418,9 +420,9 @@ namespace System {
args = objs;
}
- else
+ else
{
- if ((candidates[currentMin].CallingConvention & CallingConventions.VarArgs) == 0)
+ if ((candidates[currentMin].CallingConvention & CallingConventions.VarArgs) == 0)
{
Object[] objs = new Object[parameters.Length];
int paramArrayPos = parameters.Length - 1;
@@ -433,13 +435,14 @@ namespace System {
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)
+ public override FieldInfo BindToField(BindingFlags bindingAttr, FieldInfo[] match, Object value, CultureInfo cultureInfo)
{
- if (match == null) {
+ if (match == null)
+ {
throw new ArgumentNullException(nameof(match));
}
@@ -449,37 +452,47 @@ namespace System {
Type valueType = null;
- FieldInfo[] candidates = (FieldInfo[]) match.Clone();
-
+ FieldInfo[] candidates = (FieldInfo[])match.Clone();
+
// If we are a FieldSet, then use the value's type to disambiguate
- if ((bindingAttr & BindingFlags.SetField) != 0) {
+ if ((bindingAttr & BindingFlags.SetField) != 0)
+ {
valueType = value.GetType();
-
- for (i=0;i<candidates.Length;i++) {
+
+ for (i = 0; i < candidates.Length; i++)
+ {
Type pCls = candidates[i].FieldType;
- if (pCls == valueType) {
+ if (pCls == valueType)
+ {
candidates[CurIdx++] = candidates[i];
continue;
}
- if (value == Empty.Value) {
+ if (value == Empty.Value)
+ {
// the object passed in was null which would match any non primitive non value type
- if (pCls.IsClass) {
+ if (pCls.IsClass)
+ {
candidates[CurIdx++] = candidates[i];
continue;
}
}
- if (pCls == typeof(Object)) {
+ if (pCls == typeof(Object))
+ {
candidates[CurIdx++] = candidates[i];
continue;
}
- if (pCls.IsPrimitive) {
- if (CanConvertPrimitiveObjectToType(value,(RuntimeType)pCls)) {
+ if (pCls.IsPrimitive)
+ {
+ if (CanConvertPrimitiveObjectToType(value, (RuntimeType)pCls))
+ {
candidates[CurIdx++] = candidates[i];
continue;
}
}
- else {
- if (pCls.IsAssignableFrom(valueType)) {
+ else
+ {
+ if (pCls.IsAssignableFrom(valueType))
+ {
candidates[CurIdx++] = candidates[i];
continue;
}
@@ -490,16 +503,19 @@ namespace System {
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++) {
+ for (i = 1; i < CurIdx; i++)
+ {
int newMin = FindMostSpecificField(candidates[currentMin], candidates[i]);
if (newMin == 0)
ambig = true;
- else {
- if (newMin == 2) {
+ else
+ {
+ if (newMin == 2)
+ {
currentMin = i;
ambig = false;
}
@@ -509,48 +525,53 @@ namespace System {
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)
+ 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++) {
+ 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));
+ 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();
-
+ 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++) {
+ 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++) {
+ 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 (pCls.IsPrimitive)
+ {
if (!(types[j].UnderlyingSystemType is RuntimeType) ||
- !CanConvertPrimitive((RuntimeType)types[j].UnderlyingSystemType,(RuntimeType)pCls.UnderlyingSystemType))
+ !CanConvertPrimitive((RuntimeType)types[j].UnderlyingSystemType, (RuntimeType)pCls.UnderlyingSystemType))
break;
}
- else {
+ else
+ {
if (!pCls.IsAssignableFrom(types[j]))
break;
}
@@ -562,19 +583,22 @@ namespace System {
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++)
+ for (i = 0; i < types.Length; i++)
paramOrder[i] = i;
- for (i=1;i<CurIdx;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) {
+ else
+ {
+ if (newMin == 2)
+ {
currentMin = i;
ambig = false;
currentMin = i;
@@ -585,13 +609,13 @@ namespace System {
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)
+ 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; }))
+ if (indexes != null && !Contract.ForAll(indexes, delegate (Type t) { return t != null; }))
{
throw new ArgumentNullException(nameof(indexes));
}
@@ -599,50 +623,57 @@ namespace System {
throw new ArgumentException(Environment.GetResourceString("Arg_EmptyArray"), nameof(match));
Contract.EndContractBlock();
- PropertyInfo[] candidates = (PropertyInfo[]) match.Clone();
+ PropertyInfo[] candidates = (PropertyInfo[])match.Clone();
+
+ int i, j = 0;
- 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++) {
-
+ 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;
-
+
+ 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 (pCls.IsPrimitive)
+ {
if (!(indexes[j].UnderlyingSystemType is RuntimeType) ||
- !CanConvertPrimitive((RuntimeType)indexes[j].UnderlyingSystemType,(RuntimeType)pCls.UnderlyingSystemType))
+ !CanConvertPrimitive((RuntimeType)indexes[j].UnderlyingSystemType, (RuntimeType)pCls.UnderlyingSystemType))
break;
}
- else {
+ else
+ {
if (!pCls.IsAssignableFrom(indexes[j]))
break;
}
}
}
-
- if (j == indexesLength) {
- if (returnType != null) {
- if (candidates[i].PropertyType.IsPrimitive) {
+
+ 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))
+ !CanConvertPrimitive((RuntimeType)returnType.UnderlyingSystemType, (RuntimeType)candidates[i].PropertyType.UnderlyingSystemType))
continue;
}
- else {
+ else
+ {
if (!candidates[i].PropertyType.IsAssignableFrom(returnType))
continue;
}
@@ -654,15 +685,16 @@ namespace System {
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++)
+ 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);
+ 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,
@@ -670,7 +702,7 @@ namespace System {
candidates[i].GetIndexParameters(),
paramOrder,
null,
- indexes,
+ indexes,
null);
if (newMin == 0)
{
@@ -678,7 +710,8 @@ namespace System {
if (newMin == 0)
ambig = true;
}
- if (newMin == 2) {
+ if (newMin == 2)
+ {
ambig = false;
currentMin = i;
}
@@ -688,35 +721,40 @@ namespace System {
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)
+ 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) {
+ if (binderState.m_isParamArray)
+ {
int paramArrayPos = args.Length - 1;
if (args.Length == binderState.m_originalSize)
args[paramArrayPos] = ((Object[])args[paramArrayPos])[0];
- else {
+ 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++) {
+ 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) {
+ 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;
@@ -726,23 +764,26 @@ namespace System {
// 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)
+ public static MethodBase ExactBinding(MethodBase[] match, Type[] types, ParameterModifier[] modifiers)
{
- if (match==null)
+ 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++) {
+ for (int i = 0; i < match.Length; i++)
+ {
ParameterInfo[] par = match[i].GetParametersNoCopy();
- if (par.Length == 0) {
+ if (par.Length == 0)
+ {
continue;
}
int j;
- for (j=0;j<types.Length;j++) {
- Type pCls = par[j]. ParameterType;
-
+ for (j = 0; j < types.Length; j++)
+ {
+ Type pCls = par[j].ParameterType;
+
// If the classes exactly match continue
if (!pCls.Equals(types[j]))
break;
@@ -763,23 +804,25 @@ namespace System {
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)
+ public static PropertyInfo ExactPropertyBinding(PropertyInfo[] match, Type returnType, Type[] types, ParameterModifier[] modifiers)
{
- if (match==null)
+ 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++) {
+ for (int i = 0; i < match.Length; i++)
+ {
ParameterInfo[] par = match[i].GetIndexParameters();
int j;
- for (j=0;j<typesLength;j++) {
+ for (j = 0; j < typesLength; j++)
+ {
Type pCls = par[j].ParameterType;
-
+
// If the classes exactly match continue
if (pCls != types[j])
break;
@@ -788,7 +831,7 @@ namespace System {
continue;
if (returnType != null && returnType != match[i].PropertyType)
continue;
-
+
if (bestMatch != null)
throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException"));
@@ -839,7 +882,8 @@ namespace System {
if (c1 == c2) continue;
- switch (FindMostSpecificType(c1, c2, types[i])) {
+ switch (FindMostSpecificType(c1, c2, types[i]))
+ {
case 0: return 0;
case 1: p1Less = true; break;
case 2: p2Less = true; break;
@@ -872,18 +916,18 @@ namespace System {
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)
+ if (c1 == t)
return 1;
-
- if (c2 == t)
- return 2;
+
+ if (c2 == t)
+ return 2;
bool c1FromC2;
bool c2FromC1;
@@ -902,7 +946,7 @@ namespace System {
c1 = c1.GetElementType();
}
- else
+ else
{
if (c2.GetElementType() == c1)
return 1;
@@ -910,9 +954,9 @@ namespace System {
c2 = c2.GetElementType();
}
}
-
- if (c1.IsPrimitive && c2.IsPrimitive)
+
+ if (c1.IsPrimitive && c2.IsPrimitive)
{
c1FromC2 = CanConvertPrimitive((RuntimeType)c2, (RuntimeType)c1);
c2FromC1 = CanConvertPrimitive((RuntimeType)c1, (RuntimeType)c2);
@@ -942,7 +986,7 @@ namespace System {
{
// Find the most specific method based on the parameters.
int res = FindMostSpecific(m1.GetParametersNoCopy(), paramOrder1, paramArrayType1,
- m2.GetParametersNoCopy(), paramOrder2, paramArrayType2, types, args);
+ m2.GetParametersNoCopy(), paramOrder2, paramArrayType2, types, args);
// If the match was not ambigous then return the result.
if (res != 0)
@@ -956,11 +1000,11 @@ namespace System {
int hierarchyDepth2 = GetHierarchyDepth(m2.DeclaringType);
// The most derived method is the most specific one.
- if (hierarchyDepth1 == hierarchyDepth2)
+ if (hierarchyDepth1 == hierarchyDepth2)
{
- return 0;
+ return 0;
}
- else if (hierarchyDepth1 < hierarchyDepth2)
+ else if (hierarchyDepth1 < hierarchyDepth2)
{
return 2;
}
@@ -974,7 +1018,7 @@ namespace System {
return 0;
}
- private static int FindMostSpecificField(FieldInfo cur1,FieldInfo cur2)
+ private static int FindMostSpecificField(FieldInfo cur1, FieldInfo cur2)
{
// Check to see if the fields have the same name.
if (cur1.Name == cur2.Name)
@@ -982,11 +1026,12 @@ namespace System {
int hierarchyDepth1 = GetHierarchyDepth(cur1.DeclaringType);
int hierarchyDepth2 = GetHierarchyDepth(cur2.DeclaringType);
- if (hierarchyDepth1 == hierarchyDepth2) {
+ if (hierarchyDepth1 == hierarchyDepth2)
+ {
Debug.Assert(cur1.IsStatic != cur2.IsStatic, "hierarchyDepth1 == hierarchyDepth2");
- return 0;
+ return 0;
}
- else if (hierarchyDepth1 < hierarchyDepth2)
+ else if (hierarchyDepth1 < hierarchyDepth2)
return 2;
else
return 1;
@@ -996,7 +1041,7 @@ namespace System {
return 0;
}
- private static int FindMostSpecificProperty(PropertyInfo cur1,PropertyInfo cur2)
+ private static int FindMostSpecificProperty(PropertyInfo cur1, PropertyInfo cur2)
{
// Check to see if the fields have the same name.
if (cur1.Name == cur2.Name)
@@ -1004,10 +1049,11 @@ namespace System {
int hierarchyDepth1 = GetHierarchyDepth(cur1.DeclaringType);
int hierarchyDepth2 = GetHierarchyDepth(cur2.DeclaringType);
- if (hierarchyDepth1 == hierarchyDepth2) {
- return 0;
+ if (hierarchyDepth1 == hierarchyDepth2)
+ {
+ return 0;
}
- else if (hierarchyDepth1 < hierarchyDepth2)
+ else if (hierarchyDepth1 < hierarchyDepth2)
return 2;
else
return 1;
@@ -1016,7 +1062,7 @@ namespace System {
// The match is ambigous.
return 0;
}
-
+
internal static bool CompareMethodSigAndName(MethodBase m1, MethodBase m2)
{
ParameterInfo[] params1 = m1.GetParametersNoCopy();
@@ -1040,7 +1086,7 @@ namespace System {
int depth = 0;
Type currentType = t;
- do
+ do
{
depth++;
currentType = currentType.BaseType;
@@ -1081,43 +1127,46 @@ namespace System {
// 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);
+ 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);
-
+ 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)
+ private static void ReorderParams(int[] paramOrder, Object[] vars)
{
object[] varsCopy = new object[vars.Length];
- for (int i = 0; i < vars.Length; i ++)
+ for (int i = 0; i < vars.Length; i++)
varsCopy[i] = vars[i];
-
- for (int i = 0; i < vars.Length; 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)
+ 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++)
+ for (int i = 0; i < pars.Length; i++)
paramOrder[i] = -1;
// Find the parameters with names.
- for (int i=0;i<names.Length;i++) {
+ for (int i = 0; i < names.Length; i++)
+ {
int j;
- for (j=0;j<pars.Length;j++) {
- if (names[i].Equals(pars[j].Name)) {
+ for (j = 0; j < pars.Length; j++)
+ {
+ if (names[i].Equals(pars[j].Name))
+ {
paramOrder[j] = i;
used[i] = true;
break;
@@ -1128,13 +1177,17 @@ namespace System {
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]) {
+ 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;
@@ -1145,18 +1198,18 @@ namespace System {
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;
- }
+ 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 eefccd26d5..bd7a1f21db 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
@@ -59,11 +59,11 @@ namespace System {
DelegateBindingFlags.ClosedDelegateOnly))
throw new ArgumentException(Environment.GetResourceString("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));
@@ -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"));
-
+
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"));
}
-
+
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)
{
@@ -354,7 +353,7 @@ namespace System {
if (rtType == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), nameof(type));
if (!rtType.IsDelegate())
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"),nameof(type));
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"), nameof(type));
Delegate d = InternalAlloc(rtType);
// This API existed in v1/v1.1 and only expected to create closed
@@ -374,16 +373,16 @@ namespace System {
throw new ArgumentException(Environment.GetResourceString("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,7 +393,7 @@ 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)
@@ -410,7 +409,7 @@ namespace System {
if (rtTarget == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), nameof(target));
if (!rtType.IsDelegate())
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"),nameof(type));
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"), nameof(type));
Delegate d = InternalAlloc(rtType);
// This API existed in v1/v1.1 and only expected to create open
@@ -426,10 +425,10 @@ namespace System {
throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTargMeth"));
d = null;
}
-
+
return d;
}
-
+
// V1 API.
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public static Delegate CreateDelegate(Type type, MethodInfo method, bool throwOnBindFailure)
@@ -473,7 +472,7 @@ namespace System {
return d;
}
-
+
// V2 API.
public static Delegate CreateDelegate(Type type, Object firstArgument, MethodInfo method)
{
@@ -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
//
@@ -564,10 +563,10 @@ namespace System {
RuntimeType rtType = type as RuntimeType;
if (rtType == null)
throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), nameof(type));
-
+
if (!rtType.IsDelegate())
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"), nameof(type));
-
+
// Initialize the method...
Delegate d = InternalAlloc(rtType);
// This is a new internal API added in Whidbey. Currently it's only
@@ -600,7 +599,7 @@ namespace System {
if (!type.IsDelegate())
throw new ArgumentException(Environment.GetResourceString("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
@@ -661,13 +660,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 +702,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..4112816ba5 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,14 +21,14 @@ 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(Environment.GetResourceString("Arg_MustBeDelegate"), "type");
if (method.DeclaringType == null)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_GlobalMethodSerialization"));
@@ -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
@@ -211,18 +211,18 @@ namespace System
// 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))
+ if (de.target != null && !targetType.IsInstanceOfType(de.target))
throw new InvalidCastException();
- Object target=de.target;
+ Object target = de.target;
d = Delegate.CreateDelegateNoSecurityCheck(type, target, m_methods[index]);
}
else
{
if (de.target != null)
{
- if(!targetType.IsInstanceOfType(de.target))
+ if (!targetType.IsInstanceOfType(de.target))
throw new InvalidCastException();
- d = Delegate.CreateDelegate(type, de.target, de.methodName);
+ d = Delegate.CreateDelegate(type, de.target, de.methodName);
}
else
d = Delegate.CreateDelegate(type, targetType, de.methodName);
@@ -256,7 +256,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
diff --git a/src/mscorlib/src/System/Diagnostics/Assert.cs b/src/mscorlib/src/System/Diagnostics/Assert.cs
index 9f4b86b7e4..c0b4e4c229 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)
@@ -67,8 +68,8 @@ namespace System.Diagnostics {
{
throw new InvalidOperationException(
Environment.GetResourceString("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
index fb26fcc4ab..59125dd074 100644
--- a/src/mscorlib/src/System/Diagnostics/CodeAnalysis/SuppressMessageAttribute.cs
+++ b/src/mscorlib/src/System/Diagnostics/CodeAnalysis/SuppressMessageAttribute.cs
@@ -16,7 +16,6 @@ using System;
namespace System.Diagnostics.CodeAnalysis
{
-
[AttributeUsage(
AttributeTargets.All,
Inherited = false,
@@ -32,41 +31,41 @@ namespace System.Diagnostics.CodeAnalysis
private string scope;
private string target;
private string messageId;
-
+
public SuppressMessageAttribute(string category, string checkId)
{
- this.category = category;
+ 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; }
diff --git a/src/mscorlib/src/System/Diagnostics/ConditionalAttribute.cs b/src/mscorlib/src/System/Diagnostics/ConditionalAttribute.cs
index c57fb59319..5212db8599 100644
--- a/src/mscorlib/src/System/Diagnostics/ConditionalAttribute.cs
+++ b/src/mscorlib/src/System/Diagnostics/ConditionalAttribute.cs
@@ -4,9 +4,10 @@
using System;
-namespace System.Diagnostics {
+namespace System.Diagnostics
+{
[Serializable]
- [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple=true)]
+ [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true)]
public sealed class ConditionalAttribute : Attribute
{
public ConditionalAttribute(String conditionString)
@@ -14,8 +15,10 @@ namespace System.Diagnostics {
m_conditionString = conditionString;
}
- public String ConditionString {
- get {
+ public String ConditionString
+ {
+ get
+ {
return m_conditionString;
}
}
diff --git a/src/mscorlib/src/System/Diagnostics/Contracts/Contracts.cs b/src/mscorlib/src/System/Diagnostics/Contracts/Contracts.cs
index 4469bffb9c..b768e4d3dd 100644
--- a/src/mscorlib/src/System/Diagnostics/Contracts/Contracts.cs
+++ b/src/mscorlib/src/System/Diagnostics/Contracts/Contracts.cs
@@ -42,8 +42,8 @@ using System.Runtime.ConstrainedExecution;
using System.Security;
#endif
-namespace System.Diagnostics.Contracts {
-
+namespace System.Diagnostics.Contracts
+{
#region Attributes
/// <summary>
@@ -70,7 +70,8 @@ namespace System.Diagnostics.Contracts {
_typeWithContracts = typeContainingContracts;
}
- public Type TypeContainingContracts {
+ public Type TypeContainingContracts
+ {
get { return _typeWithContracts; }
}
}
@@ -89,7 +90,8 @@ namespace System.Diagnostics.Contracts {
_typeIAmAContractFor = typeContractsAreFor;
}
- public Type TypeContractsAreFor {
+ public Type TypeContractsAreFor
+ {
get { return _typeIAmAContractFor; }
}
}
@@ -175,7 +177,8 @@ namespace System.Diagnostics.Contracts {
public ContractVerificationAttribute(bool value) { _value = value; }
- public bool Value {
+ public bool Value
+ {
get { return _value; }
}
}
@@ -196,7 +199,8 @@ namespace System.Diagnostics.Contracts {
_publicName = name;
}
- public String Name {
+ public String Name
+ {
get { return _publicName; }
}
}
@@ -246,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; }
}
}
@@ -295,7 +303,8 @@ namespace System.Diagnostics.Contracts {
#endif
public static void Assume(bool condition)
{
- if (!condition) {
+ if (!condition)
+ {
ReportFailure(ContractFailureKind.Assume, null, null, null);
}
}
@@ -315,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);
}
}
@@ -768,7 +778,8 @@ namespace System.Diagnostics.Contracts {
#endregion
}
- public enum ContractFailureKind {
+ public enum ContractFailureKind
+ {
Precondition,
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Postcondition")]
Postcondition,
@@ -778,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 00c9c35027..1e86b914e6 100644
--- a/src/mscorlib/src/System/Diagnostics/Contracts/ContractsBCL.cs
+++ b/src/mscorlib/src/System/Diagnostics/Contracts/ContractsBCL.cs
@@ -36,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
@@ -115,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;
}
}
@@ -158,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; }
}
@@ -169,7 +173,8 @@ namespace System.Diagnostics.Contracts {
_handled = true;
}
- public bool Unwind {
+ public bool Unwind
+ {
get { return _unwind; }
}
@@ -185,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; } }
@@ -208,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)
@@ -258,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
@@ -274,7 +280,8 @@ namespace System.Runtime.CompilerServices
}
#if FEATURE_UNTRUSTED_CALLERS
#endif
- remove {
+ remove
+ {
lock (lockObject)
{
contractFailedEvent -= value;
@@ -368,7 +375,8 @@ 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);
}
@@ -429,11 +437,13 @@ 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);
}
- else {
+ else
+ {
failureMessage = Environment.GetResourceString(resourceName);
}
diff --git a/src/mscorlib/src/System/Diagnostics/Debugger.cs b/src/mscorlib/src/System/Diagnostics/Debugger.cs
index 21c57dbfaf..aad67bc197 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
{
@@ -36,7 +36,7 @@ namespace System.Diagnostics
BreakInternal();
}
- static void BreakCanThrow()
+ private static void BreakCanThrow()
{
BreakInternal();
}
@@ -128,7 +128,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
index 1a1f5fa2c0..f605179490 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/ActivityTracker.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/ActivityTracker.cs
@@ -15,6 +15,7 @@ using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract;
namespace Microsoft.Diagnostics.Tracing
#else
using System.Threading.Tasks;
+
namespace System.Diagnostics.Tracing
#endif
{
@@ -43,7 +44,6 @@ namespace System.Diagnostics.Tracing
/// </summary>
internal class ActivityTracker
{
-
/// <summary>
/// Called on work item begins. The activity name = providerName + activityName without 'Start' suffix.
/// It updates CurrentActivityId to track.
@@ -123,7 +123,7 @@ namespace System.Diagnostics.Tracing
// Remember the current ID so we can log it
activityId = newActivity.ActivityId;
-
+
if (etwLog.Debug)
{
etwLog.DebugFacilityMessage("OnStartRetActivityState", ActivityInfo.LiveActivities(newActivity));
@@ -143,7 +143,7 @@ namespace System.Diagnostics.Tracing
return;
var fullActivityName = NormalizeActivityName(providerName, activityName, task);
-
+
var etwLog = TplEtwProvider.Log;
if (etwLog.Debug)
{
@@ -151,7 +151,7 @@ namespace System.Diagnostics.Tracing
etwLog.DebugFacilityMessage("OnStopEnterActivityState", ActivityInfo.LiveActivities(m_current.Value));
}
- for (; ; ) // This is a retry loop.
+ 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.
@@ -230,12 +230,13 @@ namespace System.Diagnostics.Tracing
{
m_current = new AsyncLocal<ActivityInfo>(ActivityChanging);
}
- catch (NotImplementedException) {
+ 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
- }
+ }
}
}
@@ -427,7 +428,7 @@ namespace System.Diagnostics.Tracing
/// the value is either encoded into nibble itself or it can spill over into the
/// bytes that follow.
/// </summary>
- enum NumberListCodes : byte
+ private enum NumberListCodes : byte
{
End = 0x0, // ends the list. No valid value has this prefix.
LastImmediateValue = 0xA,
@@ -536,7 +537,7 @@ namespace System.Diagnostics.Tracing
#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
+ private 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)
@@ -551,7 +552,7 @@ namespace System.Diagnostics.Tracing
// 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)
+ private void ActivityChanging(AsyncLocalValueChangedArgs<ActivityInfo> args)
{
ActivityInfo cur = args.CurrentValue;
ActivityInfo prev = args.PreviousValue;
@@ -595,14 +596,14 @@ namespace System.Diagnostics.Tracing
///
/// 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;
+ private AsyncLocal<ActivityInfo> m_current;
+ private 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 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.
@@ -661,5 +662,4 @@ namespace System.Diagnostics.Tracing
}
}
#endif
-
}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/EventDescriptor.cs b/src/mscorlib/src/System/Diagnostics/Eventing/EventDescriptor.cs
index 116b50f86c..2294fb94f8 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/EventDescriptor.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/EventDescriptor.cs
@@ -53,14 +53,14 @@ namespace System.Diagnostics.Tracing
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;
+ m_id = 0;
+ m_version = 0;
+ m_channel = 0;
+ m_traceloggingId = traceloggingId;
+ m_level = level;
+ m_opcode = opcode;
+ m_task = 0;
+ m_keywords = keywords;
}
public EventDescriptor(
@@ -159,7 +159,7 @@ namespace System.Diagnostics.Tracing
if (!(obj is EventDescriptor))
return false;
- return Equals((EventDescriptor) obj);
+ return Equals((EventDescriptor)obj);
}
public override int GetHashCode()
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/EventProvider.cs b/src/mscorlib/src/System/Diagnostics/Eventing/EventProvider.cs
index 1da6a46707..046b27b6b3 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/EventProvider.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/EventProvider.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 Microsoft.Win32;
using System.Collections.Generic;
using System.Diagnostics;
@@ -45,7 +46,7 @@ namespace System.Diagnostics.Tracing
/// Only here because System.Diagnostics.EventProvider needs one more extensibility hook (when it gets a
/// controller callback)
/// </summary>
-#if !CORECLR
+#if !CORECLR
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
#endif // CORECLR
internal partial class EventProvider : IDisposable
@@ -78,7 +79,7 @@ namespace System.Diagnostics.Tracing
private static bool m_setInformationMissing;
- UnsafeNativeMethods.ManifestEtw.EtwEnableCallback m_etwCallback; // Trace Callback function
+ private 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
@@ -178,7 +179,7 @@ namespace System.Diagnostics.Tracing
// Do most of the work under a lock to avoid shutdown race.
- long registrationHandle = 0;
+ long registrationHandle = 0;
lock (EventListener.EventListenersLock)
{
// Double check
@@ -200,7 +201,6 @@ namespace System.Diagnostics.Tracing
// We solve by Unregistering after releasing the EventListenerLock.
if (registrationHandle != 0)
EventUnregister(registrationHandle);
-
}
/// <summary>
@@ -221,7 +221,7 @@ namespace System.Diagnostics.Tracing
// <UsesUnsafeCode Name="Parameter filterData of type: Void*" />
// <UsesUnsafeCode Name="Parameter callbackContext of type: Void*" />
// </SecurityKernel>
- unsafe void EtwEnableCallBack(
+ private unsafe void EtwEnableCallBack(
[In] ref System.Guid sourceId,
[In] int controlCode,
[In] byte setLevel,
@@ -362,7 +362,6 @@ namespace System.Diagnostics.Tracing
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)
@@ -413,7 +412,7 @@ namespace System.Diagnostics.Tracing
}
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
@@ -432,7 +431,7 @@ namespace System.Diagnostics.Tracing
#if ES_SESSION_INFO || !ES_BUILD_STANDALONE
int buffSize = 256; // An initial guess that probably works most of the time.
byte* buffer;
- for (; ; )
+ for (;;)
{
var space = stackalloc byte[buffSize];
buffer = space;
@@ -621,7 +620,6 @@ namespace System.Diagnostics.Tracing
if ((level <= m_level) ||
(m_level == 0))
{
-
//
// Check if Keyword is enabled
//
@@ -1186,7 +1184,7 @@ namespace System.Diagnostics.Tracing
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[] 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;
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/EventSource.cs b/src/mscorlib/src/System/Diagnostics/Eventing/EventSource.cs
index a558a1647e..3668d8cb64 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/EventSource.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/EventSource.cs
@@ -252,7 +252,6 @@ namespace System.Diagnostics.Tracing
/// </remarks>
public partial class EventSource : IDisposable
{
-
#if FEATURE_EVENTSOURCE_XPLAT
private static readonly EventListener persistent_Xplat_Listener = XplatEventLogger.InitializePersistentListener();
#endif //FEATURE_EVENTSOURCE_XPLAT
@@ -1160,7 +1159,6 @@ namespace System.Diagnostics.Tracing
#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;
@@ -1243,7 +1241,6 @@ namespace System.Diagnostics.Tracing
m_eventData[eventId].Tags,
m_eventData[eventId].Parameters);
Interlocked.CompareExchange(ref m_eventData[eventId].TraceLoggingEventTypes, tlet, null);
-
}
EventSourceOptions opt = new EventSourceOptions
{
@@ -1548,18 +1545,18 @@ namespace System.Diagnostics.Tracing
/// </summary>
public void Start()
{
- if (this.w == null)
+ if (w == null)
{
- this.w = new uint[85];
+ 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;
+ length = 0;
+ pos = 0;
+ w[80] = 0x67452301;
+ w[81] = 0xEFCDAB89;
+ w[82] = 0x98BADCFE;
+ w[83] = 0x10325476;
+ w[84] = 0xC3D2E1F0;
}
/// <summary>
@@ -1568,8 +1565,8 @@ namespace System.Diagnostics.Tracing
/// <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)
+ w[pos / 4] = (w[pos / 4] << 8) | input;
+ if (64 == ++pos)
{
this.Drain();
}
@@ -1605,9 +1602,9 @@ namespace System.Diagnostics.Tracing
/// </param>
public void Finish(byte[] output)
{
- long l = this.length + 8 * this.pos;
+ long l = length + 8 * pos;
this.Append(0x80);
- while (this.pos != 56)
+ while (pos != 56)
{
this.Append(0x00);
}
@@ -1626,9 +1623,9 @@ namespace System.Diagnostics.Tracing
int end = output.Length < 20 ? output.Length : 20;
for (int i = 0; i != end; i++)
{
- uint temp = this.w[80 + i / 4];
+ uint temp = w[80 + i / 4];
output[i] = (byte)(temp >> 24);
- this.w[80 + i / 4] = temp << 8;
+ w[80 + i / 4] = temp << 8;
}
}
}
@@ -1640,54 +1637,54 @@ namespace System.Diagnostics.Tracing
{
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]));
+ w[i] = Rol1((w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ 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];
+ uint a = w[80];
+ uint b = w[81];
+ uint c = w[82];
+ uint d = w[83];
+ uint e = 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;
+ uint temp = Rol5(a) + f + e + k + 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;
+ uint temp = Rol5(a) + f + e + k + 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;
+ uint temp = Rol5(a) + f + e + k + 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;
+ uint temp = Rol5(a) + f + e + k + 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;
+ w[80] += a;
+ w[81] += b;
+ w[82] += c;
+ w[83] += d;
+ w[84] += e;
}
- this.length += 512; // 64 bytes == 512 bits
- this.pos = 0;
+ length += 512; // 64 bytes == 512 bits
+ pos = 0;
}
private static uint Rol1(uint input)
@@ -1731,7 +1728,7 @@ namespace System.Diagnostics.Tracing
Type dataType = GetDataType(m_eventData[eventId], parameterId);
- Again:
+ Again:
if (dataType == typeof(IntPtr))
{
return *((IntPtr*)dataPointer);
@@ -1843,7 +1840,6 @@ namespace System.Diagnostics.Tracing
// ETW strings are NULL-terminated, so marshal everything up to the first
// null in the string.
return System.Runtime.InteropServices.Marshal.PtrToStringUni(dataPointer);
-
}
finally
{
@@ -1995,7 +1991,6 @@ namespace System.Diagnostics.Tracing
EventTags.None,
m_eventData[eventId].Parameters);
Interlocked.CompareExchange(ref m_eventData[eventId].TraceLoggingEventTypes, tlet, null);
-
}
// TODO: activity ID support
EventSourceOptions opt = new EventSourceOptions
@@ -2387,7 +2382,6 @@ namespace System.Diagnostics.Tracing
}
}
return true;
-
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
private void ThrowEventSourceException(string eventName, Exception innerEx = null)
@@ -2476,7 +2470,7 @@ namespace System.Diagnostics.Tracing
{
public OverideEventProvider(EventSource eventSource)
{
- this.m_eventSource = eventSource;
+ m_eventSource = eventSource;
}
protected override void OnControllerCommand(ControllerCommand command, IDictionary<string, string> arguments,
int perEventSourceSessionId, int etwSessionId)
@@ -2559,7 +2553,7 @@ namespace System.Diagnostics.Tracing
if (m_completelyInited)
{
// After the first command arrive after construction, we are ready to get rid of the deferred commands
- this.m_deferredCommands = null;
+ m_deferredCommands = null;
// We are fully initialized, do the command
DoCommand(commandArgs);
}
@@ -2713,7 +2707,7 @@ namespace System.Diagnostics.Tracing
}
this.OnEventCommand(commandArgs);
- var eventCommandCallback = this.m_eventCommandExecuted;
+ var eventCommandCallback = m_eventCommandExecuted;
if (eventCommandCallback != null)
eventCommandCallback(this, commandArgs);
@@ -3015,7 +3009,6 @@ namespace System.Diagnostics.Tracing
Debug.Assert(m_rawManifest == null);
m_rawManifest = CreateManifestAndDescriptors(this.GetType(), Name, this);
Debug.Assert(m_eventData != null);
-
}
else
{
@@ -3093,7 +3086,7 @@ namespace System.Diagnostics.Tracing
dataDescrs[1].Reserved = 0;
int chunkSize = ManifestEnvelope.MaxChunkSize;
- TRY_AGAIN_WITH_SMALLER_CHUNK_SIZE:
+ TRY_AGAIN_WITH_SMALLER_CHUNK_SIZE:
envelope.TotalChunks = (ushort)((dataLeft + (chunkSize - 1)) / chunkSize);
while (dataLeft > 0)
{
@@ -3467,7 +3460,6 @@ namespace System.Diagnostics.Tracing
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;
@@ -3627,7 +3619,7 @@ namespace System.Diagnostics.Tracing
}
#endif
return;
- Error:
+ Error:
manifest.ManifestError(Resources.GetResourceString("EventSource_EnumKindMismatch", staticField.Name, staticField.FieldType.Name, providerEnumKind));
}
@@ -4101,7 +4093,7 @@ namespace System.Diagnostics.Tracing
// 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;
+ private ActivityTracker m_activityTracker;
internal const string s_ActivityStartSuffix = "Start";
internal const string s_ActivityStopSuffix = "Stop";
@@ -4627,7 +4619,6 @@ namespace System.Diagnostics.Tracing
s_CreatingListener = false;
}
}
-
}
// Instance fields
@@ -5019,7 +5010,7 @@ namespace System.Diagnostics.Tracing
{
/// <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; }
+ public EventAttribute(int eventId) { this.EventId = eventId; Level = EventLevel.Informational; 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>
@@ -5035,8 +5026,8 @@ namespace System.Diagnostics.Tracing
}
set
{
- this.m_opcode = value;
- this.m_opcodeSet = true;
+ m_opcode = value;
+ m_opcodeSet = true;
}
}
@@ -5076,7 +5067,7 @@ namespace System.Diagnostics.Tracing
public EventActivityOptions ActivityOptions { get; set; }
#region private
- EventOpcode m_opcode;
+ private EventOpcode m_opcode;
private bool m_opcodeSet;
#endregion
}
@@ -5115,7 +5106,7 @@ namespace System.Diagnostics.Tracing
#if FEATURE_ADVANCED_MANAGED_ETW_CHANNELS
public
#endif
- class EventChannelAttribute : Attribute
+ internal class EventChannelAttribute : Attribute
{
/// <summary>
/// Specified whether the channel is enabled by default
@@ -5155,7 +5146,7 @@ namespace System.Diagnostics.Tracing
#if FEATURE_ADVANCED_MANAGED_ETW_CHANNELS
public
#endif
- enum EventChannelType
+ internal enum EventChannelType
{
/// <summary>The admin channel</summary>
Admin = 1,
@@ -5566,7 +5557,7 @@ namespace System.Diagnostics.Tracing
}
}
- #region private
+ #region private
/// <summary>
/// Creates a new ActivityFilter that is triggered by 'eventId' from 'source' ever
@@ -5735,7 +5726,7 @@ namespace System.Diagnostics.Tracing
ActivityFilter m_next; // We create a linked list of these
Action<Guid> m_myActivityDelegate;
- #endregion
+ #endregion
};
@@ -5860,7 +5851,7 @@ namespace System.Diagnostics.Tracing
public bool IsEqualOrSupersetOf(SessionMask m)
{
- return (this.m_mask | m.m_mask) == this.m_mask;
+ return (m_mask | m.m_mask) == m_mask;
}
public static SessionMask All
@@ -6139,7 +6130,7 @@ namespace System.Diagnostics.Tracing
public ulong[] GetChannelData()
{
- if (this.channelTab == null)
+ if (channelTab == null)
{
return new ulong[0];
}
@@ -6147,7 +6138,7 @@ namespace System.Diagnostics.Tracing
// 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)
+ foreach (var item in channelTab.Keys)
{
if (item > maxkey)
{
@@ -6156,7 +6147,7 @@ namespace System.Diagnostics.Tracing
}
ulong[] channelMask = new ulong[maxkey + 1];
- foreach (var item in this.channelTab)
+ foreach (var item in channelTab)
{
channelMask[item.Key] = item.Value.Keywords;
}
@@ -6328,7 +6319,6 @@ namespace System.Diagnostics.Tracing
private string CreateManifestString()
{
-
#if FEATURE_MANAGED_ETW_CHANNELS
// Write out the channels
if (channelTab != null)
@@ -6396,7 +6386,6 @@ namespace System.Diagnostics.Tracing
// Write out the tasks
if (taskTab != null)
{
-
sb.Append(" <tasks>").AppendLine();
var sortedTasks = new List<int>(taskTab.Keys);
sortedTasks.Sort();
@@ -6840,7 +6829,7 @@ namespace System.Diagnostics.Tracing
}
#if FEATURE_MANAGED_ETW_CHANNELS
- class ChannelInfo
+ private class ChannelInfo
{
public string Name;
public ulong Keywords;
@@ -6848,15 +6837,15 @@ namespace System.Diagnostics.Tracing
}
#endif
- Dictionary<int, string> opcodeTab;
- Dictionary<int, string> taskTab;
+ private Dictionary<int, string> opcodeTab;
+ private Dictionary<int, string> taskTab;
#if FEATURE_MANAGED_ETW_CHANNELS
- Dictionary<int, ChannelInfo> channelTab;
+ private Dictionary<int, ChannelInfo> channelTab;
#endif
- Dictionary<ulong, string> keywordTab;
- Dictionary<string, Type> mapsTab;
+ private Dictionary<ulong, string> keywordTab;
+ private Dictionary<string, Type> mapsTab;
- Dictionary<string, string> stringTab; // Maps unlocalized strings to localized ones
+ private 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
@@ -6865,26 +6854,26 @@ namespace System.Diagnostics.Tracing
// 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
+ private ulong nextChannelKeywordBit = 0x8000000000000000; // available Keyword bit to be used for next channel definition, grows down
+ private 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;
+ private StringBuilder sb; // Holds the provider information.
+ private StringBuilder events; // Holds the events.
+ private StringBuilder templates;
#if FEATURE_MANAGED_ETW_CHANNELS
- string providerName;
+ private 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
+ private ResourceManager resources; // Look up localized strings here.
+ private EventManifestOptions flags;
+ private IList<string> errors; // list of currently encountered errors
+ private 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
+ private string eventName; // Name of the event currently being processed.
+ private int numParams; // keeps track of the number of args the event has.
+ private List<int> byteArrArgIndices; // keeps track of the index of each byte[] argument
#endregion
}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/EventSourceException.cs b/src/mscorlib/src/System/Diagnostics/Eventing/EventSourceException.cs
index 3fc9d545b8..c64c97b4df 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/EventSourceException.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/EventSourceException.cs
@@ -27,7 +27,8 @@ namespace System.Diagnostics.Tracing
/// Initializes a new instance of the EventSourceException class.
/// </summary>
public EventSourceException() :
- base(Resources.GetResourceString("EventSource_ListenerWriteFailure")) { }
+ base(Resources.GetResourceString("EventSource_ListenerWriteFailure"))
+ { }
/// <summary>
/// Initializes a new instance of the EventSourceException class with a specified error message.
@@ -48,6 +49,7 @@ namespace System.Diagnostics.Tracing
#endif
internal EventSourceException(Exception innerException) :
- base(Resources.GetResourceString("EventSource_ListenerWriteFailure"), 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..71c421231e 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/EventSource_CoreCLR.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/EventSource_CoreCLR.cs
@@ -130,10 +130,10 @@ namespace System.Diagnostics.Tracing
{
return Environment.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,7 +209,7 @@ namespace System.Diagnostics.Tracing
return status;
}
}
-
+
internal static class Resources
{
internal static string GetResourceString(string key, params object[] 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
index e090c4f106..7b6491094b 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/StubEnvironment.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/StubEnvironment.cs
@@ -31,7 +31,7 @@ namespace System.Diagnostics.Tracing.Internal
return string.Format(fmt, args);
string sargs = String.Empty;
- foreach(var arg in args)
+ foreach (var arg in args)
{
if (sargs != String.Empty)
sargs += ", ";
@@ -196,7 +196,7 @@ namespace Microsoft.Reflection
String = 18, // Unicode character string
}
#endif
- static class ReflectionExtensions
+ internal static class ReflectionExtensions
{
#if (!ES_BUILD_PCL && !PROJECTN)
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/ArrayTypeInfo.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/ArrayTypeInfo.cs
index 5771354f67..f5abd471a4 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/ArrayTypeInfo.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/ArrayTypeInfo.cs
@@ -27,7 +27,7 @@ namespace System.Diagnostics.Tracing
EventFieldFormat format)
{
collector.BeginBufferedArray();
- this.elementInfo.WriteMetadata(collector, name, format);
+ elementInfo.WriteMetadata(collector, name, format);
collector.EndBufferedArray();
}
@@ -42,7 +42,7 @@ namespace System.Diagnostics.Tracing
count = array.Length;
for (int i = 0; i < array.Length; i++)
{
- this.elementInfo.WriteData(collector, elementInfo.PropertyValueFactory(array.GetValue(i)));
+ elementInfo.WriteData(collector, elementInfo.PropertyValueFactory(array.GetValue(i)));
}
}
@@ -55,7 +55,7 @@ namespace System.Diagnostics.Tracing
var serializedArray = new object[array.Length];
for (int i = 0; i < array.Length; i++)
{
- serializedArray[i] = this.elementInfo.GetData(array.GetValue(i));
+ serializedArray[i] = 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
index 76c01c6c06..eb55c8cf33 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/ConcurrentSet.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/ConcurrentSet.cs
@@ -31,7 +31,7 @@ namespace System.Diagnostics.Tracing
public ItemType TryGet(KeyType key)
{
ItemType item;
- var oldItems = this.items;
+ var oldItems = items;
if (oldItems != null)
{
@@ -69,7 +69,7 @@ namespace System.Diagnostics.Tracing
public ItemType GetOrAdd(ItemType newItem)
{
ItemType item;
- var oldItems = this.items;
+ var oldItems = items;
ItemType[] newItems;
Retry:
@@ -110,7 +110,7 @@ namespace System.Diagnostics.Tracing
Array.Copy(oldItems, lo, newItems, lo + 1, oldLength - lo);
}
- newItems = Interlocked.CompareExchange(ref this.items, newItems, oldItems);
+ newItems = Interlocked.CompareExchange(ref items, newItems, oldItems);
if (oldItems != newItems)
{
oldItems = newItems;
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/DataCollector.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/DataCollector.cs
index 079d7f480b..f3983ed2d9 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/DataCollector.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/DataCollector.cs
@@ -47,14 +47,14 @@ namespace System.Diagnostics.Tracing
GCHandle* pins,
int pinCount)
{
- this.datasStart = datas;
- this.scratchEnd = scratch + scratchSize;
- this.datasEnd = datas + dataCount;
- this.pinsEnd = pins + pinCount;
+ datasStart = datas;
+ scratchEnd = scratch + scratchSize;
+ datasEnd = datas + dataCount;
+ pinsEnd = pins + pinCount;
this.scratch = scratch;
this.datas = datas;
this.pins = pins;
- this.writingScalars = false;
+ writingScalars = false;
}
internal void Disable()
@@ -73,23 +73,23 @@ namespace System.Diagnostics.Tracing
internal EventSource.EventData* Finish()
{
this.ScalarsEnd();
- return this.datas;
+ return datas;
}
internal void AddScalar(void* value, int size)
{
var pb = (byte*)value;
- if (this.bufferNesting == 0)
+ if (bufferNesting == 0)
{
- var scratchOld = this.scratch;
+ var scratchOld = scratch;
var scratchNew = scratchOld + size;
- if (this.scratchEnd < scratchNew)
+ if (scratchEnd < scratchNew)
{
throw new IndexOutOfRangeException(Resources.GetResourceString("EventSource_AddScalarOutOfRange"));
}
this.ScalarsBegin();
- this.scratch = scratchNew;
+ scratch = scratchNew;
for (int i = 0; i != size; i++)
{
@@ -98,12 +98,12 @@ namespace System.Diagnostics.Tracing
}
else
{
- var oldPos = this.bufferPos;
- this.bufferPos = checked(this.bufferPos + size);
+ var oldPos = bufferPos;
+ bufferPos = checked(bufferPos + size);
this.EnsureBuffer();
for (int i = 0; i != size; i++, oldPos++)
{
- this.buffer[oldPos] = pb[i];
+ buffer[oldPos] = pb[i];
}
}
}
@@ -115,7 +115,7 @@ namespace System.Diagnostics.Tracing
size = ushort.MaxValue - 1;
}
- if (this.bufferNesting != 0)
+ if (bufferNesting != 0)
{
this.EnsureBuffer(size + 2);
}
@@ -124,19 +124,19 @@ namespace System.Diagnostics.Tracing
if (size != 0)
{
- if (this.bufferNesting == 0)
+ if (bufferNesting == 0)
{
this.ScalarsEnd();
this.PinArray(value, size);
}
else
{
- var oldPos = this.bufferPos;
- this.bufferPos = checked(this.bufferPos + size);
+ var oldPos = bufferPos;
+ bufferPos = checked(bufferPos + size);
this.EnsureBuffer();
fixed (void* p = value)
{
- Marshal.Copy((IntPtr)p, this.buffer, oldPos, size);
+ Marshal.Copy((IntPtr)p, buffer, oldPos, size);
}
}
}
@@ -155,7 +155,7 @@ namespace System.Diagnostics.Tracing
}
var size = length * itemSize;
- if (this.bufferNesting != 0)
+ if (bufferNesting != 0)
{
this.EnsureBuffer(size + 2);
}
@@ -164,17 +164,17 @@ namespace System.Diagnostics.Tracing
if (length != 0)
{
- if (this.bufferNesting == 0)
+ if (bufferNesting == 0)
{
this.ScalarsEnd();
this.PinArray(value, size);
}
else
{
- var oldPos = this.bufferPos;
- this.bufferPos = checked(this.bufferPos + size);
+ var oldPos = bufferPos;
+ bufferPos = checked(bufferPos + size);
this.EnsureBuffer();
- Buffer.BlockCopy(value, 0, this.buffer, oldPos, size);
+ Buffer.BlockCopy(value, 0, buffer, oldPos, size);
}
}
}
@@ -186,8 +186,8 @@ namespace System.Diagnostics.Tracing
internal int BeginBufferedArray()
{
this.BeginBuffered();
- this.bufferPos += 2; // Reserve space for the array length (filled in by EndEnumerable)
- return this.bufferPos;
+ bufferPos += 2; // Reserve space for the array length (filled in by EndEnumerable)
+ return bufferPos;
}
/// <summary>
@@ -198,8 +198,8 @@ namespace System.Diagnostics.Tracing
internal void EndBufferedArray(int bookmark, int count)
{
this.EnsureBuffer();
- this.buffer[bookmark - 2] = unchecked((byte)count);
- this.buffer[bookmark - 1] = unchecked((byte)(count >> 8));
+ buffer[bookmark - 2] = unchecked((byte)count);
+ buffer[bookmark - 1] = unchecked((byte)(count >> 8));
this.EndBuffered();
}
@@ -209,7 +209,7 @@ namespace System.Diagnostics.Tracing
internal void BeginBuffered()
{
this.ScalarsEnd();
- this.bufferNesting += 1;
+ bufferNesting += 1;
}
/// <summary>
@@ -217,9 +217,9 @@ namespace System.Diagnostics.Tracing
/// </summary>
internal void EndBuffered()
{
- this.bufferNesting -= 1;
+ bufferNesting -= 1;
- if (this.bufferNesting == 0)
+ if (bufferNesting == 0)
{
/*
TODO (perf): consider coalescing adjacent buffered regions into a
@@ -230,16 +230,16 @@ namespace System.Diagnostics.Tracing
*/
this.EnsureBuffer();
- this.PinArray(this.buffer, this.bufferPos);
- this.buffer = null;
- this.bufferPos = 0;
+ this.PinArray(buffer, bufferPos);
+ buffer = null;
+ bufferPos = 0;
}
}
private void EnsureBuffer()
{
- var required = this.bufferPos;
- if (this.buffer == null || this.buffer.Length < required)
+ var required = bufferPos;
+ if (buffer == null || buffer.Length < required)
{
this.GrowBuffer(required);
}
@@ -247,8 +247,8 @@ namespace System.Diagnostics.Tracing
private void EnsureBuffer(int additionalSize)
{
- var required = this.bufferPos + additionalSize;
- if (this.buffer == null || this.buffer.Length < required)
+ var required = bufferPos + additionalSize;
+ if (buffer == null || buffer.Length < required)
{
this.GrowBuffer(required);
}
@@ -256,7 +256,7 @@ namespace System.Diagnostics.Tracing
private void GrowBuffer(int required)
{
- var newSize = this.buffer == null ? 64 : this.buffer.Length;
+ var newSize = buffer == null ? 64 : buffer.Length;
do
{
@@ -264,25 +264,25 @@ namespace System.Diagnostics.Tracing
}
while (newSize < required);
- Array.Resize(ref this.buffer, newSize);
+ Array.Resize(ref buffer, newSize);
}
private void PinArray(object value, int size)
{
- var pinsTemp = this.pins;
- if (this.pinsEnd <= pinsTemp)
+ var pinsTemp = pins;
+ if (pinsEnd <= pinsTemp)
{
throw new IndexOutOfRangeException(Resources.GetResourceString("EventSource_PinArrayOutOfRange"));
}
- var datasTemp = this.datas;
- if (this.datasEnd <= datasTemp)
+ var datasTemp = datas;
+ if (datasEnd <= datasTemp)
{
throw new IndexOutOfRangeException(Resources.GetResourceString("EventSource_DataDescriptorsOutOfRange"));
}
- this.pins = pinsTemp + 1;
- this.datas = datasTemp + 1;
+ pins = pinsTemp + 1;
+ datas = datasTemp + 1;
*pinsTemp = GCHandle.Alloc(value, GCHandleType.Pinned);
datasTemp->m_Ptr = (long)(ulong)(UIntPtr)(void*)pinsTemp->AddrOfPinnedObject();
@@ -291,27 +291,27 @@ namespace System.Diagnostics.Tracing
private void ScalarsBegin()
{
- if (!this.writingScalars)
+ if (!writingScalars)
{
- var datasTemp = this.datas;
- if (this.datasEnd <= datasTemp)
+ var datasTemp = datas;
+ if (datasEnd <= datasTemp)
{
throw new IndexOutOfRangeException(Resources.GetResourceString("EventSource_DataDescriptorsOutOfRange"));
}
- datasTemp->m_Ptr = (long)(ulong)(UIntPtr)this.scratch;
- this.writingScalars = true;
+ datasTemp->m_Ptr = (long)(ulong)(UIntPtr)scratch;
+ writingScalars = true;
}
}
private void ScalarsEnd()
{
- if (this.writingScalars)
+ if (writingScalars)
{
- var datasTemp = this.datas;
- datasTemp->m_Size = checked((int)(this.scratch - (byte*)datasTemp->m_Ptr));
- this.datas = datasTemp + 1;
- this.writingScalars = false;
+ var datasTemp = datas;
+ datasTemp->m_Size = checked((int)(scratch - (byte*)datasTemp->m_Ptr));
+ datas = datasTemp + 1;
+ writingScalars = false;
}
}
}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EnumerableTypeInfo.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EnumerableTypeInfo.cs
index 74a3fa27b2..f8bd90f3bd 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EnumerableTypeInfo.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EnumerableTypeInfo.cs
@@ -28,7 +28,7 @@ namespace System.Diagnostics.Tracing
EventFieldFormat format)
{
collector.BeginBufferedArray();
- this.elementInfo.WriteMetadata(collector, name, format);
+ elementInfo.WriteMetadata(collector, name, format);
collector.EndBufferedArray();
}
@@ -42,7 +42,7 @@ namespace System.Diagnostics.Tracing
{
foreach (var element in enumerable)
{
- this.elementInfo.WriteData(collector, elementInfo.PropertyValueFactory(element));
+ elementInfo.WriteData(collector, elementInfo.PropertyValueFactory(element));
count++;
}
}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventDataAttribute.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventDataAttribute.cs
index cdedf13c64..8707f22bf7 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventDataAttribute.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventDataAttribute.cs
@@ -81,8 +81,8 @@ namespace System.Diagnostics.Tracing
/// </summary>
internal EventLevel Level
{
- get { return this.level; }
- set { this.level = value; }
+ get { return level; }
+ set { level = value; }
}
/// <summary>
@@ -107,8 +107,8 @@ namespace System.Diagnostics.Tracing
/// </summary>
internal EventOpcode Opcode
{
- get { return this.opcode; }
- set { this.opcode = value; }
+ get { return opcode; }
+ set { opcode = value; }
}
/// <summary>
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventPayload.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventPayload.cs
index 5967ad6ab5..568bfeaadd 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventPayload.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventPayload.cs
@@ -25,7 +25,7 @@ namespace System.Diagnostics.Tracing
/// </summary>
internal class EventPayload : IDictionary<string, object>
{
- internal EventPayload(List<string> payloadNames, List<object> payloadValues)
+ internal EventPayload(List<string> payloadNames, List<object> payloadValues)
{
Debug.Assert(payloadNames.Count == payloadValues.Count);
@@ -44,8 +44,8 @@ namespace System.Diagnostics.Tracing
throw new System.ArgumentNullException(nameof(key));
int position = 0;
- foreach(var name in m_names)
- {
+ foreach (var name in m_names)
+ {
if (name == key)
{
return m_values[position];
@@ -102,7 +102,7 @@ namespace System.Diagnostics.Tracing
{
for (int i = 0; i < Keys.Count; i++)
{
- yield return new KeyValuePair<string, object>(this.m_names[i], this.m_values[i]);
+ yield return new KeyValuePair<string, object>(m_names[i], m_values[i]);
}
}
@@ -116,7 +116,7 @@ namespace System.Diagnostics.Tracing
{
throw new System.NotSupportedException();
}
-
+
public bool Remove(string key)
{
throw new System.NotSupportedException();
@@ -126,7 +126,7 @@ namespace System.Diagnostics.Tracing
{
throw new System.NotSupportedException();
}
-
+
public bool TryGetValue(string key, out object value)
{
if (key == null)
@@ -137,7 +137,7 @@ namespace System.Diagnostics.Tracing
{
if (name == key)
{
- value = m_values[position];
+ value = m_values[position];
return true;
}
position++;
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/FieldMetadata.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/FieldMetadata.cs
index 309226b84d..732c78dd6e 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/FieldMetadata.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/FieldMetadata.cs
@@ -117,9 +117,9 @@ namespace System.Diagnostics.Tracing
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);
+ nameSize = Encoding.UTF8.GetByteCount(this.name) + 1;
+ inType = (byte)(coreType | countFlags);
+ outType = (byte)(((int)dataType >> 8) & Statics.OutTypeMask);
this.tags = tags;
this.fixedCount = fixedCount;
this.custom = custom;
@@ -145,20 +145,20 @@ namespace System.Diagnostics.Tracing
if (((int)this.tags & 0xfffffff) != 0)
{
- this.outType |= Statics.OutTypeChainFlag;
+ outType |= Statics.OutTypeChainFlag;
}
- if (this.outType != 0)
+ if (outType != 0)
{
- this.inType |= Statics.InTypeChainFlag;
+ inType |= Statics.InTypeChainFlag;
}
}
public void IncrementStructFieldCount()
{
- this.inType |= Statics.InTypeChainFlag;
- this.outType++;
- if ((this.outType & Statics.OutTypeMask) == 0)
+ inType |= Statics.InTypeChainFlag;
+ outType++;
+ if ((outType & Statics.OutTypeMask) == 0)
{
throw new NotSupportedException(Resources.GetResourceString("EventSource_TooManyFields"));
}
@@ -178,52 +178,52 @@ namespace System.Diagnostics.Tracing
// Write out the null terminated UTF8 encoded name
if (metadata != null)
{
- Encoding.UTF8.GetBytes(this.name, 0, this.name.Length, metadata, pos);
+ Encoding.UTF8.GetBytes(name, 0, name.Length, metadata, pos);
}
- pos += this.nameSize;
+ pos += nameSize;
// Write 1 byte for inType
if (metadata != null)
{
- metadata[pos] = this.inType;
+ metadata[pos] = inType;
}
pos += 1;
// If InTypeChainFlag set, then write out the outType
- if (0 != (this.inType & Statics.InTypeChainFlag))
+ if (0 != (inType & Statics.InTypeChainFlag))
{
if (metadata != null)
{
- metadata[pos] = this.outType;
+ metadata[pos] = outType;
}
pos += 1;
// If OutTypeChainFlag set, then write out tags
- if (0 != (this.outType & Statics.OutTypeChainFlag))
+ if (0 != (outType & Statics.OutTypeChainFlag))
{
- Statics.EncodeTags((int)this.tags, ref pos, metadata);
+ Statics.EncodeTags((int)tags, ref pos, metadata);
}
}
// If InTypeFixedCountFlag set, write out the fixedCount (2 bytes little endian)
- if (0 != (this.inType & Statics.InTypeFixedCountFlag))
+ if (0 != (inType & Statics.InTypeFixedCountFlag))
{
if (metadata != null)
{
- metadata[pos + 0] = unchecked((byte)this.fixedCount);
- metadata[pos + 1] = (byte)(this.fixedCount >> 8);
+ metadata[pos + 0] = unchecked((byte)fixedCount);
+ metadata[pos + 1] = (byte)(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 (Statics.InTypeCustomCountFlag == (inType & Statics.InTypeCountMask) &&
+ fixedCount != 0)
{
if (metadata != null)
{
- Buffer.BlockCopy(this.custom, 0, metadata, pos, this.fixedCount);
+ Buffer.BlockCopy(custom, 0, metadata, pos, fixedCount);
}
- pos += this.fixedCount;
+ pos += fixedCount;
}
}
}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/InvokeTypeInfo.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/InvokeTypeInfo.cs
index 3e5997bc9b..c424108077 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/InvokeTypeInfo.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/InvokeTypeInfo.cs
@@ -35,7 +35,7 @@ namespace System.Diagnostics.Tracing
typeAnalysis.tags)
{
if (typeAnalysis.properties.Length != 0)
- this.properties = typeAnalysis.properties;
+ properties = typeAnalysis.properties;
}
public override void WriteMetadata(
@@ -44,9 +44,9 @@ namespace System.Diagnostics.Tracing
EventFieldFormat format)
{
var groupCollector = collector.AddGroup(name);
- if (this.properties != null)
+ if (properties != null)
{
- foreach (var property in this.properties)
+ foreach (var property in properties)
{
var propertyFormat = EventFieldFormat.Default;
var propertyAttribute = property.fieldAttribute;
@@ -66,9 +66,9 @@ namespace System.Diagnostics.Tracing
public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value)
{
- if (this.properties != null)
+ if (properties != null)
{
- foreach (var property in this.properties)
+ foreach (var property in properties)
{
property.typeInfo.WriteData(collector, property.getter(value));
}
@@ -77,11 +77,11 @@ namespace System.Diagnostics.Tracing
public override object GetData(object value)
{
- if (this.properties != null)
+ if (properties != null)
{
var membersNames = new List<string>();
var memebersValues = new List<object>();
- for (int i = 0; i < this.properties.Length; i++)
+ for (int i = 0; i < properties.Length; i++)
{
var propertyValue = properties[i].propertyInfo.GetValue(value);
membersNames.Add(properties[i].name);
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/NameInfo.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/NameInfo.cs
index 668043ae68..fc55788dae 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/NameInfo.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/NameInfo.cs
@@ -25,7 +25,7 @@ namespace System.Diagnostics.Tracing
/// </summary>
internal static void ReserveEventIDsBelow(int eventId)
{
- for(;;)
+ for (;;)
{
int snapshot = lastIdentity;
int newIdentity = (lastIdentity & ~0xFFFFFF) + eventId;
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/PropertyValue.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/PropertyValue.cs
index 3ea781252f..f95e36da42 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/PropertyValue.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/PropertyValue.cs
@@ -65,9 +65,9 @@ namespace System.Diagnostics.Tracing
}
// Anything not covered by the Scalar union gets stored in this reference.
- readonly object _reference;
- readonly Scalar _scalar;
- readonly int _scalarLength;
+ private readonly object _reference;
+ private readonly Scalar _scalar;
+ private readonly int _scalarLength;
private PropertyValue(object value)
{
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/SimpleTypeInfos.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/SimpleTypeInfos.cs
index 901a0ed1a2..6ecfc29d58 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/SimpleTypeInfos.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/SimpleTypeInfos.cs
@@ -48,15 +48,15 @@ namespace System.Diagnostics.Tracing
/// <summary>
/// Type handler for simple scalar types.
/// </summary>
- sealed class ScalarTypeInfo : TraceLoggingTypeInfo
+ internal sealed class ScalarTypeInfo : TraceLoggingTypeInfo
{
- Func<EventFieldFormat, TraceLoggingDataType, TraceLoggingDataType> formatFunc;
- TraceLoggingDataType nativeFormat;
+ private Func<EventFieldFormat, TraceLoggingDataType, TraceLoggingDataType> formatFunc;
+ private TraceLoggingDataType nativeFormat;
private ScalarTypeInfo(
Type type,
Func<EventFieldFormat, TraceLoggingDataType, TraceLoggingDataType> formatFunc,
- TraceLoggingDataType nativeFormat)
+ TraceLoggingDataType nativeFormat)
: base(type)
{
this.formatFunc = formatFunc;
@@ -96,15 +96,15 @@ namespace System.Diagnostics.Tracing
/// </summary>
internal sealed class ScalarArrayTypeInfo : TraceLoggingTypeInfo
{
- Func<EventFieldFormat, TraceLoggingDataType, TraceLoggingDataType> formatFunc;
- TraceLoggingDataType nativeFormat;
- int elementSize;
+ private Func<EventFieldFormat, TraceLoggingDataType, TraceLoggingDataType> formatFunc;
+ private TraceLoggingDataType nativeFormat;
+ private int elementSize;
private ScalarArrayTypeInfo(
Type type,
Func<EventFieldFormat, TraceLoggingDataType, TraceLoggingDataType> formatFunc,
TraceLoggingDataType nativeFormat,
- int elementSize)
+ int elementSize)
: base(type)
{
this.formatFunc = formatFunc;
@@ -158,14 +158,14 @@ namespace System.Diagnostics.Tracing
{
collector.AddBinary((string)value.ReferenceValue);
}
-
+
public override object GetData(object value)
{
- if(value == null)
+ if (value == null)
{
return "";
}
-
+
return value;
}
}
@@ -271,9 +271,9 @@ namespace System.Diagnostics.Tracing
{
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"));
+ valueInfo = TraceLoggingTypeInfo.GetInstance(typeArgs[0], recursionCheck);
+ hasValueGetter = PropertyValue.GetPropertyGetter(type.GetTypeInfo().GetDeclaredProperty("HasValue"));
+ valueGetter = PropertyValue.GetPropertyGetter(type.GetTypeInfo().GetDeclaredProperty("Value"));
}
public override void WriteMetadata(
@@ -283,7 +283,7 @@ namespace System.Diagnostics.Tracing
{
var group = collector.AddGroup(name);
group.AddScalar("HasValue", TraceLoggingDataType.Boolean8);
- this.valueInfo.WriteMetadata(group, "Value", format);
+ valueInfo.WriteMetadata(group, "Value", format);
}
public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value)
@@ -291,7 +291,7 @@ namespace System.Diagnostics.Tracing
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);
+ valueInfo.WriteData(collector, val);
}
}
}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingEventSource.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingEventSource.cs
index 07a56751ea..2279544695 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingEventSource.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingEventSource.cs
@@ -445,11 +445,11 @@ namespace System.Diagnostics.Tracing
var pins = stackalloc GCHandle[pinCount];
fixed (byte*
- pMetadata0 = this.providerMetadata,
+ pMetadata0 = providerMetadata,
pMetadata1 = nameInfo.nameMetadata,
pMetadata2 = eventTypes.typeMetadata)
{
- descriptors[0].SetMetadata(pMetadata0, this.providerMetadata.Length, 2);
+ descriptors[0].SetMetadata(pMetadata0, providerMetadata.Length, 2);
descriptors[1].SetMetadata(pMetadata1, nameInfo.nameMetadata.Length, 1);
descriptors[2].SetMetadata(pMetadata2, eventTypes.typeMetadata.Length, 1);
@@ -546,11 +546,11 @@ namespace System.Diagnostics.Tracing
var descriptors = stackalloc EventData[eventTypes.dataCount + eventTypes.typeInfos.Length * 2 + 3];
fixed (byte*
- pMetadata0 = this.providerMetadata,
+ pMetadata0 = providerMetadata,
pMetadata1 = nameInfo.nameMetadata,
pMetadata2 = eventTypes.typeMetadata)
{
- descriptors[0].SetMetadata(pMetadata0, this.providerMetadata.Length, 2);
+ descriptors[0].SetMetadata(pMetadata0, providerMetadata.Length, 2);
descriptors[1].SetMetadata(pMetadata1, nameInfo.nameMetadata.Length, 1);
descriptors[2].SetMetadata(pMetadata2, eventTypes.typeMetadata.Length, 1);
int numDescrs = 3;
@@ -622,11 +622,11 @@ namespace System.Diagnostics.Tracing
var pins = stackalloc GCHandle[pinCount];
fixed (byte*
- pMetadata0 = this.providerMetadata,
+ pMetadata0 = providerMetadata,
pMetadata1 = nameInfo.nameMetadata,
pMetadata2 = eventTypes.typeMetadata)
{
- descriptors[0].SetMetadata(pMetadata0, this.providerMetadata.Length, 2);
+ descriptors[0].SetMetadata(pMetadata0, providerMetadata.Length, 2);
descriptors[1].SetMetadata(pMetadata1, nameInfo.nameMetadata.Length, 1);
descriptors[2].SetMetadata(pMetadata2, eventTypes.typeMetadata.Length, 1);
#endif // FEATURE_MANAGED_ETW
@@ -684,7 +684,6 @@ namespace System.Diagnostics.Tracing
var eventData = (EventPayload)(eventTypes.typeInfos[0].GetData(data));
WriteToAllListeners(eventName, ref descriptor, nameInfo.tags, pActivityId, eventData);
}
-
}
catch (Exception ex)
{
@@ -715,9 +714,9 @@ namespace System.Diagnostics.Tracing
{
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_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.
@@ -852,7 +851,7 @@ namespace System.Diagnostics.Tracing
{
return (c - 'A' + 10);
}
-
+
throw new ArgumentException(Resources.GetResourceString("BadHexDigit", c), "traits");
}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingEventTypes.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingEventTypes.cs
index c2239671bb..6f4a1dc71c 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingEventTypes.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingEventTypes.cs
@@ -199,10 +199,10 @@ namespace System.Diagnostics.Tracing
internal NameInfo GetNameInfo(string name, EventTags tags)
{
- var ret = this.nameInfos.TryGet(new KeyValuePair<string, EventTags>(name, tags));
+ var ret = nameInfos.TryGet(new KeyValuePair<string, EventTags>(name, tags));
if (ret == null)
{
- ret = this.nameInfos.GetOrAdd(new NameInfo(name, tags, this.typeMetadata.Length));
+ ret = nameInfos.GetOrAdd(new NameInfo(name, tags, this.typeMetadata.Length));
}
return ret;
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingMetadataCollector.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingMetadataCollector.cs
index 41225c8626..583efce973 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingMetadataCollector.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingMetadataCollector.cs
@@ -27,7 +27,7 @@ namespace System.Diagnostics.Tracing
/// </summary>
internal TraceLoggingMetadataCollector()
{
- this.impl = new Impl();
+ impl = new Impl();
}
/// <summary>
@@ -39,8 +39,8 @@ namespace System.Diagnostics.Tracing
TraceLoggingMetadataCollector other,
FieldMetadata group)
{
- this.impl = other.impl;
- this.currentGroup = group;
+ impl = other.impl;
+ currentGroup = group;
}
/// <summary>
@@ -55,22 +55,22 @@ namespace System.Diagnostics.Tracing
internal int ScratchSize
{
- get { return this.impl.scratchSize; }
+ get { return impl.scratchSize; }
}
internal int DataCount
{
- get { return this.impl.dataCount; }
+ get { return impl.dataCount; }
}
internal int PinCount
{
- get { return this.impl.pinCount; }
+ get { return impl.pinCount; }
}
private bool BeginningBufferedArray
{
- get { return this.bufferedArrayFieldCount == 0; }
+ get { return bufferedArrayFieldCount == 0; }
}
/// <summary>
@@ -159,7 +159,7 @@ namespace System.Diagnostics.Tracing
throw new ArgumentOutOfRangeException(nameof(type));
}
- this.impl.AddScalar(size);
+ impl.AddScalar(size);
this.AddField(new FieldMetadata(name, type, this.Tags, this.BeginningBufferedArray));
}
@@ -186,8 +186,8 @@ namespace System.Diagnostics.Tracing
throw new ArgumentOutOfRangeException(nameof(type));
}
- this.impl.AddScalar(2);
- this.impl.AddNonscalar();
+ impl.AddScalar(2);
+ impl.AddNonscalar();
this.AddField(new FieldMetadata(name, type, this.Tags, this.BeginningBufferedArray));
}
@@ -235,31 +235,31 @@ namespace System.Diagnostics.Tracing
throw new NotSupportedException(Resources.GetResourceString("EventSource_NotSupportedNestedArraysEnums"));
}
- this.impl.AddScalar(2);
- this.impl.AddNonscalar();
+ impl.AddScalar(2);
+ impl.AddNonscalar();
this.AddField(new FieldMetadata(name, type, this.Tags, true));
}
public void BeginBufferedArray()
{
- if (this.bufferedArrayFieldCount >= 0)
+ if (bufferedArrayFieldCount >= 0)
{
throw new NotSupportedException(Resources.GetResourceString("EventSource_NotSupportedNestedArraysEnums"));
}
- this.bufferedArrayFieldCount = 0;
- this.impl.BeginBuffered();
+ bufferedArrayFieldCount = 0;
+ impl.BeginBuffered();
}
public void EndBufferedArray()
{
- if (this.bufferedArrayFieldCount != 1)
+ if (bufferedArrayFieldCount != 1)
{
throw new InvalidOperationException(Resources.GetResourceString("EventSource_IncorrentlyAuthoredTypeInfo"));
}
- this.bufferedArrayFieldCount = int.MinValue;
- this.impl.EndBuffered();
+ bufferedArrayFieldCount = int.MinValue;
+ impl.EndBuffered();
}
/// <summary>
@@ -277,8 +277,8 @@ namespace System.Diagnostics.Tracing
throw new NotSupportedException(Resources.GetResourceString("EventSource_NotSupportedCustomSerializedData"));
}
- this.impl.AddScalar(2);
- this.impl.AddNonscalar();
+ impl.AddScalar(2);
+ impl.AddNonscalar();
this.AddField(new FieldMetadata(
name,
type,
@@ -288,21 +288,21 @@ namespace System.Diagnostics.Tracing
internal byte[] GetMetadata()
{
- var size = this.impl.Encode(null);
+ var size = impl.Encode(null);
var metadata = new byte[size];
- this.impl.Encode(metadata);
+ impl.Encode(metadata);
return metadata;
}
private void AddField(FieldMetadata fieldMetadata)
{
this.Tags = EventFieldTags.None;
- this.bufferedArrayFieldCount++;
- this.impl.fields.Add(fieldMetadata);
+ bufferedArrayFieldCount++;
+ impl.fields.Add(fieldMetadata);
- if (this.currentGroup != null)
+ if (currentGroup != null)
{
- this.currentGroup.IncrementStructFieldCount();
+ currentGroup.IncrementStructFieldCount();
}
}
@@ -317,23 +317,23 @@ namespace System.Diagnostics.Tracing
public void AddScalar(int size)
{
- if (this.bufferNesting == 0)
+ if (bufferNesting == 0)
{
- if (!this.scalar)
+ if (!scalar)
{
this.dataCount = checked((sbyte)(this.dataCount + 1));
}
- this.scalar = true;
+ scalar = true;
this.scratchSize = checked((short)(this.scratchSize + size));
}
}
public void AddNonscalar()
{
- if (this.bufferNesting == 0)
+ if (bufferNesting == 0)
{
- this.scalar = false;
+ scalar = false;
this.pinCount = checked((sbyte)(this.pinCount + 1));
this.dataCount = checked((sbyte)(this.dataCount + 1));
}
@@ -341,17 +341,17 @@ namespace System.Diagnostics.Tracing
public void BeginBuffered()
{
- if (this.bufferNesting == 0)
+ if (bufferNesting == 0)
{
this.AddNonscalar();
}
- this.bufferNesting++;
+ bufferNesting++;
}
public void EndBuffered()
{
- this.bufferNesting--;
+ bufferNesting--;
}
public int Encode(byte[] metadata)
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingTypeInfo.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingTypeInfo.cs
index d68e106b0b..48198319e3 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingTypeInfo.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingTypeInfo.cs
@@ -41,9 +41,9 @@ namespace System.Diagnostics.Tracing
Contract.EndContractBlock();
- this.name = dataType.Name;
+ name = dataType.Name;
this.dataType = dataType;
- this.propertyValueFactory = PropertyValue.GetFactory(dataType);
+ propertyValueFactory = PropertyValue.GetFactory(dataType);
}
internal TraceLoggingTypeInfo(
@@ -74,7 +74,7 @@ namespace System.Diagnostics.Tracing
this.opcode = opcode;
this.tags = tags;
this.dataType = dataType;
- this.propertyValueFactory = PropertyValue.GetFactory(dataType);
+ propertyValueFactory = PropertyValue.GetFactory(dataType);
}
/// <summary>
@@ -84,7 +84,7 @@ namespace System.Diagnostics.Tracing
/// </summary>
public string Name
{
- get { return this.name; }
+ get { return name; }
}
/// <summary>
@@ -94,7 +94,7 @@ namespace System.Diagnostics.Tracing
/// </summary>
public EventLevel Level
{
- get { return this.level; }
+ get { return level; }
}
/// <summary>
@@ -104,7 +104,7 @@ namespace System.Diagnostics.Tracing
/// </summary>
public EventOpcode Opcode
{
- get { return this.opcode; }
+ get { return opcode; }
}
/// <summary>
@@ -112,7 +112,7 @@ namespace System.Diagnostics.Tracing
/// </summary>
public EventKeywords Keywords
{
- get { return this.keywords; }
+ get { return keywords; }
}
/// <summary>
@@ -120,17 +120,17 @@ namespace System.Diagnostics.Tracing
/// </summary>
public EventTags Tags
{
- get { return this.tags; }
+ get { return tags; }
}
internal Type DataType
{
- get { return this.dataType; }
+ get { return dataType; }
}
internal Func<object, PropertyValue> PropertyValueFactory
{
- get { return this.propertyValueFactory; }
+ get { return propertyValueFactory; }
}
/// <summary>
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/Winmeta.cs b/src/mscorlib/src/System/Diagnostics/Eventing/Winmeta.cs
index c93e745173..091166c172 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/Winmeta.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/Winmeta.cs
@@ -142,7 +142,6 @@ namespace System.Diagnostics.Tracing
Analytic = 18,
/// <summary>The debug channel</summary>
Debug = 19,
-
};
/// <summary>
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..85f4f4f646 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.
@@ -40,23 +41,23 @@ namespace System.Diagnostics {
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..40c2526ad1 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),
+ throw new ArgumentOutOfRangeException(nameof(skipFrames),
Environment.GetResourceString("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),
+ throw new ArgumentOutOfRangeException(nameof(skipFrames),
Environment.GetResourceString("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),
+ throw new ArgumentOutOfRangeException(nameof(skipFrames),
Environment.GetResourceString("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),
+ throw new ArgumentOutOfRangeException(nameof(skipFrames),
Environment.GetResourceString("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.
//
@@ -390,22 +389,21 @@ namespace System.Diagnostics {
//
[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 +411,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 +457,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 +486,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 +511,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 +533,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 +548,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");
}
-
+
bool fFirstFrame = true;
StringBuilder sb = new StringBuilder(255);
for (int iFrameIndex = 0; iFrameIndex < m_iNumOfFrames; iFrameIndex++)
@@ -569,11 +567,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 +590,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 +601,8 @@ namespace System.Diagnostics {
sb.Append(typars[k].Name);
k++;
- }
- sb.Append(']');
+ }
+ sb.Append(']');
}
ParameterInfo[] pi = null;
@@ -635,7 +633,7 @@ namespace System.Diagnostics {
sb.Append(typeName);
sb.Append(' ');
sb.Append(pi[j].Name);
- }
+ }
sb.Append(')');
}
@@ -645,7 +643,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 +658,7 @@ namespace System.Diagnostics {
displayFilenames = false;
}
- if (fileName != null)
+ if (fileName != null)
{
// tack on " in c:\tmp\MyFile.cs:line 5"
sb.Append(' ');
@@ -676,10 +674,10 @@ namespace System.Diagnostics {
}
}
- 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 +691,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..19e062964c 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,18 @@ 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.
- //
+
+
+ // 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 +36,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 +51,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 +76,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 +84,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"));
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 +113,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/DllNotFoundException.cs b/src/mscorlib/src/System/DllNotFoundException.cs
index 43bb57fec2..63b263e9dd 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")) {
+ public class DllNotFoundException : TypeLoadException
+ {
+ public DllNotFoundException()
+ : base(Environment.GetResourceString("Arg_DllNotFoundException"))
+ {
SetErrorCode(__HResults.COR_E_DLLNOTFOUND);
}
-
- public DllNotFoundException(String message)
- : base(message) {
+
+ public DllNotFoundException(String message)
+ : base(message)
+ {
SetErrorCode(__HResults.COR_E_DLLNOTFOUND);
}
-
- public DllNotFoundException(String message, Exception inner)
- : base(message, inner) {
+
+ public DllNotFoundException(String message, Exception inner)
+ : base(message, inner)
+ {
SetErrorCode(__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..d7319b6c48 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;
@@ -115,7 +123,8 @@ namespace System {
throw new ArgumentException(Environment.GetResourceString("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,98 @@ 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) {
+ char IConvertible.ToChar(IFormatProvider provider)
+ {
throw new InvalidCastException(Environment.GetResourceString("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) {
+ DateTime IConvertible.ToDateTime(IFormatProvider provider)
+ {
throw new InvalidCastException(Environment.GetResourceString("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/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/Enum.cs b/src/mscorlib/src/System/Enum.cs
index 97cfdf1b23..0f01052f31 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
@@ -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);
@@ -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.
@@ -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;
}
@@ -407,7 +407,8 @@ namespace System
if (!enumType.IsEnum)
throw new ArgumentException(Environment.GetResourceString("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:
@@ -635,7 +637,7 @@ namespace System
return enumType.IsEnumDefined(value);
}
-
+
public static String Format(Type enumType, Object value, String format)
{
if (enumType == null)
@@ -661,8 +663,8 @@ 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()));
@@ -674,7 +676,8 @@ namespace System
return ((Enum)value).ToString(format);
}
// The value must be of the same type as the Underlying type of the Enum
- else if (valueType != underlyingType) {
+ else if (valueType != underlyingType)
+ {
throw new ArgumentException(Environment.GetResourceString("Arg_EnumFormatUnderlyingTypeAndObjectMustBeSameType", valueType.ToString(), underlyingType.ToString()));
}
if (format.Length != 1)
@@ -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,21 +916,22 @@ namespace System
Type thisType = this.GetType();
Type targetType = target.GetType();
- throw new ArgumentException(Environment.GetResourceString("Arg_EnumAndObjectMustBeSameType",
+ throw new ArgumentException(Environment.GetResourceString("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"));
}
}
#endregion
#region Public Methods
- public String ToString(String format) {
+ public String ToString(String format)
+ {
char formatCh;
if (format == null || format.Length == 0)
formatCh = 'G';
@@ -957,12 +961,14 @@ 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())) {
+
+ if (!this.GetType().IsEquivalentTo(flag.GetType()))
+ {
throw new ArgumentException(Environment.GetResourceString("Argument_EnumTypeDoesNotMatch", flag.GetType(), this.GetType()));
}
@@ -1002,96 +1008,96 @@ namespace System
}
/// <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"));
}
/// <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)
diff --git a/src/mscorlib/src/System/Environment.cs b/src/mscorlib/src/System/Environment.cs
index e39b38c928..4f1971c9e7 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;
@@ -40,18 +42,19 @@ namespace System {
public 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;
internal sealed class ResourceHelper
{
- internal ResourceHelper(String name) {
+ internal ResourceHelper(String name)
+ {
m_name = name;
}
@@ -61,7 +64,7 @@ namespace System {
// 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
@@ -69,9 +72,11 @@ namespace System {
// Is this thread currently doing infinite resource lookups?
private int infinitelyRecursingCount;
-
- internal String GetResourceString(String key) {
- if (key == null || key.Length == 0) {
+
+ 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]";
}
@@ -87,7 +92,7 @@ namespace System {
// 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
@@ -169,13 +174,16 @@ namespace System {
private static volatile ResourceHelper m_resHelper; // Doesn't need to be initialized as they're zero-init.
- private const int MaxMachineNameLength = 256;
+ 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 +200,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 +257,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,14 +289,16 @@ namespace System {
throw new ArgumentNullException(nameof(name));
Contract.EndContractBlock();
- if (name.Length == 0) {
+ if (name.Length == 0)
+ {
return name;
}
- if (AppDomain.IsAppXModel() && !AppDomain.IsAppXDesignMode()) {
+ 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;
+ return name;
}
int currentSize = 100;
@@ -314,8 +331,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,9 +347,10 @@ namespace System {
return blob.ToString();
}
- public static String MachineName {
- get {
-
+ public static String MachineName
+ {
+ get
+ {
// UWP Debug scenarios
if (AppDomain.IsAppXModel() && !AppDomain.IsAppXDesignMode())
{
@@ -353,8 +372,10 @@ namespace System {
[SuppressUnmanagedCodeSecurity]
private static extern Int32 GetProcessorCount();
- public static int ProcessorCount {
- get {
+ public static int ProcessorCount
+ {
+ get
+ {
return GetProcessorCount();
}
}
@@ -381,7 +402,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,8 +471,10 @@ 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
return "\r\n";
@@ -461,21 +484,22 @@ namespace System {
}
}
-
+
/*===================================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);
+
+ return new Version(4, 0, 30319, 42000);
}
}
@@ -485,17 +509,20 @@ namespace System {
**Arguments:
**Exceptions:
==============================================================================*/
- internal static OperatingSystem OSVersion {
- get {
+ 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.
-
+ 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)) {
+ 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"));
@@ -506,7 +533,7 @@ namespace System {
PlatformID id = PlatformID.Win32NT;
#endif // PLATFORM_UNIX
- Version v = new Version(osvi.MajorVersion, osvi.MinorVersion, osvi.BuildNumber, (osviEx.ServicePackMajor << 16) |osviEx.ServicePackMinor);
+ 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");
@@ -515,15 +542,19 @@ namespace System {
}
- internal static bool IsWindows8OrAbove {
- get {
+ internal static bool IsWindows8OrAbove
+ {
+ get
+ {
return true;
}
}
#if FEATURE_COMINTEROP
- internal static bool IsWinRTSupported {
- get {
+ internal static bool IsWinRTSupported
+ {
+ get
+ {
return true;
}
}
@@ -531,10 +562,10 @@ namespace System {
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern bool GetVersion(Microsoft.Win32.Win32Native.OSVERSIONINFO osVer);
+ internal static extern bool GetVersion(Microsoft.Win32.Win32Native.OSVERSIONINFO osVer);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern bool GetVersionEx(Microsoft.Win32.Win32Native.OSVERSIONINFOEX osVer);
+ internal static extern bool GetVersionEx(Microsoft.Win32.Win32Native.OSVERSIONINFOEX osVer);
/*==================================StackTrace==================================
@@ -543,8 +574,10 @@ namespace System {
**Arguments:
**Exceptions:
==============================================================================*/
- public static String StackTrace {
- get {
+ public static String StackTrace
+ {
+ get
+ {
Contract.Ensures(Contract.Result<String>() != null);
return GetStackTrace(null, true);
@@ -564,28 +597,31 @@ namespace System {
st = new StackTrace(e, needFileInfo);
// Do no include a trailing newline for backwards compatibility
- return st.ToString( System.Diagnostics.StackTrace.TraceFormat.Normal );
+ return st.ToString(System.Diagnostics.StackTrace.TraceFormat.Normal);
}
- private static void InitResourceHelper() {
+ 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 {
-
+ try
+ {
Monitor.Enter(Environment.InternalSyncObject, ref tookLock);
- if (m_resHelper == null) {
+ if (m_resHelper == null)
+ {
ResourceHelper rh = new ResourceHelper(System.CoreLib.Name);
System.Threading.Thread.MemoryBarrier();
- m_resHelper =rh;
+ m_resHelper = rh;
}
}
- finally {
+ finally
+ {
if (tookLock)
Monitor.Exit(Environment.InternalSyncObject);
}
@@ -596,14 +632,16 @@ namespace System {
// 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 static String GetResourceStringLocal(String key)
+ {
if (m_resHelper == null)
InitResourceHelper();
return m_resHelper.GetResourceString(key);
}
- internal static String GetResourceString(String key) {
+ internal static String GetResourceString(String key)
+ {
return GetResourceStringLocal(key);
}
@@ -650,14 +688,16 @@ namespace System {
return String.Format(CultureInfo.CurrentCulture, rs, values);
}
- public static extern bool HasShutdownStarted {
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ public static extern bool HasShutdownStarted
+ {
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
internal static bool UserInteractive
{
- get {
+ get
+ {
return true;
}
}
@@ -680,11 +720,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()
{
diff --git a/src/mscorlib/src/System/Exception.cs b/src/mscorlib/src/System/Exception.cs
index a166c1ab0a..6036063ca6 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)
+ if (_className == null || HResult == 0)
throw new SerializationException(Environment.GetResourceString("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 {
+ }
+ 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();
@@ -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 +
+ if (_innerException != null)
+ {
+ s = s + " ---> " + _innerException.ToString(needFileLineInfo, needMessage) + Environment.NewLine +
" " + Environment.GetResourceString("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(); }
+ remove { throw new PlatformNotSupportedException(); }
}
- 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,10 +859,10 @@ 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);
}
diff --git a/src/mscorlib/src/System/GC.cs b/src/mscorlib/src/System/GC.cs
index fd09ef7984..347bc3f511 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,15 +108,18 @@ 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),
+
+ public static void AddMemoryPressure(long bytesAllocated)
+ {
+ if (bytesAllocated <= 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(bytesAllocated),
Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
}
- if( (4 == IntPtr.Size) && (bytesAllocated > Int32.MaxValue) ) {
- throw new ArgumentOutOfRangeException("pressure",
+ if ((4 == IntPtr.Size) && (bytesAllocated > Int32.MaxValue))
+ {
+ throw new ArgumentOutOfRangeException("pressure",
Environment.GetResourceString("ArgumentOutOfRange_MustBeNonNegInt32"));
}
Contract.EndContractBlock();
@@ -123,19 +127,22 @@ namespace System {
_AddMemoryPressure((ulong)bytesAllocated);
}
- public static void RemoveMemoryPressure (long bytesAllocated) {
- if( bytesAllocated <= 0) {
- throw new ArgumentOutOfRangeException(nameof(bytesAllocated),
+ public static void RemoveMemoryPressure(long bytesAllocated)
+ {
+ if (bytesAllocated <= 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(bytesAllocated),
Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
}
- if( (4 == IntPtr.Size) && (bytesAllocated > Int32.MaxValue) ) {
- throw new ArgumentOutOfRangeException(nameof(bytesAllocated),
+ if ((4 == IntPtr.Size) && (bytesAllocated > Int32.MaxValue))
+ {
+ throw new ArgumentOutOfRangeException(nameof(bytesAllocated),
Environment.GetResourceString("ArgumentOutOfRange_MustBeNonNegInt32"));
}
Contract.EndContractBlock();
- _RemoveMemoryPressure((ulong) bytesAllocated);
+ _RemoveMemoryPressure((ulong)bytesAllocated);
}
@@ -144,33 +151,35 @@ 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"));
}
@@ -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"));
}
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,23 +369,23 @@ 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,
+ Environment.GetResourceString("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,
+ Environment.GetResourceString("ArgumentOutOfRange_Bounds_Lower_Upper"),
+ 1,
99));
-}
+ }
if (!_RegisterForFullGCNotification(maxGenerationThreshold, largeObjectHeapThreshold))
{
@@ -409,7 +426,7 @@ namespace System {
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..9a3d8c42ae 100644
--- a/src/mscorlib/src/System/Globalization/Calendar.cs
+++ b/src/mscorlib/src/System/Globalization/Calendar.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.Globalization {
- using System;
- using System.Runtime.CompilerServices;
- using System.Globalization;
- using System.Runtime.Versioning;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
+using System;
+using System.Runtime.CompilerServices;
+using System.Globalization;
+using System.Runtime.Versioning;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+
+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.
@@ -33,62 +34,61 @@ namespace System.Globalization {
[Serializable]
public abstract 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 int DaysTo10000 = DaysPer400Years * 25 - 366;
- internal const long MaxMillis = (long)DaysTo10000 * MillisPerDay;
+ 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 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;
@@ -118,15 +118,18 @@ namespace System.Globalization {
- 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 {
+ internal virtual int ID
+ {
+ get
+ {
return (-1);
}
}
@@ -172,10 +175,10 @@ namespace System.Globalization {
public virtual Object Clone()
{
object o = MemberwiseClone();
- ((Calendar) o).SetReadOnlyState(false);
+ ((Calendar)o).SetReadOnlyState(false);
return (o);
}
-
+
////////////////////////////////////////////////////////////////////////
//
// ReadOnly
@@ -184,15 +187,15 @@ 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);
}
@@ -219,10 +222,13 @@ 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) {
+ if (m_currentEraValue == -1)
+ {
Debug.Assert(BaseCalendarID > 0, "[Calendar.CurrentEraValue] Expected ID > 0");
m_currentEraValue = CalendarData.GetCalendarData(BaseCalendarID).iCurrentEra;
}
@@ -236,8 +242,10 @@ 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));
@@ -245,7 +253,8 @@ namespace System.Globalization {
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
@@ -272,7 +281,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 +294,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 +306,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 +319,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 +352,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 +362,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 +440,8 @@ namespace System.Globalization {
============================================================================*/
- public abstract int[] Eras {
+ public abstract int[] Eras
+ {
get;
}
@@ -434,7 +450,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 +459,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 +468,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 +494,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 +536,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 +548,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 +598,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 +666,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",
DayOfWeek.Sunday, DayOfWeek.Saturday));
}
Contract.EndContractBlock();
- switch (rule) {
+ switch (rule)
+ {
case CalendarWeekRule.FirstDay:
return (GetFirstDayWeekOfYear(time, (int)firstDayOfWeek));
case CalendarWeekRule.FirstFullWeek:
@@ -660,7 +685,6 @@ namespace System.Globalization {
throw new ArgumentOutOfRangeException(
nameof(rule), Environment.GetResourceString("ArgumentOutOfRange_Range",
CalendarWeekRule.FirstDay, CalendarWeekRule.FirstFourDayWeek));
-
}
// Returns the year part of the specified DateTime. The returned value is an
@@ -688,7 +712,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 +742,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 +769,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 +779,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 +835,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"));
}
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,9 +856,10 @@ 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(
@@ -847,6 +881,5 @@ namespace System.Globalization {
}
return (twoDigitYearMax);
}
-
}
}
diff --git a/src/mscorlib/src/System/Globalization/CalendarAlgorithmType.cs b/src/mscorlib/src/System/Globalization/CalendarAlgorithmType.cs
index 33b5035a8d..9c09c58a97 100644
--- a/src/mscorlib/src/System/Globalization/CalendarAlgorithmType.cs
+++ b/src/mscorlib/src/System/Globalization/CalendarAlgorithmType.cs
@@ -2,10 +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;
- public enum CalendarAlgorithmType {
+namespace System.Globalization
+{
+ 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.
diff --git a/src/mscorlib/src/System/Globalization/CalendarData.cs b/src/mscorlib/src/System/Globalization/CalendarData.cs
index ed961b3a53..b683db1e28 100644
--- a/src/mscorlib/src/System/Globalization/CalendarData.cs
+++ b/src/mscorlib/src/System/Globalization/CalendarData.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.
+
+using System;
+using System.Runtime.InteropServices;
+using System.Runtime.CompilerServices;
+using System.Runtime.Versioning;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+
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.
@@ -34,39 +35,39 @@ namespace System.Globalization
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 readonly CalendarData Invariant = CreateInvariant();
// Private constructor
- private CalendarData() {}
+ private CalendarData() { }
// Invariant factory
private static CalendarData CreateInvariant()
@@ -77,34 +78,34 @@ namespace System.Globalization
// 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;
return invariant;
}
@@ -120,27 +121,27 @@ namespace System.Globalization
this.bUseUserOverrides = bUseUserOverrides;
if (!nativeGetCalendarData(this, localeName, calendarId))
{
- Debug.Assert(false, "[CalendarData] nativeGetCalendarData call isn't expected to fail for calendar " + calendarId + " locale " +localeName);
-
+ Debug.Assert(false, "[CalendarData] nativeGetCalendarData 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
}
@@ -196,7 +197,7 @@ namespace System.Globalization
// Note that the saEraNames only include "A.D." We don't have localized names for other calendars available from windows
switch ((CalendarId)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]))
@@ -205,7 +206,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." };
@@ -235,7 +236,7 @@ namespace System.Globalization
case CalendarId.GREGORIAN_ME_FRENCH:
this.saEraNames = new String[] { "ap. J.-C." };
break;
-
+
case CalendarId.TAIWAN:
if (CultureInfo.IsTaiwanSku)
{
@@ -250,11 +251,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();
@@ -279,7 +280,7 @@ namespace System.Globalization
// Note that the saAbbrevEraNames only include "AD" We don't have localized names for other calendars available from windows
switch ((CalendarId)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
if (this.saAbbrevEraNames == null || this.saAbbrevEraNames.Length == 0 || String.IsNullOrEmpty(this.saAbbrevEraNames[0]))
@@ -288,11 +289,11 @@ 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:
+ case CalendarId.JULIAN:
this.saAbbrevEraNames = new String[] { "AD" };
- break;
+ break;
case CalendarId.JAPAN:
case CalendarId.JAPANESELUNISOLAR:
this.saAbbrevEraNames = JapaneseCalendar.AbbrevEraNames();
@@ -314,12 +315,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:
@@ -347,7 +348,7 @@ namespace System.Globalization
// Get a culture name
String culture = CalendarIdToCultureName(calendarId);
-
+
// Return our calendar
return CultureInfo.GetCultureInfo(culture).m_cultureData.GetCalendar(calendarId);
}
@@ -360,18 +361,18 @@ namespace System.Globalization
// note that this doesn't handle the new calendars (lunisolar, etc)
switch (calendarId)
{
- case Calendar.CAL_GREGORIAN_US:
+ case Calendar.CAL_GREGORIAN_US:
return "fa-IR"; // "fa-IR" Iran
-
+
case Calendar.CAL_JAPAN:
return "ja-JP"; // "ja-JP" Japan
case Calendar.CAL_TAIWAN: // zh-TW Taiwan
return "zh-TW";
-
- case Calendar.CAL_KOREA:
+
+ case Calendar.CAL_KOREA:
return "ko-KR"; // "ko-KR" Korea
-
+
case Calendar.CAL_HIJRI:
case Calendar.CAL_GREGORIAN_ARABIC:
case Calendar.CAL_UMALQURA:
@@ -379,17 +380,17 @@ namespace System.Globalization
case Calendar.CAL_THAI:
return "th-TH"; // "th-TH" Thailand
-
+
case Calendar.CAL_HEBREW:
return "he-IL"; // "he-IL" Israel
-
+
case Calendar.CAL_GREGORIAN_ME_FRENCH:
return "ar-DZ"; // "ar-DZ" Algeria
-
+
case Calendar.CAL_GREGORIAN_XLIT_ENGLISH:
case Calendar.CAL_GREGORIAN_XLIT_FRENCH:
return "ar-IQ"; // "ar-IQ"; Iraq
-
+
default:
// Default to gregorian en-US
break;
@@ -398,7 +399,7 @@ namespace System.Globalization
return "en-US";
}
-
+
// Get native two digit year max
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int nativeGetTwoDigitYearMax(int calID);
@@ -410,7 +411,6 @@ namespace System.Globalization
// 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
index fa2a6429f1..4013ce7237 100644
--- a/src/mscorlib/src/System/Globalization/CalendarWeekRule.cs
+++ b/src/mscorlib/src/System/Globalization/CalendarWeekRule.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.
-namespace System.Globalization {
- using System;
-
+using System;
+namespace System.Globalization
+{
[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
diff --git a/src/mscorlib/src/System/Globalization/CalendricalCalculationsHelper.cs b/src/mscorlib/src/System/Globalization/CalendricalCalculationsHelper.cs
index 1113cd58ba..9f1c086f64 100644
--- a/src/mscorlib/src/System/Globalization/CalendricalCalculationsHelper.cs
+++ b/src/mscorlib/src/System/Globalization/CalendricalCalculationsHelper.cs
@@ -2,57 +2,57 @@
// The .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.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;
+ private const double FullCircleOfArc = 360.0; // 360.0;
+ private const int HalfCircleOfArc = 180;
+ private const double TwelveHours = 0.5; // half a day
+ private 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)
+ private const double MeanSpeedOfSun = MeanTropicalYearInDays / FullCircleOfArc;
+ private const double LongitudeSpring = 0.0;
+ private const double TwoDegreesAfterSpring = 2.0;
+ private const int SecondsPerDay = 24 * 60 * 60; // 24 hours * 60 minutes * 60 seconds
+
+ private const int DaysInUniformLengthCentury = 36525;
+ private const int SecondsPerMinute = 60;
+ private const int MinutesPerDegree = 60;
+
+ private static long StartOf1810 = GetNumberOfDays(new DateTime(1810, 1, 1));
+ private static long StartOf1900Century = GetNumberOfDays(new DateTime(1900, 1, 1));
+
+ private static double[] Coefficients1900to1987 = new double[] { -0.00002, 0.000297, 0.025184, -0.181133, 0.553040, -0.861938, 0.677066, -0.212591 };
+ private 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 };
+ private static double[] Coefficients1700to1799 = new double[] { 8.118780842, -0.005092142, 0.003336121, -0.0000266484 };
+ private static double[] Coefficients1620to1699 = new double[] { 196.58333, -4.0675, 0.0219167 };
+ private static double[] LambdaCoefficients = new double[] { 280.46645, 36000.76983, 0.0003032 };
+ private static double[] AnomalyCoefficients = new double[] { 357.52910, 35999.05030, -0.0001559, -0.00000048 };
+ private static double[] EccentricityCoefficients = new double[] { 0.016708617, -0.000042037, -0.0000001236 };
+ private 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) };
+ private static double[] CoefficientsA = new double[] { 124.90, -1934.134, 0.002063 };
+ private static double[] CoefficientsB = new double[] { 201.11, 72001.5377, 0.00057 };
+
+ private static double RadiansFromDegrees(double degree)
{
return degree * Math.PI / 180;
}
- static double SinOfDegree(double degree)
+ private static double SinOfDegree(double degree)
{
return Math.Sin(RadiansFromDegrees(degree));
}
- static double CosOfDegree(double degree)
+ private static double CosOfDegree(double degree)
{
return Math.Cos(RadiansFromDegrees(degree));
}
- static double TanOfDegree(double degree)
+ private static double TanOfDegree(double degree)
{
return Math.Tan(RadiansFromDegrees(degree));
}
@@ -62,7 +62,7 @@ namespace System.Globalization
return ((seconds / SecondsPerMinute + minutes) / MinutesPerDegree) + degrees;
}
- static double Obliquity(double julianCenturies)
+ private static double Obliquity(double julianCenturies)
{
return PolynomialSum(Coefficients, julianCenturies);
}
@@ -72,12 +72,12 @@ namespace System.Globalization
return date.Ticks / GregorianCalendar.TicksPerDay;
}
- static int GetGregorianYear(double numberOfDays)
+ private static int GetGregorianYear(double numberOfDays)
{
return new DateTime(Math.Min((long)(Math.Floor(numberOfDays) * GregorianCalendar.TicksPerDay), DateTime.MaxValue.Ticks)).Year;
}
- enum CorrectionAlgorithm
+ private enum CorrectionAlgorithm
{
Default,
Year1988to2019,
@@ -87,7 +87,7 @@ namespace System.Globalization
Year1620to1699
}
- struct EphemerisCorrectionAlgorithmMap
+ private struct EphemerisCorrectionAlgorithmMap
{
public EphemerisCorrectionAlgorithmMap(int year, CorrectionAlgorithm algorithm)
{
@@ -99,7 +99,7 @@ namespace System.Globalization
internal CorrectionAlgorithm _algorithm;
};
- static EphemerisCorrectionAlgorithmMap[] EphemerisCorrectionTable = new EphemerisCorrectionAlgorithmMap[]
+ private static EphemerisCorrectionAlgorithmMap[] EphemerisCorrectionTable = new EphemerisCorrectionAlgorithmMap[]
{
// lowest year that starts algorithm, algorithm to use
new EphemerisCorrectionAlgorithmMap(2020, CorrectionAlgorithm.Default),
@@ -111,13 +111,13 @@ namespace System.Globalization
new EphemerisCorrectionAlgorithmMap(int.MinValue, CorrectionAlgorithm.Default) // default must be last
};
- static double Reminder(double divisor, double dividend)
+ private static double Reminder(double divisor, double dividend)
{
double whole = Math.Floor(divisor / dividend);
return divisor - (dividend * whole);
}
- static double NormalizeLongitude(double longitude)
+ private static double NormalizeLongitude(double longitude)
{
longitude = Reminder(longitude, FullCircleOfArc);
if (longitude < 0)
@@ -132,11 +132,11 @@ namespace System.Globalization
return longitude / FullCircleOfArc;
}
- static double PolynomialSum(double[] coefficients, double indeterminate)
+ private static double PolynomialSum(double[] coefficients, double indeterminate)
{
double sum = coefficients[0];
double indeterminateRaised = 1;
- for (int i=1; i<coefficients.Length; i++)
+ for (int i = 1; i < coefficients.Length; i++)
{
indeterminateRaised *= indeterminate;
sum += (coefficients[i] * indeterminateRaised);
@@ -145,14 +145,14 @@ namespace System.Globalization
return sum;
}
- static double CenturiesFrom1900(int gregorianYear)
+ private static double CenturiesFrom1900(int gregorianYear)
{
long july1stOfYear = GetNumberOfDays(new DateTime(gregorianYear, 7, 1));
- return (double) (july1stOfYear - StartOf1900Century) / DaysInUniformLengthCentury;
+ 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)
+ private static double DefaultEphemerisCorrection(int gregorianYear)
{
Debug.Assert(gregorianYear < 1620 || 2020 <= gregorianYear);
long january1stOfYear = GetNumberOfDays(new DateTime(gregorianYear, 1, 1));
@@ -161,34 +161,34 @@ namespace System.Globalization
return ((Math.Pow(x, 2) / 41048480) - 15) / SecondsPerDay;
}
- static double EphemerisCorrection1988to2019(int gregorianYear)
+ private static double EphemerisCorrection1988to2019(int gregorianYear)
{
Debug.Assert(1988 <= gregorianYear && gregorianYear <= 2019);
return (double)(gregorianYear - 1933) / SecondsPerDay;
}
- static double EphemerisCorrection1900to1987(int gregorianYear)
+ private static double EphemerisCorrection1900to1987(int gregorianYear)
{
Debug.Assert(1900 <= gregorianYear && gregorianYear <= 1987);
double centuriesFrom1900 = CenturiesFrom1900(gregorianYear);
return PolynomialSum(Coefficients1900to1987, centuriesFrom1900);
}
- static double EphemerisCorrection1800to1899(int gregorianYear)
+ private static double EphemerisCorrection1800to1899(int gregorianYear)
{
Debug.Assert(1800 <= gregorianYear && gregorianYear <= 1899);
double centuriesFrom1900 = CenturiesFrom1900(gregorianYear);
return PolynomialSum(Coefficients1800to1899, centuriesFrom1900);
}
- static double EphemerisCorrection1700to1799(int gregorianYear)
+ private 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)
+ private static double EphemerisCorrection1620to1699(int gregorianYear)
{
Debug.Assert(1620 <= gregorianYear && gregorianYear <= 1699);
double yearsSince1600 = gregorianYear - 1600;
@@ -196,7 +196,7 @@ namespace System.Globalization
}
// ephemeris-correction: correction to account for the slowing down of the rotation of the earth
- static double EphemerisCorrection(double time)
+ private static double EphemerisCorrection(double time)
{
int year = GetGregorianYear(time);
foreach (EphemerisCorrectionAlgorithmMap map in EphemerisCorrectionTable)
@@ -227,12 +227,12 @@ namespace System.Globalization
return (dynamicalMoment - Noon2000Jan01) / DaysInUniformLengthCentury;
}
- static bool IsNegative(double value)
+ private static bool IsNegative(double value)
{
return Math.Sign(value) == -1;
}
- static double CopySign(double value, double sign)
+ private static double CopySign(double value, double sign)
{
return (IsNegative(value) == IsNegative(sign)) ? value : -value;
}
@@ -243,7 +243,7 @@ namespace System.Globalization
// 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)
+ private static double EquationOfTime(double time)
{
double julianCenturies = JulianCenturies(time);
double lambda = PolynomialSum(LambdaCoefficients, julianCenturies);
@@ -267,7 +267,7 @@ namespace System.Globalization
return CopySign(Math.Min(Math.Abs(equation), TwelveHours), equation);
}
- static double AsLocalTime(double apparentMidday, double longitude)
+ private 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);
@@ -277,10 +277,10 @@ namespace System.Globalization
// midday
static public double Midday(double date, double longitude)
{
- return AsLocalTime(date+TwelveHours, longitude) - AsDayFraction(longitude);
+ return AsLocalTime(date + TwelveHours, longitude) - AsDayFraction(longitude);
}
- static double InitLongitude(double longitude)
+ private static double InitLongitude(double longitude)
{
return NormalizeLongitude(longitude + HalfCircleOfArc) - HalfCircleOfArc;
}
@@ -291,12 +291,12 @@ namespace System.Globalization
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)
+ private static double PeriodicTerm(double julianCenturies, int x, double y, double z)
{
return x * SinOfDegree(y + z * julianCenturies);
}
- static double SumLongSequenceOfPeriodicTerms(double julianCenturies)
+ private static double SumLongSequenceOfPeriodicTerms(double julianCenturies)
{
double sum = 0.0;
sum += PeriodicTerm(julianCenturies, 403406, 270.54861, 0.9287892);
@@ -351,12 +351,12 @@ namespace System.Globalization
return sum;
}
- static double Aberration(double julianCenturies)
+ private static double Aberration(double julianCenturies)
{
return (0.0000974 * CosOfDegree(177.63 + (35999.01848 * julianCenturies))) - 0.005575;
}
- static double Nutation(double julianCenturies)
+ private static double Nutation(double julianCenturies)
{
double a = PolynomialSum(CoefficientsA, julianCenturies);
double b = PolynomialSum(CoefficientsB, julianCenturies);
@@ -379,7 +379,7 @@ namespace System.Globalization
return (longitude < 0) ? (longitude + FullCircleOfArc) : longitude;
}
- static double EstimatePrior(double longitude, double time)
+ private static double EstimatePrior(double longitude, double time)
{
double timeSunLastAtLongitude = time - (MeanSpeedOfSun * AsSeason(InitLongitude(Compute(time) - longitude)));
double longitudeErrorDelta = InitLongitude(Compute(timeSunLastAtLongitude) - longitude);
@@ -391,15 +391,15 @@ namespace System.Globalization
// 1/1/0001 is absolute date 1.
internal static long PersianNewYearOnOrBefore(long numberOfDays)
{
- double date = (double) numberOfDays;
+ double date = (double)numberOfDays;
double approx = EstimatePrior(LongitudeSpring, MiddayAtPersianObservationSite(date));
- long lowerBoundNewYearDay = (long) Math.Floor(approx) - 1;
+ 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 midday = MiddayAtPersianObservationSite((double)day);
double l = Compute(midday);
if ((LongitudeSpring <= l) && (l <= TwoDegreesAfterSpring))
{
diff --git a/src/mscorlib/src/System/Globalization/CharUnicodeInfo.cs b/src/mscorlib/src/System/Globalization/CharUnicodeInfo.cs
index 2822b418ef..860b847d36 100644
--- a/src/mscorlib/src/System/Globalization/CharUnicodeInfo.cs
+++ b/src/mscorlib/src/System/Globalization/CharUnicodeInfo.cs
@@ -12,8 +12,8 @@
//
////////////////////////////////////////////////////////////////////////////
-namespace System.Globalization {
-
+namespace System.Globalization
+{
//This class has only static members and therefore doesn't need to be serialized.
using System;
@@ -36,34 +36,34 @@ 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();
+ private 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;
+ private unsafe static ushort* s_pCategoryLevel1Index;
+ private 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;
+ private 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;
+ private 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;
+ private 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.
@@ -75,7 +75,8 @@ namespace System.Globalization {
//
// 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 {
+ internal unsafe struct UnicodeDataHeader
+ {
[FieldOffset(0)]
internal char TableName; // WCHAR[16]
[FieldOffset(0x20)]
@@ -90,14 +91,14 @@ namespace System.Globalization {
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 {
+ [StructLayout(LayoutKind.Sequential, Pack = 2)]
+ internal struct DigitValues
+ {
internal sbyte decimalDigit;
internal sbyte digit;
}
@@ -107,19 +108,19 @@ namespace System.Globalization {
//use. We allocate this once in the class initializer and then we don't need to worry
//about it again.
//
- unsafe static bool InitTable() {
-
+ private 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);
+ 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);
+ 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;
}
@@ -137,14 +138,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);
}
@@ -175,16 +180,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 +219,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 +235,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):
@@ -240,7 +251,8 @@ namespace System.Globalization {
//
// 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 unsafe static 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];
@@ -254,7 +266,8 @@ namespace System.Globalization {
// 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) {
+ if (((long)pSourcePtr % 8) != 0)
+ {
// We are not aligned in 8-byte boundary. Do a copy.
double ret;
byte* retPtr = (byte*)&ret;
@@ -272,7 +285,8 @@ namespace System.Globalization {
//
// 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 unsafe static DigitValues* 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];
@@ -285,11 +299,13 @@ namespace System.Globalization {
return &(s_pDigitValues[pBytePtr[(ch & 0x000f)]]);
}
- internal unsafe static sbyte InternalGetDecimalDigitValue(int ch) {
+ internal unsafe static sbyte InternalGetDecimalDigitValue(int ch)
+ {
return (InternalGetDigitValues(ch)->decimalDigit);
}
- internal unsafe static sbyte InternalGetDigitValue(int ch) {
+ internal unsafe static sbyte InternalGetDigitValue(int ch)
+ {
return (InternalGetDigitValues(ch)->digit);
}
@@ -310,21 +326,24 @@ 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) {
+ if (index < 0 || index >= s.Length)
+ {
throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
Contract.EndContractBlock();
return (InternalGetNumericValue(InternalConvertToUtf32(s, index)));
-
}
////////////////////////////////////////////////////////////////////////
@@ -345,16 +364,20 @@ namespace System.Globalization {
////////////////////////////////////////////////////////////////////////
- public static int GetDecimalDigitValue(char ch) {
+ public static int GetDecimalDigitValue(char ch)
+ {
return (InternalGetDecimalDigitValue(ch));
}
- 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) {
+ if (index < 0 || index >= s.Length)
+ {
throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
Contract.EndContractBlock();
@@ -382,16 +405,20 @@ namespace System.Globalization {
////////////////////////////////////////////////////////////////////////
- public static int GetDigitValue(char ch) {
+ public static int GetDigitValue(char ch)
+ {
return (InternalGetDigitValue(ch));
}
- 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) {
+ if (index < 0 || index >= s.Length)
+ {
throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
Contract.EndContractBlock();
@@ -400,21 +427,23 @@ namespace System.Globalization {
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 unsafe static UnicodeCategory InternalGetUnicodeCategory(int ch)
+ {
return ((UnicodeCategory)InternalGetCategoryValue(ch, UNICODE_CATEGORY_OFFSET));
}
@@ -432,7 +461,8 @@ namespace System.Globalization {
//
////////////////////////////////////////////////////////////////////////
- internal unsafe static byte InternalGetCategoryValue(int ch, int offset) {
+ internal unsafe static 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];
@@ -451,14 +481,16 @@ namespace System.Globalization {
return (uc);
}
-// internal static BidiCategory GetBidiCategory(char ch) {
-// return ((BidiCategory)InternalGetCategoryValue(c, BIDI_CATEGORY_OFFSET));
-// }
+ // internal static BidiCategory GetBidiCategory(char ch) {
+ // return ((BidiCategory)InternalGetCategoryValue(c, BIDI_CATEGORY_OFFSET));
+ // }
- internal static BidiCategory GetBidiCategory(String s, int index) {
- if (s==null)
+ internal static BidiCategory GetBidiCategory(String s, int index)
+ {
+ 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();
@@ -478,7 +510,8 @@ 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");
@@ -492,15 +525,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/ChineseLunisolarCalendar.cs b/src/mscorlib/src/System/Globalization/ChineseLunisolarCalendar.cs
index 374ed0dcfa..260b435be1 100644
--- a/src/mscorlib/src/System/Globalization/ChineseLunisolarCalendar.cs
+++ b/src/mscorlib/src/System/Globalization/ChineseLunisolarCalendar.cs
@@ -2,27 +2,27 @@
// 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;
+using System;
+using System.Diagnostics.Contracts;
+namespace System.Globalization
+{
////////////////////////////////////////////////////////////////////////////
//
// Notes about ChineseLunisolarCalendar
//
////////////////////////////////////////////////////////////////////////////
- /*
- ** Calendar support range:
- ** Calendar Minimum Maximum
- ** ========== ========== ==========
- ** Gregorian 1901/02/19 2101/01/28
- ** ChineseLunisolar 1901/01/01 2100/12/29
- */
+ /*
+ ** 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 {
-
-
+ public class ChineseLunisolarCalendar : EastAsianLunisolarCalendar
+ {
//
// The era value for the current era.
//
@@ -44,7 +44,8 @@ namespace System.Globalization {
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 {
+ public override DateTime MinSupportedDateTime
+ {
get
{
return (minDate);
@@ -52,7 +53,8 @@ namespace System.Globalization {
}
- public override DateTime MaxSupportedDateTime {
+ public override DateTime MaxSupportedDateTime
+ {
get
{
return (maxDate);
@@ -69,7 +71,7 @@ namespace System.Globalization {
}
- static readonly int [,] yinfo =
+ private 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
@@ -275,64 +277,75 @@ namespace System.Globalization {
*/};
- internal override int MinCalendarYear {
+ internal override int MinCalendarYear
+ {
get
{
return (MIN_LUNISOLAR_YEAR);
}
}
- internal override int MaxCalendarYear {
+ internal override int MaxCalendarYear
+ {
get
{
return (MAX_LUNISOLAR_YEAR);
}
}
- internal override DateTime MinDate {
+ internal override DateTime MinDate
+ {
get
{
return (minDate);
}
}
- internal override DateTime MaxDate {
+ internal override DateTime MaxDate
+ {
get
{
return (maxDate);
}
}
- internal override EraInfo[] CalEraInfo {
+ internal override EraInfo[] CalEraInfo
+ {
get
{
return (null);
}
}
- internal override int GetYearInfo(int LunarYear, int Index) {
- if ((LunarYear < MIN_LUNISOLAR_YEAR) || (LunarYear > MAX_LUNISOLAR_YEAR)) {
+ 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 ));
+ 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) {
+ internal override int GetYear(int year, DateTime time)
+ {
return year;
}
- internal override int GetGregorianYear(int year, int era) {
- if (era != CurrentEra && era != ChineseEra) {
+ 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) {
+ if (year < MIN_LUNISOLAR_YEAR || year > MAX_LUNISOLAR_YEAR)
+ {
throw new ArgumentOutOfRangeException(
nameof(year),
String.Format(
@@ -365,32 +378,40 @@ namespace System.Globalization {
// Construct an instance of ChineseLunisolar calendar.
- public ChineseLunisolarCalendar() {
+ public ChineseLunisolarCalendar()
+ {
}
- public override int GetEra(DateTime time) {
+ public override int GetEra(DateTime time)
+ {
CheckTicksRange(time.Ticks);
return (ChineseEra);
}
- internal override int ID {
- get {
+ internal override int ID
+ {
+ get
+ {
return (CAL_CHINESELUNISOLAR);
}
}
- internal override int BaseCalendarID {
- get {
+ 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});
+ public override int[] Eras
+ {
+ get
+ {
+ return (new int[] { ChineseEra });
}
}
}
diff --git a/src/mscorlib/src/System/Globalization/CompareInfo.cs b/src/mscorlib/src/System/Globalization/CompareInfo.cs
index dac7b0bf4e..49ae7c22d4 100644
--- a/src/mscorlib/src/System/Globalization/CompareInfo.cs
+++ b/src/mscorlib/src/System/Globalization/CompareInfo.cs
@@ -12,8 +12,8 @@
//
////////////////////////////////////////////////////////////////////////////
-namespace System.Globalization {
-
+namespace System.Globalization
+{
//
// We pass all of the sorting calls to the native side, preferrably to the OS to do
// the actual work.
@@ -42,19 +42,19 @@ namespace System.Globalization {
//
-[Serializable]
+ [Serializable]
[Flags]
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.
+ 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,
@@ -90,7 +90,7 @@ namespace System.Globalization {
[OptionalField(VersionAdded = 2)]
private String m_name; // The name used to construct this CompareInfo
- [NonSerialized]
+ [NonSerialized]
private String m_sortName; // The name that defines our behavior
[NonSerialized]
@@ -109,12 +109,12 @@ namespace System.Globalization {
// identifier.
internal CompareInfo(CultureInfo culture)
{
- this.m_name = culture.m_name;
- this.m_sortName = culture.SortName;
+ m_name = culture.m_name;
+ m_sortName = culture.SortName;
IntPtr handleOrigin;
- this.m_dataHandle = InternalInitSortHandle(m_sortName, out handleOrigin);
- this.m_handleOrigin = handleOrigin;
+ m_dataHandle = InternalInitSortHandle(m_sortName, out handleOrigin);
+ m_handleOrigin = handleOrigin;
}
/*=================================GetCompareInfo==========================
@@ -130,12 +130,15 @@ namespace System.Globalization {
============================================================================*/
#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) {
+ if (assembly != typeof(Object).Module.Assembly)
+ {
throw new ArgumentException(Environment.GetResourceString("Argument_OnlyMscorlib"));
}
Contract.EndContractBlock();
@@ -157,13 +160,16 @@ namespace System.Globalization {
** 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) {
+ if (assembly != typeof(Object).Module.Assembly)
+ {
throw new ArgumentException(Environment.GetResourceString("Argument_OnlyMscorlib"));
}
@@ -214,19 +220,23 @@ namespace System.Globalization {
return CultureInfo.GetCultureInfo(name).CompareInfo;
}
- public static bool IsSortable(char ch) {
- return(IsSortable(ch.ToString()));
+ public static bool IsSortable(char ch)
+ {
+ return (IsSortable(ch.ToString()));
}
- public static bool IsSortable(String text) {
- if (text == null) {
+ public static bool IsSortable(String text)
+ {
+ if (text == null)
+ {
// A null param is invalid here.
throw new ArgumentNullException(nameof(text));
}
- if (0 == text.Length) {
+ if (0 == text.Length)
+ {
// A zero length string is not invalid, but it is also not sortable.
- return(false);
+ return (false);
}
CompareInfo c = CultureInfo.InvariantCulture.CompareInfo;
@@ -235,43 +245,42 @@ namespace System.Globalization {
}
-#region Serialization
+ #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.
+ [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;
+ m_name = null;
}
private void OnDeserialized()
{
CultureInfo ci;
// If we didn't have a name, use the LCID
- if (this.m_name == null)
+ if (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;
+ ci = CultureInfo.GetCultureInfo(culture);
+ m_name = ci.m_name;
+ m_sortName = ci.SortName;
#endif
}
else
{
ci = CultureInfo.GetCultureInfo(m_name);
- this.m_sortName = ci.SortName;
+ m_sortName = ci.SortName;
}
IntPtr handleOrigin;
- this.m_dataHandle = InternalInitSortHandle(m_sortName, out handleOrigin);
- this.m_handleOrigin = handleOrigin;
-
+ m_dataHandle = InternalInitSortHandle(m_sortName, out handleOrigin);
+ m_handleOrigin = handleOrigin;
}
[OnDeserialized]
@@ -295,7 +304,7 @@ namespace System.Globalization {
OnDeserialized();
}
-#endregion Serialization
+ #endregion Serialization
///////////////////////////----- Name -----/////////////////////////////////
@@ -321,18 +330,18 @@ namespace System.Globalization {
}
// 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_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 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]
@@ -346,15 +355,15 @@ namespace System.Globalization {
// 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; }
+ 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; }
+ if (options == CompareOptions.Ordinal) { nativeCompareFlags = COMPARE_OPTIONS_ORDINAL; }
Debug.Assert(((options & ~(CompareOptions.IgnoreCase |
CompareOptions.IgnoreKanaType |
@@ -387,8 +396,8 @@ namespace System.Globalization {
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);
@@ -400,9 +409,9 @@ namespace System.Globalization {
if (options != CompareOptions.Ordinal)
{
throw new ArgumentException(Environment.GetResourceString("Argument_CompareOptionOrdinal"), nameof(options));
- }
+ }
return String.CompareOrdinal(string1, string2);
- }
+ }
if ((options & ValidCompareMaskOffFlags) != 0)
{
@@ -411,13 +420,16 @@ namespace System.Globalization {
//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
}
@@ -446,8 +458,8 @@ namespace System.Globalization {
public unsafe 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);
}
@@ -461,9 +473,9 @@ namespace System.Globalization {
{
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);
}
@@ -517,9 +529,9 @@ namespace System.Globalization {
{
return string.CompareOrdinalHelper(string1, offset1, length1, string2, offset2, length2);
}
- return InternalCompareString(this.m_dataHandle, this.m_handleOrigin, this.m_sortName,
- string1, offset1, length1,
- string2, offset2, length2,
+ return InternalCompareString(m_dataHandle, m_handleOrigin, m_sortName,
+ string1, offset1, length1,
+ string2, offset2, length2,
GetNativeCompareFlags(options));
}
@@ -535,7 +547,8 @@ namespace System.Globalization {
public unsafe 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"));
}
@@ -557,7 +570,8 @@ namespace System.Globalization {
return source.StartsWith(prefix, StringComparison.Ordinal);
}
- if ((options & ValidIndexMaskOffFlags) != 0) {
+ if ((options & ValidIndexMaskOffFlags) != 0)
+ {
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), nameof(options));
}
@@ -565,7 +579,7 @@ namespace System.Globalization {
// 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,
+ 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,
null) > -1);
@@ -589,7 +603,8 @@ namespace System.Globalization {
public unsafe 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"));
}
@@ -601,22 +616,25 @@ namespace System.Globalization {
return (true);
}
- if (options == CompareOptions.OrdinalIgnoreCase) {
+ 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) {
+ if ((options & ValidIndexMaskOffFlags) != 0)
+ {
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,
+ 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, null) >= 0;
}
@@ -643,7 +661,7 @@ namespace System.Globalization {
public unsafe virtual int IndexOf(String source, char value)
{
- if (source==null)
+ if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
@@ -653,7 +671,7 @@ namespace System.Globalization {
public unsafe virtual int IndexOf(String source, String value)
{
- if (source==null)
+ if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
@@ -663,7 +681,7 @@ namespace System.Globalization {
public unsafe virtual int IndexOf(String source, char value, CompareOptions options)
{
- if (source==null)
+ if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
@@ -673,7 +691,7 @@ namespace System.Globalization {
public unsafe virtual int IndexOf(String source, String value, CompareOptions options)
{
- if (source==null)
+ if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
@@ -758,7 +776,7 @@ namespace System.Globalization {
// 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,
+ 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, null);
}
@@ -788,7 +806,7 @@ namespace System.Globalization {
{
if (value.Length == 0)
{
- if(matchLengthPtr != null)
+ if (matchLengthPtr != null)
*matchLengthPtr = 0;
return 0;
}
@@ -808,7 +826,7 @@ namespace System.Globalization {
int index = source.IndexOf(value, startIndex, count, StringComparison.OrdinalIgnoreCase);
if (index != -1)
{
- if(matchLengthPtr != null)
+ if (matchLengthPtr != null)
*matchLengthPtr = value.Length;
}
return index;
@@ -843,7 +861,7 @@ namespace System.Globalization {
public unsafe virtual int LastIndexOf(String source, char value)
{
- if (source==null)
+ if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
@@ -855,7 +873,7 @@ namespace System.Globalization {
public virtual int LastIndexOf(String source, String value)
{
- if (source==null)
+ if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
@@ -867,7 +885,7 @@ namespace System.Globalization {
public virtual int LastIndexOf(String source, char value, CompareOptions options)
{
- if (source==null)
+ if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
@@ -878,7 +896,7 @@ namespace System.Globalization {
public unsafe virtual int LastIndexOf(String source, String value, CompareOptions options)
{
- if (source==null)
+ if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
@@ -927,7 +945,7 @@ namespace System.Globalization {
public unsafe 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();
@@ -966,7 +984,7 @@ namespace System.Globalization {
// 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,
+ 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, null);
}
@@ -1020,7 +1038,7 @@ namespace System.Globalization {
// 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,
+ 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, null);
}
@@ -1046,7 +1064,7 @@ namespace System.Globalization {
private SortKey CreateSortKey(String source, CompareOptions options)
{
- if (source==null) { throw new ArgumentNullException(nameof(source)); }
+ if (source == null) { throw new ArgumentNullException(nameof(source)); }
Contract.EndContractBlock();
// Mask used to check if we have the right flags.
@@ -1087,7 +1105,7 @@ namespace System.Globalization {
if (keyData == null)
{
// Make an appropriate byte array
- keyData = new byte[length];
+ keyData = new byte[length];
// Fill up the array
length = InternalGetSortKey(m_dataHandle, m_handleOrigin, m_sortName, flags, source, source.Length, keyData, keyData.Length);
@@ -1204,7 +1222,7 @@ namespace System.Globalization {
//
// Parameter validation
//
- if(null == source)
+ if (null == source)
{
throw new ArgumentNullException(nameof(source));
}
@@ -1215,14 +1233,14 @@ namespace System.Globalization {
}
Contract.EndContractBlock();
- if(0 == source.Length)
+ if (0 == source.Length)
{
- return(0);
+ return (0);
}
//
////////////////////////////////////////////////////////////////////////
- return (InternalGetGlobalizedHashCode(m_dataHandle, m_handleOrigin, this.m_sortName, source, source.Length, GetNativeCompareFlags(options), forceRandomizedHashing, additionalEntropy));
+ return (InternalGetGlobalizedHashCode(m_dataHandle, m_handleOrigin, m_sortName, source, source.Length, GetNativeCompareFlags(options), forceRandomizedHashing, additionalEntropy));
}
////////////////////////////////////////////////////////////////////////
@@ -1262,7 +1280,7 @@ namespace System.Globalization {
{
get
{
- if(m_SortVersion == null)
+ if (m_SortVersion == null)
{
Win32Native.NlsVersionInfoEx v = new Win32Native.NlsVersionInfoEx();
v.dwNLSVersionInfoSize = Marshal.SizeOf(typeof(Win32Native.NlsVersionInfoEx));
@@ -1273,7 +1291,7 @@ namespace System.Globalization {
return m_SortVersion;
}
}
-
+
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
diff --git a/src/mscorlib/src/System/Globalization/CultureData.cs b/src/mscorlib/src/System/Globalization/CultureData.cs
index a93b7d43bb..10ea239bf6 100644
--- a/src/mscorlib/src/System/Globalization/CultureData.cs
+++ b/src/mscorlib/src/System/Globalization/CultureData.cs
@@ -4,7 +4,6 @@
namespace System.Globalization
{
-
using System;
using System.Collections;
using System.Collections.Generic;
@@ -61,7 +60,7 @@ namespace System.Globalization
[FriendAccessAllowed]
internal class CultureData
{
- const int undef = -1;
+ private const int undef = -1;
// Override flag
private String sRealName; // Name you passed in (ie: en-US, en, or de-DE_phoneb)
@@ -162,12 +161,12 @@ namespace System.Globalization
private int iDefaultEbcdicCodePage = undef; // default EBCDIC code page
// These are desktop only, not coreclr
- private int iLanguage; // locale ID (0409) - NO sort information
+ 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 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)
@@ -184,142 +183,142 @@ namespace System.Globalization
//Using a property so we avoid creating the dictionary untill we need it
private static Dictionary<string, string> 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;
- }
+ { "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;
}
}
@@ -330,132 +329,132 @@ namespace System.Globalization
//
// We need an invariant instance, which we build hard-coded
/////////////////////////////////////////////////////////////////////////
- internal static CultureData Invariant
+ internal static CultureData Invariant
{
- get
+ 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
+ // 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;
}
return s_Invariant;
@@ -826,17 +825,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 this.sRealName to be populated by COMNlsInfo::nativeInitCultureData 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 +844,7 @@ namespace System.Globalization
{
get
{
- return this.bUseOverrides;
+ return bUseOverrides;
}
}
@@ -856,11 +855,11 @@ namespace System.Globalization
{
// 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 +868,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 = DoGetLocaleInfo(sRealName, LOCALE_SPARENT);
}
- return this.sParent;
+ return sParent;
}
}
@@ -883,31 +882,31 @@ namespace System.Globalization
{
get
{
- if (this.sLocalizedDisplayName == null)
+ if (sLocalizedDisplayName == null)
{
// 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))
{
- this.sLocalizedDisplayName = DoGetLocaleInfo(LOCALE_SLOCALIZEDDISPLAYNAME);
+ sLocalizedDisplayName = DoGetLocaleInfo(LOCALE_SLOCALIZEDDISPLAYNAME);
}
- if (String.IsNullOrEmpty(this.sLocalizedDisplayName))
+ if (String.IsNullOrEmpty(sLocalizedDisplayName))
{
- this.sLocalizedDisplayName = this.SNATIVEDISPLAYNAME;
+ sLocalizedDisplayName = this.SNATIVEDISPLAYNAME;
}
}
}
}
- return this.sLocalizedDisplayName;
+ return sLocalizedDisplayName;
}
}
@@ -916,19 +915,19 @@ 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;
}
else
{
- this.sEnglishDisplayName = DoGetLocaleInfo(LOCALE_SENGLISHDISPLAYNAME);
+ sEnglishDisplayName = DoGetLocaleInfo(LOCALE_SENGLISHDISPLAYNAME);
// 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)"
@@ -936,19 +935,19 @@ namespace System.Globalization
if (this.SENGLISHLANGUAGE.EndsWith(')'))
{
// "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,26 +956,26 @@ 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;
}
else
{
- this.sNativeDisplayName = DoGetLocaleInfo(LOCALE_SNATIVEDISPLAYNAME);
+ sNativeDisplayName = DoGetLocaleInfo(LOCALE_SNATIVEDISPLAYNAME);
// 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;
}
}
@@ -986,8 +985,8 @@ namespace System.Globalization
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;
+ Debug.Assert(sSpecificCulture != null, "[CultureData.SSPECIFICCULTURE] Expected this.sSpecificCulture to be populated by COMNlsInfo::nativeInitCultureData already");
+ return sSpecificCulture;
}
}
@@ -1000,11 +999,11 @@ namespace System.Globalization
{
get
{
- if (this.sISO639Language == null)
+ if (sISO639Language == null)
{
- this.sISO639Language = DoGetLocaleInfo(LOCALE_SISO639LANGNAME);
+ sISO639Language = DoGetLocaleInfo(LOCALE_SISO639LANGNAME);
}
- return this.sISO639Language;
+ return sISO639Language;
}
}
@@ -1013,11 +1012,11 @@ namespace System.Globalization
{
get
{
- if (this.sISO639Language2 == null)
+ if (sISO639Language2 == null)
{
- this.sISO639Language2 = DoGetLocaleInfo(LOCALE_SISO639LANGNAME2);
+ sISO639Language2 = DoGetLocaleInfo(LOCALE_SISO639LANGNAME2);
}
- return this.sISO639Language2;
+ return sISO639Language2;
}
}
@@ -1026,11 +1025,11 @@ namespace System.Globalization
{
get
{
- if (this.sAbbrevLang == null)
+ if (sAbbrevLang == null)
{
- this.sAbbrevLang = DoGetLocaleInfo(LOCALE_SABBREVLANGNAME);
+ sAbbrevLang = DoGetLocaleInfo(LOCALE_SABBREVLANGNAME);
}
- return this.sAbbrevLang;
+ return sAbbrevLang;
}
}
@@ -1040,20 +1039,20 @@ namespace System.Globalization
{
get
{
- if (this.sLocalizedLanguage == null)
+ if (sLocalizedLanguage == null)
{
if (CultureInfo.UserDefaultUICulture.Name.Equals(Thread.CurrentThread.CurrentUICulture.Name))
{
- this.sLocalizedLanguage = DoGetLocaleInfo(LOCALE_SLOCALIZEDLANGUAGENAME);
+ sLocalizedLanguage = DoGetLocaleInfo(LOCALE_SLOCALIZEDLANGUAGENAME);
}
// Some OS's might not have this resource or LCTYPE
- if (String.IsNullOrEmpty(this.sLocalizedLanguage))
+ if (String.IsNullOrEmpty(sLocalizedLanguage))
{
- this.sLocalizedLanguage = SNATIVELANGUAGE;
+ sLocalizedLanguage = SNATIVELANGUAGE;
}
}
- return this.sLocalizedLanguage;
+ return sLocalizedLanguage;
}
}
@@ -1062,11 +1061,11 @@ namespace System.Globalization
{
get
{
- if (this.sEnglishLanguage == null)
+ if (sEnglishLanguage == null)
{
- this.sEnglishLanguage = DoGetLocaleInfo(LOCALE_SENGLISHLANGUAGENAME);
+ sEnglishLanguage = DoGetLocaleInfo(LOCALE_SENGLISHLANGUAGENAME);
}
- return this.sEnglishLanguage;
+ return sEnglishLanguage;
}
}
@@ -1075,13 +1074,13 @@ namespace System.Globalization
{
get
{
- if (this.sNativeLanguage == null)
+ if (sNativeLanguage == null)
{
{
- this.sNativeLanguage = DoGetLocaleInfo(LOCALE_SNATIVELANGUAGENAME);
+ sNativeLanguage = DoGetLocaleInfo(LOCALE_SNATIVELANGUAGENAME);
}
}
- return this.sNativeLanguage;
+ return sNativeLanguage;
}
}
@@ -1094,11 +1093,11 @@ namespace System.Globalization
{
get
{
- if (this.sRegionName == null)
+ if (sRegionName == null)
{
- this.sRegionName = DoGetLocaleInfo(LOCALE_SISO3166CTRYNAME);
+ sRegionName = DoGetLocaleInfo(LOCALE_SISO3166CTRYNAME);
}
- return this.sRegionName;
+ return sRegionName;
}
}
@@ -1107,11 +1106,11 @@ namespace System.Globalization
{
get
{
- if (this.iGeoId == undef)
+ if (iGeoId == undef)
{
- this.iGeoId = DoGetLocaleInfoInt(LOCALE_IGEOID);
+ iGeoId = DoGetLocaleInfoInt(LOCALE_IGEOID);
}
- return this.iGeoId;
+ return iGeoId;
}
}
@@ -1120,23 +1119,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))
+ if (String.IsNullOrEmpty(sLocalizedCountry))
{
// 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);
+ sLocalizedCountry = DoGetLocaleInfo(LOCALE_SLOCALIZEDCOUNTRYNAME);
}
- if (String.IsNullOrEmpty(this.sLocalizedDisplayName))
+ if (String.IsNullOrEmpty(sLocalizedDisplayName))
{
- this.sLocalizedCountry = SNATIVECOUNTRY;
+ sLocalizedCountry = SNATIVECOUNTRY;
}
}
}
- return this.sLocalizedCountry;
+ return sLocalizedCountry;
}
}
@@ -1145,11 +1144,11 @@ namespace System.Globalization
{
get
{
- if (this.sEnglishCountry == null)
+ if (sEnglishCountry == null)
{
- this.sEnglishCountry = DoGetLocaleInfo(LOCALE_SENGLISHCOUNTRYNAME);
+ sEnglishCountry = DoGetLocaleInfo(LOCALE_SENGLISHCOUNTRYNAME);
}
- return this.sEnglishCountry;
+ return sEnglishCountry;
}
}
@@ -1158,11 +1157,11 @@ namespace System.Globalization
{
get
{
- if (this.sNativeCountry == null)
+ if (sNativeCountry == null)
{
- this.sNativeCountry = DoGetLocaleInfo(LOCALE_SNATIVECOUNTRYNAME);
+ sNativeCountry = DoGetLocaleInfo(LOCALE_SNATIVECOUNTRYNAME);
}
- return this.sNativeCountry;
+ return sNativeCountry;
}
}
@@ -1171,11 +1170,11 @@ namespace System.Globalization
{
get
{
- if (this.sISO3166CountryName == null)
+ if (sISO3166CountryName == null)
{
- this.sISO3166CountryName = DoGetLocaleInfo(LOCALE_SISO3166CTRYNAME);
+ sISO3166CountryName = DoGetLocaleInfo(LOCALE_SISO3166CTRYNAME);
}
- return this.sISO3166CountryName;
+ return sISO3166CountryName;
}
}
@@ -1184,11 +1183,11 @@ namespace System.Globalization
{
get
{
- if (this.sISO3166CountryName2 == null)
+ if (sISO3166CountryName2 == null)
{
- this.sISO3166CountryName2 = DoGetLocaleInfo(LOCALE_SISO3166CTRYNAME2);
+ sISO3166CountryName2 = DoGetLocaleInfo(LOCALE_SISO3166CTRYNAME2);
}
- return this.sISO3166CountryName2;
+ return sISO3166CountryName2;
}
}
@@ -1197,11 +1196,11 @@ namespace System.Globalization
{
get
{
- if (this.sAbbrevCountry == null)
+ if (sAbbrevCountry == null)
{
- this.sAbbrevCountry = DoGetLocaleInfo(LOCALE_SABBREVCTRYNAME);
+ sAbbrevCountry = DoGetLocaleInfo(LOCALE_SABBREVCTRYNAME);
}
- return this.sAbbrevCountry;
+ return sAbbrevCountry;
}
}
@@ -1210,19 +1209,19 @@ namespace System.Globalization
{
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;
}
}
@@ -1231,16 +1230,16 @@ namespace System.Globalization
{
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 = consoleFallbackName;
}
- return this.sConsoleFallbackName;
+ return sConsoleFallbackName;
}
}
@@ -1250,11 +1249,11 @@ namespace System.Globalization
{
get
{
- if (this.waGrouping == null || UseUserOverride)
+ if (waGrouping == null || UseUserOverride)
{
- this.waGrouping = ConvertWin32GroupString(DoGetLocaleInfo(LOCALE_SGROUPING));
+ waGrouping = ConvertWin32GroupString(DoGetLocaleInfo(LOCALE_SGROUPING));
}
- return this.waGrouping;
+ return waGrouping;
}
}
@@ -1267,11 +1266,11 @@ namespace System.Globalization
{
get
{
- if (this.sNaN == null)
+ if (sNaN == null)
{
- this.sNaN = DoGetLocaleInfo(LOCALE_SNAN);
+ sNaN = DoGetLocaleInfo(LOCALE_SNAN);
}
- return this.sNaN;
+ return sNaN;
}
}
@@ -1280,11 +1279,11 @@ namespace System.Globalization
{
get
{
- if (this.sPositiveInfinity == null)
+ if (sPositiveInfinity == null)
{
- this.sPositiveInfinity = DoGetLocaleInfo(LOCALE_SPOSINFINITY);
+ sPositiveInfinity = DoGetLocaleInfo(LOCALE_SPOSINFINITY);
}
- return this.sPositiveInfinity;
+ return sPositiveInfinity;
}
}
@@ -1293,11 +1292,11 @@ namespace System.Globalization
{
get
{
- if (this.sNegativeInfinity == null)
+ if (sNegativeInfinity == null)
{
- this.sNegativeInfinity = DoGetLocaleInfo(LOCALE_SNEGINFINITY);
+ sNegativeInfinity = DoGetLocaleInfo(LOCALE_SNEGINFINITY);
}
- return this.sNegativeInfinity;
+ return sNegativeInfinity;
}
}
@@ -1311,12 +1310,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 = DoGetLocaleInfoInt(LOCALE_INEGATIVEPERCENT);
}
- return this.iNegativePercent;
+ return iNegativePercent;
}
}
@@ -1325,12 +1324,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 = DoGetLocaleInfoInt(LOCALE_IPOSITIVEPERCENT);
}
- return this.iPositivePercent;
+ return iPositivePercent;
}
}
@@ -1339,12 +1338,12 @@ 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 = DoGetLocaleInfo(LOCALE_SPERCENT);
}
- return this.sPercent;
+ return sPercent;
}
}
@@ -1353,12 +1352,12 @@ namespace System.Globalization
{
get
{
- if (this.sPerMille == null)
+ if (sPerMille == null)
{
// Note that <= Windows Vista this is synthesized by native code
- this.sPerMille = DoGetLocaleInfo(LOCALE_SPERMILLE);
+ sPerMille = DoGetLocaleInfo(LOCALE_SPERMILLE);
}
- return this.sPerMille;
+ return sPerMille;
}
}
@@ -1371,11 +1370,11 @@ namespace System.Globalization
{
get
{
- if (this.sCurrency == null || UseUserOverride)
+ if (sCurrency == null || UseUserOverride)
{
- this.sCurrency = DoGetLocaleInfo(LOCALE_SCURRENCY);
+ sCurrency = DoGetLocaleInfo(LOCALE_SCURRENCY);
}
- return this.sCurrency;
+ return sCurrency;
}
}
@@ -1384,11 +1383,11 @@ namespace System.Globalization
{
get
{
- if (this.sIntlMonetarySymbol == null)
+ if (sIntlMonetarySymbol == null)
{
- this.sIntlMonetarySymbol = DoGetLocaleInfo(LOCALE_SINTLSYMBOL);
+ sIntlMonetarySymbol = DoGetLocaleInfo(LOCALE_SINTLSYMBOL);
}
- return this.sIntlMonetarySymbol;
+ return sIntlMonetarySymbol;
}
}
@@ -1397,11 +1396,11 @@ namespace System.Globalization
{
get
{
- if (this.sEnglishCurrency == null)
+ if (sEnglishCurrency == null)
{
- this.sEnglishCurrency = DoGetLocaleInfo(LOCALE_SENGCURRNAME);
+ sEnglishCurrency = DoGetLocaleInfo(LOCALE_SENGCURRNAME);
}
- return this.sEnglishCurrency;
+ return sEnglishCurrency;
}
}
@@ -1410,11 +1409,11 @@ namespace System.Globalization
{
get
{
- if (this.sNativeCurrency == null)
+ if (sNativeCurrency == null)
{
- this.sNativeCurrency = DoGetLocaleInfo(LOCALE_SNATIVECURRNAME);
+ sNativeCurrency = DoGetLocaleInfo(LOCALE_SNATIVECURRNAME);
}
- return this.sNativeCurrency;
+ return sNativeCurrency;
}
}
@@ -1427,11 +1426,11 @@ namespace System.Globalization
{
get
{
- if (this.waMonetaryGrouping == null || UseUserOverride)
+ if (waMonetaryGrouping == null || UseUserOverride)
{
- this.waMonetaryGrouping = ConvertWin32GroupString(DoGetLocaleInfo(LOCALE_SMONGROUPING));
+ waMonetaryGrouping = ConvertWin32GroupString(DoGetLocaleInfo(LOCALE_SMONGROUPING));
}
- return this.waMonetaryGrouping;
+ return waMonetaryGrouping;
}
}
@@ -1447,11 +1446,11 @@ namespace System.Globalization
{
get
{
- if (this.iMeasure == undef || UseUserOverride)
+ if (iMeasure == undef || UseUserOverride)
{
- this.iMeasure = DoGetLocaleInfoInt(LOCALE_IMEASURE);
+ iMeasure = DoGetLocaleInfoInt(LOCALE_IMEASURE);
}
- return this.iMeasure;
+ return iMeasure;
}
}
@@ -1460,11 +1459,11 @@ namespace System.Globalization
{
get
{
- if (this.sListSeparator == null || UseUserOverride)
+ if (sListSeparator == null || UseUserOverride)
{
- this.sListSeparator = DoGetLocaleInfo(LOCALE_SLIST);
+ sListSeparator = DoGetLocaleInfo(LOCALE_SLIST);
}
- return this.sListSeparator;
+ return sListSeparator;
}
}
@@ -1477,11 +1476,11 @@ namespace System.Globalization
{
get
{
- if (this.sAM1159 == null || UseUserOverride)
+ if (sAM1159 == null || UseUserOverride)
{
- this.sAM1159 = DoGetLocaleInfo(LOCALE_S1159);
+ sAM1159 = DoGetLocaleInfo(LOCALE_S1159);
}
- return this.sAM1159;
+ return sAM1159;
}
}
@@ -1490,11 +1489,11 @@ namespace System.Globalization
{
get
{
- if (this.sPM2359 == null || UseUserOverride)
+ if (sPM2359 == null || UseUserOverride)
{
- this.sPM2359 = DoGetLocaleInfo(LOCALE_S2359);
+ sPM2359 = DoGetLocaleInfo(LOCALE_S2359);
}
- return this.sPM2359;
+ return sPM2359;
}
}
@@ -1503,19 +1502,19 @@ namespace System.Globalization
{
get
{
- if (this.saLongTimes == null || UseUserOverride)
+ if (saLongTimes == null || UseUserOverride)
{
String[] longTimes = DoEnumTimeFormats();
if (longTimes == null || longTimes.Length == 0)
{
- this.saLongTimes = Invariant.saLongTimes;
+ saLongTimes = Invariant.saLongTimes;
}
else
{
- this.saLongTimes = longTimes;
+ saLongTimes = longTimes;
}
}
- return this.saLongTimes;
+ return saLongTimes;
}
}
@@ -1525,7 +1524,7 @@ namespace System.Globalization
{
get
{
- if (this.saShortTimes == null || UseUserOverride)
+ if (saShortTimes == null || UseUserOverride)
{
// Try to get the short times from the OS/culture.dll
String[] shortTimes = DoEnumShortTimeFormats();
@@ -1540,9 +1539,9 @@ namespace System.Globalization
}
// Found short times, use them
- this.saShortTimes = shortTimes;
+ saShortTimes = shortTimes;
}
- return this.saShortTimes;
+ return saShortTimes;
}
}
@@ -1670,12 +1669,12 @@ namespace System.Globalization
{
get
{
- if (this.iFirstDayOfWeek == undef || UseUserOverride)
+ if (iFirstDayOfWeek == undef || UseUserOverride)
{
// Have to convert it from windows to .Net formats
- this.iFirstDayOfWeek = ConvertFirstDayOfWeekMonToSun(DoGetLocaleInfoInt(LOCALE_IFIRSTDAYOFWEEK));
+ iFirstDayOfWeek = ConvertFirstDayOfWeekMonToSun(DoGetLocaleInfoInt(LOCALE_IFIRSTDAYOFWEEK));
}
- return this.iFirstDayOfWeek;
+ return iFirstDayOfWeek;
}
}
@@ -1684,11 +1683,11 @@ namespace System.Globalization
{
get
{
- if (this.iFirstWeekOfYear == undef || UseUserOverride)
+ if (iFirstWeekOfYear == undef || UseUserOverride)
{
- this.iFirstWeekOfYear = DoGetLocaleInfoInt(LOCALE_IFIRSTWEEKOFYEAR);
+ iFirstWeekOfYear = DoGetLocaleInfoInt(LOCALE_IFIRSTWEEKOFYEAR);
}
- return this.iFirstWeekOfYear;
+ return iFirstWeekOfYear;
}
}
@@ -1778,25 +1777,25 @@ namespace System.Globalization
{
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);
+ Debug.Assert(sWindowsName != null, "[CultureData.CalendarIds] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
+ int count = CalendarData.nativeGetCalendars(sWindowsName, bUseOverrides, calendarInts);
// 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")
+ if (sWindowsName == "zh-TW")
{
bool found = false;
@@ -1839,11 +1838,11 @@ namespace System.Globalization
}
}
- this.waCalendars = temp;
+ waCalendars = temp;
}
}
- return this.waCalendars;
+ return waCalendars;
}
}
@@ -1875,8 +1874,8 @@ namespace System.Globalization
// Make sure that calendar has data
if (calendarData == null || UseUserOverride)
{
- 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);
+ Debug.Assert(sWindowsName != null, "[CultureData.GetCalendar] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
+ calendarData = new CalendarData(sWindowsName, calendarId, this.UseUserOverride);
calendars[calendarIndex] = calendarData;
}
@@ -1913,13 +1912,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 this.sRealName to be populated by COMNlsInfo::nativeInitCultureData already");
+ iReadingLayout = DoGetLocaleInfoInt(LOCALE_IREADINGLAYOUT);
}
- return (this.iReadingLayout);
+ return (iReadingLayout);
}
}
@@ -1934,23 +1933,23 @@ namespace System.Globalization
{
get
{
- if (this.sTextInfo == null)
+ if (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;
+ sTextInfo = GetCultureData(sortLocale, bUseOverrides).SNAME;
}
- if (this.sTextInfo == null)
+ if (sTextInfo == null)
{
- this.sTextInfo = this.SNAME; // removes alternate sort
+ sTextInfo = this.SNAME; // removes alternate sort
}
}
- return this.sTextInfo;
+ return sTextInfo;
}
}
@@ -1959,7 +1958,7 @@ namespace System.Globalization
{
get
{
- if (this.sCompareInfo == null)
+ if (sCompareInfo == null)
{
// LOCALE_SSORTLOCALE is broken in Win7 for Alt sorts.
// It is also not supported downlevel without culture.dll.
@@ -1967,16 +1966,16 @@ namespace System.Globalization
// since for all other cases, it is the same as sWindowsName
if (IsSupplementalCustomCulture)
{
- this.sCompareInfo = DoGetLocaleInfo(LOCALE_SSORTLOCALE);
+ sCompareInfo = DoGetLocaleInfo(LOCALE_SSORTLOCALE);
}
- if (this.sCompareInfo == null)
+ if (sCompareInfo == null)
{
- this.sCompareInfo = this.sWindowsName;
+ sCompareInfo = sWindowsName;
}
}
- return this.sCompareInfo;
+ return sCompareInfo;
}
}
@@ -1993,11 +1992,11 @@ namespace System.Globalization
{
get
{
- if (this.iDefaultAnsiCodePage == undef)
+ if (iDefaultAnsiCodePage == undef)
{
- this.iDefaultAnsiCodePage = DoGetLocaleInfoInt(LOCALE_IDEFAULTANSICODEPAGE);
+ iDefaultAnsiCodePage = DoGetLocaleInfoInt(LOCALE_IDEFAULTANSICODEPAGE);
}
- return this.iDefaultAnsiCodePage;
+ return iDefaultAnsiCodePage;
}
}
@@ -2005,11 +2004,11 @@ namespace System.Globalization
{
get
{
- if (this.iDefaultOemCodePage == undef)
+ if (iDefaultOemCodePage == undef)
{
- this.iDefaultOemCodePage = DoGetLocaleInfoInt(LOCALE_IDEFAULTCODEPAGE);
+ iDefaultOemCodePage = DoGetLocaleInfoInt(LOCALE_IDEFAULTCODEPAGE);
}
- return this.iDefaultOemCodePage;
+ return iDefaultOemCodePage;
}
}
@@ -2017,11 +2016,11 @@ namespace System.Globalization
{
get
{
- if (this.iDefaultMacCodePage == undef)
+ if (iDefaultMacCodePage == undef)
{
- this.iDefaultMacCodePage = DoGetLocaleInfoInt(LOCALE_IDEFAULTMACCODEPAGE);
+ iDefaultMacCodePage = DoGetLocaleInfoInt(LOCALE_IDEFAULTMACCODEPAGE);
}
- return this.iDefaultMacCodePage;
+ return iDefaultMacCodePage;
}
}
@@ -2029,11 +2028,11 @@ namespace System.Globalization
{
get
{
- if (this.iDefaultEbcdicCodePage == undef)
+ if (iDefaultEbcdicCodePage == undef)
{
- this.iDefaultEbcdicCodePage = DoGetLocaleInfoInt(LOCALE_IDEFAULTEBCDICCODEPAGE);
+ iDefaultEbcdicCodePage = DoGetLocaleInfoInt(LOCALE_IDEFAULTEBCDICCODEPAGE);
}
- return this.iDefaultEbcdicCodePage;
+ return iDefaultEbcdicCodePage;
}
}
@@ -2048,23 +2047,23 @@ namespace System.Globalization
{
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 by COMNlsInfo::nativeInitCultureData already");
+ iLanguage = LocaleNameToLCID(sRealName);
}
- return this.iLanguage;
+ return iLanguage;
}
}
internal bool IsWin32Installed
{
- get { return this.bWin32Installed; }
+ get { return bWin32Installed; }
}
internal bool IsFramework
{
- get { return this.bFramework; }
+ get { return bFramework; }
}
////////////////////
@@ -2076,7 +2075,7 @@ namespace System.Globalization
get
{
// NlsInfo::nativeInitCultureData told us if we're neutral or not
- return this.bNeutral;
+ return bNeutral;
}
}
@@ -2413,15 +2412,15 @@ namespace System.Globalization
return -1;
}
- string DoGetLocaleInfo(uint lctype)
+ private 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);
+ Debug.Assert(sWindowsName != null, "[CultureData.DoGetLocaleInfo] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
+ return DoGetLocaleInfo(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)
+ private string DoGetLocaleInfo(string localeName, uint lctype)
{
// Fix lctype if we don't want overrides
if (!UseUserOverride)
@@ -2441,7 +2440,7 @@ namespace System.Globalization
return result;
}
- int DoGetLocaleInfoInt(uint lctype)
+ private int DoGetLocaleInfoInt(uint lctype)
{
// Fix lctype if we don't want overrides
if (!UseUserOverride)
@@ -2451,26 +2450,26 @@ namespace System.Globalization
// 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);
+ Debug.Assert(sWindowsName != null, "[CultureData.DoGetLocaleInfoInt] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
+ int result = CultureInfo.nativeGetLocaleInfoExInt(sWindowsName, lctype);
return result;
}
- String[] DoEnumTimeFormats()
+ private 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));
+ Debug.Assert(sWindowsName != null, "[CultureData.DoEnumTimeFormats] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
+ String[] result = ReescapeWin32Strings(nativeEnumTimeFormats(sWindowsName, 0, UseUserOverride));
return result;
}
- String[] DoEnumShortTimeFormats()
+ private 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));
+ Debug.Assert(sWindowsName != null, "[CultureData.DoEnumShortTimeFormats] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
+ String[] result = ReescapeWin32Strings(nativeEnumTimeFormats(sWindowsName, TIME_NOSECONDS, UseUserOverride));
return result;
}
@@ -2498,23 +2497,23 @@ namespace System.Globalization
{
if (this.IsInvariantCulture)
{
- nfi.positiveSign = this.sPositiveSign;
- nfi.negativeSign = this.sNegativeSign;
+ nfi.positiveSign = sPositiveSign;
+ nfi.negativeSign = sNegativeSign;
- nfi.nativeDigits = this.saNativeDigits;
- nfi.digitSubstitution = this.iDigitSubstitution;
+ nfi.nativeDigits = saNativeDigits;
+ nfi.digitSubstitution = iDigitSubstitution;
- 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
{
@@ -2531,8 +2530,8 @@ namespace System.Globalization
//
// 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);
+ Debug.Assert(sWindowsName != null, "[CultureData.GetNFIValues] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
+ CultureData.nativeGetNumberFormatInfoValues(sWindowsName, nfi, UseUserOverride);
}
diff --git a/src/mscorlib/src/System/Globalization/CultureInfo.cs b/src/mscorlib/src/System/Globalization/CultureInfo.cs
index 88bf29b479..fc213427ba 100644
--- a/src/mscorlib/src/System/Globalization/CultureInfo.cs
+++ b/src/mscorlib/src/System/Globalization/CultureInfo.cs
@@ -26,7 +26,8 @@
//
////////////////////////////////////////////////////////////////////////////
-namespace System.Globalization {
+namespace System.Globalization
+{
using System;
using System.Security;
using System.Threading;
@@ -43,7 +44,8 @@ namespace System.Globalization {
using System.Resources;
[Serializable]
- public partial class CultureInfo : ICloneable, IFormatProvider {
+ public partial class CultureInfo : ICloneable, IFormatProvider
+ {
//--------------------------------------------------------------------//
// Internal Information //
//--------------------------------------------------------------------//
@@ -71,16 +73,16 @@ namespace System.Globalization {
[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)
+ internal int cultureID = 0x007f; // NEVER USED, DO NOT USE THIS! (Serialized in Whidbey/Everett)
//
// 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 m_cultureData;
+
+ [NonSerialized] internal bool m_isInherited;
+ [NonSerialized] private CultureInfo m_consoleFallbackCulture;
// Names are confusing. Here are 3 names we have:
//
@@ -100,12 +102,12 @@ namespace System.Globalization {
// 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 m_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 m_sortName;
//--------------------------------------------------------------------//
@@ -148,17 +150,17 @@ namespace System.Globalization {
#endif
//The parent culture.
- [NonSerialized]private CultureInfo m_parent;
+ [NonSerialized] private CultureInfo m_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_DEFAULT = 0x0c00;
+ internal const int LOCALE_CUSTOM_UNSPECIFIED = 0x1000;
+ internal const int LOCALE_INVARIANT = 0x007F;
+ private const int LOCALE_TRADITIONAL_SPANISH = 0x040a;
//
// The CultureData instance that reads the data provided by our CultureData class.
@@ -168,8 +170,7 @@ namespace System.Globalization {
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;
@@ -185,7 +186,7 @@ namespace System.Globalization {
return true;
}
- static CultureInfo InitUserDefaultCulture()
+ private static CultureInfo InitUserDefaultCulture()
{
String strDefault = GetDefaultLocaleName(LOCALE_USER_DEFAULT);
if (strDefault == null)
@@ -205,7 +206,7 @@ namespace System.Globalization {
return (temp);
}
- static CultureInfo InitUserDefaultUICulture()
+ private static CultureInfo InitUserDefaultUICulture()
{
String strDefault = GetUserDefaultUILanguage();
@@ -215,7 +216,7 @@ namespace System.Globalization {
return (UserDefaultCulture);
}
- CultureInfo temp = GetCultureByName( strDefault, true);
+ CultureInfo temp = GetCultureByName(strDefault, true);
if (temp == null)
{
@@ -236,7 +237,7 @@ namespace System.Globalization {
// (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)
+ if (ts_IsDoingAppXCultureInfoLookup)
{
return null;
}
@@ -254,22 +255,22 @@ namespace System.Globalization {
CultureInfo toReturn = null;
- try
+ try
{
ts_IsDoingAppXCultureInfoLookup = true;
- if(s_WindowsRuntimeResourceManager == null)
+ if (s_WindowsRuntimeResourceManager == null)
{
s_WindowsRuntimeResourceManager = ResourceManager.GetWinRTResourceManager();
}
toReturn = s_WindowsRuntimeResourceManager.GlobalResourceContextBestFitCultureInfo;
- }
- finally
+ }
+ finally
{
- ts_IsDoingAppXCultureInfoLookup = false;
+ ts_IsDoingAppXCultureInfoLookup = false;
}
-
+
return toReturn;
}
@@ -302,12 +303,15 @@ 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"));
}
@@ -316,7 +320,8 @@ namespace System.Globalization {
// Get our data providing record
this.m_cultureData = CultureData.GetCultureData(name, useUserOverride);
- if (this.m_cultureData == null) {
+ if (this.m_cultureData == null)
+ {
throw new CultureNotFoundException(nameof(name), name, Environment.GetResourceString("Argument_CultureNotSupported"));
}
@@ -326,12 +331,15 @@ namespace System.Globalization {
#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) {
+ if (culture < 0)
+ {
throw new ArgumentOutOfRangeException(nameof(culture),
Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
}
@@ -364,9 +372,9 @@ namespace System.Globalization {
}
#endif // FEATURE_USE_LCID
-#region Serialization
+ #region Serialization
// We need to store the override from the culture data record.
- private bool m_useUserOverride;
+ private bool m_useUserOverride;
[OnDeserialized]
private void OnDeserialized(StreamingContext ctx)
@@ -379,7 +387,7 @@ namespace System.Globalization {
// 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");
+ Debug.Assert(cultureID >= 0, "[CultureInfo.OnDeserialized] cultureID >= 0");
InitializeFromCultureId(cultureID, m_useUserOverride);
}
else
@@ -391,7 +399,7 @@ namespace System.Globalization {
if (this.m_cultureData == null)
throw new CultureNotFoundException(
nameof(m_name), m_name, Environment.GetResourceString("Argument_CultureNotSupported"));
-
+
#if FEATURE_USE_LCID
}
#endif
@@ -411,7 +419,7 @@ namespace System.Globalization {
static private bool IsAlternateSortLcid(int lcid)
{
- if(lcid == LOCALE_TRADITIONAL_SPANISH)
+ if (lcid == LOCALE_TRADITIONAL_SPANISH)
{
return true;
}
@@ -423,15 +431,15 @@ namespace System.Globalization {
[OnSerializing]
private void OnSerializing(StreamingContext ctx)
{
- this.m_name = this.m_cultureData.CultureName;
- this.m_useUserOverride = this.m_cultureData.UseUserOverride;
+ this.m_name = this.m_cultureData.CultureName;
+ m_useUserOverride = this.m_cultureData.UseUserOverride;
#if FEATURE_USE_LCID
// for compatibility with v2 serialize cultureID
this.cultureID = this.m_cultureData.ILANGUAGE;
#endif
}
-#endregion Serialization
+ #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
@@ -441,7 +449,8 @@ namespace System.Globalization {
// the GetCultureInfo override *only*.
internal CultureInfo(String cultureName, String textAndCompareCultureName)
{
- if (cultureName==null) {
+ if (cultureName == null)
+ {
throw new ArgumentNullException(nameof(cultureName),
Environment.GetResourceString("ArgumentNull_String"));
}
@@ -451,8 +460,8 @@ namespace System.Globalization {
if (this.m_cultureData == null)
throw new CultureNotFoundException(
nameof(cultureName), cultureName, Environment.GetResourceString("Argument_CultureNotSupported"));
-
- this.m_name = this.m_cultureData.CultureName;
+
+ this.m_name = this.m_cultureData.CultureName;
CultureInfo altCulture = GetCultureInfo(textAndCompareCultureName);
this.compareInfo = altCulture.CompareInfo;
@@ -462,7 +471,7 @@ namespace System.Globalization {
// 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)
private static CultureInfo GetCultureByName(String name, bool userOverride)
- {
+ {
// Try to get our culture
try
{
@@ -483,14 +492,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,64 +511,74 @@ 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 (null == culture)
+ {
// 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)) {
+ if (!(culture.IsNeutralCulture))
+ {
return culture;
}
return (new CultureInfo(culture.m_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().
// 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=='_') {
+ if (Char.IsLetterOrDigit(c) || c == '-' || c == '_')
+ {
continue;
}
- if (throwException) {
+ if (throwException)
+ {
throw new ArgumentException(Environment.GetResourceString("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)
+ {
+ Debug.Assert(culture != null, "[CultureInfo.VerifyCultureName]culture!=null");
//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.m_isInherited)
+ {
return true;
}
return VerifyCultureName(culture.Name, throwException);
-
}
////////////////////////////////////////////////////////////////////////
@@ -571,7 +594,8 @@ namespace System.Globalization {
public static CultureInfo CurrentCulture
{
- get {
+ get
+ {
Contract.Ensures(Contract.Result<CultureInfo>() != null);
// In the case of CoreCLR, Thread.m_CurrentCulture and
@@ -584,7 +608,8 @@ namespace System.Globalization {
// because these fields are thread static, and so do not
// require a Thread instance to be accessed.
#if FEATURE_APPX
- if(AppDomain.IsAppXModel()) {
+ if (AppDomain.IsAppXModel())
+ {
CultureInfo culture = GetCultureInfoForUserPreferredLanguageInAppX();
if (culture != null)
return culture;
@@ -596,27 +621,32 @@ namespace System.Globalization {
UserDefaultCulture;
}
- set {
+ 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;
- }
+ 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;
+ Thread.CurrentThread.CurrentCulture = value;
}
}
//
// This is the equivalence of the Win32 GetUserDefaultLCID()
//
- internal static CultureInfo UserDefaultCulture {
+ internal static CultureInfo UserDefaultCulture
+ {
get
{
Contract.Ensures(Contract.Result<CultureInfo>() != null);
@@ -629,7 +659,7 @@ namespace System.Globalization {
// 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;
@@ -641,21 +671,23 @@ namespace System.Globalization {
//
// This is the equivalence of the Win32 GetUserDefaultUILanguage()
//
- internal static CultureInfo UserDefaultUICulture {
- get {
+ internal static CultureInfo UserDefaultUICulture
+ {
+ get
+ {
Contract.Ensures(Contract.Result<CultureInfo>() != null);
CultureInfo temp = s_userDefaultUICulture;
- if (temp == null)
+ 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;
}
@@ -664,8 +696,10 @@ namespace System.Globalization {
}
- public static CultureInfo CurrentUICulture {
- get {
+ public static CultureInfo CurrentUICulture
+ {
+ get
+ {
Contract.Ensures(Contract.Result<CultureInfo>() != null);
// In the case of CoreCLR, Thread.m_CurrentCulture and
@@ -678,7 +712,8 @@ namespace System.Globalization {
// because these fields are thread static, and so do not
// require a Thread instance to be accessed.
#if FEATURE_APPX
- if(AppDomain.IsAppXModel()) {
+ if (AppDomain.IsAppXModel())
+ {
CultureInfo culture = GetCultureInfoForUserPreferredLanguageInAppX();
if (culture != null)
return culture;
@@ -690,20 +725,24 @@ namespace System.Globalization {
UserDefaultUICulture;
}
- set {
+ 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;
- }
+ 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;
+ Thread.CurrentThread.CurrentUICulture = value;
}
}
@@ -711,12 +750,15 @@ namespace System.Globalization {
//
// 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) {
+ if (temp == null)
+ {
String strDefault = GetSystemDefaultUILanguage();
temp = GetCultureByName(strDefault, true);
@@ -732,13 +774,15 @@ namespace System.Globalization {
}
}
- public static CultureInfo DefaultThreadCurrentCulture {
- get {
+ public static CultureInfo DefaultThreadCurrentCulture
+ {
+ get
+ {
return s_DefaultThreadCurrentCulture;
}
- set {
-
+ set
+ {
// If you add pre-conditions to this method, check to see if you also need to
// add them to Thread.CurrentCulture.set.
@@ -746,21 +790,23 @@ namespace System.Globalization {
}
}
- public static CultureInfo DefaultThreadCurrentUICulture {
- get {
+ public static CultureInfo DefaultThreadCurrentUICulture
+ {
+ get
+ {
return s_DefaultThreadCurrentUICulture;
}
- set {
-
+ 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
// add them to Thread.CurrentUICulture.set.
- if (value != null)
- {
+ if (value != null)
+ {
CultureInfo.VerifyCultureName(value, true);
}
@@ -782,9 +828,11 @@ namespace System.Globalization {
////////////////////////////////////////////////////////////////////////
- public static CultureInfo InvariantCulture {
+ public static CultureInfo InvariantCulture
+ {
[Pure]
- get {
+ get
+ {
Contract.Ensures(Contract.Result<CultureInfo>() != null);
return (s_InvariantCultureInfo);
}
@@ -825,7 +873,7 @@ 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;
+ culture = InvariantCulture;
}
Interlocked.CompareExchange<CultureInfo>(ref m_parent, culture, null);
@@ -844,8 +892,10 @@ namespace System.Globalization {
////////////////////////////////////////////////////////////////////////
#if FEATURE_USE_LCID
- public virtual int LCID {
- get {
+ public virtual int LCID
+ {
+ get
+ {
return (this.m_cultureData.ILANGUAGE);
}
}
@@ -872,11 +922,12 @@ namespace System.Globalization {
}
#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 +942,22 @@ namespace System.Globalization {
// "en-US" This version does NOT include sort information in the name.
//
////////////////////////////////////////////////////////////////////////
- public virtual String Name {
- get {
+ public virtual String Name
+ {
+ get
+ {
Contract.Ensures(Contract.Result<String>() != null);
// 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 (m_nonSortName == null)
+ {
+ m_nonSortName = this.m_cultureData.SNAME;
+ if (m_nonSortName == null)
+ {
+ m_nonSortName = String.Empty;
}
}
- return this.m_nonSortName;
+ return m_nonSortName;
}
}
@@ -911,12 +966,12 @@ namespace System.Globalization {
{
get
{
- if (this.m_sortName == null)
+ if (m_sortName == null)
{
- this.m_sortName = this.m_cultureData.SCOMPAREINFO;
+ m_sortName = this.m_cultureData.SCOMPAREINFO;
}
- return this.m_sortName;
+ return m_sortName;
}
}
@@ -968,8 +1023,10 @@ 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);
}
@@ -984,24 +1041,30 @@ 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);
}
}
-
+
// ie: en
- public virtual String TwoLetterISOLanguageName {
- get {
+ public virtual String TwoLetterISOLanguageName
+ {
+ get
+ {
Contract.Ensures(Contract.Result<String>() != null);
return (this.m_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);
}
@@ -1015,8 +1078,10 @@ 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);
}
@@ -1039,8 +1104,8 @@ namespace System.Globalization {
{
// 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.m_name).CompareInfo
: new CompareInfo(this);
if (CompatibilitySwitches.IsCompatibilityBehaviorDefined)
{
@@ -1064,11 +1129,13 @@ namespace System.Globalization {
////////////////////////////////////////////////////////////////////////
- public virtual TextInfo TextInfo {
- get {
+ public virtual TextInfo TextInfo
+ {
+ get
+ {
Contract.Ensures(Contract.Result<TextInfo>() != null);
- if (textInfo==null)
+ if (textInfo == null)
{
// Make a new textInfo
TextInfo tempTextInfo = new TextInfo(this.m_cultureData);
@@ -1151,18 +1218,23 @@ namespace System.Globalization {
}
- 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 {
+ public virtual bool IsNeutralCulture
+ {
+ get
+ {
return this.m_cultureData.IsNeutralCulture;
}
}
@@ -1175,12 +1247,12 @@ namespace System.Globalization {
if (m_cultureData.IsNeutralCulture)
types |= CultureTypes.NeutralCultures;
- else
+ else
types |= CultureTypes.SpecificCultures;
types |= m_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
@@ -1192,20 +1264,24 @@ namespace System.Globalization {
}
}
- public virtual NumberFormatInfo NumberFormat {
- get
+ public virtual NumberFormatInfo NumberFormat
+ {
+ get
{
Contract.Ensures(Contract.Result<NumberFormatInfo>() != null);
- if (numInfo == null) {
+ if (numInfo == null)
+ {
NumberFormatInfo temp = new NumberFormatInfo(this.m_cultureData);
temp.isReadOnly = m_isReadOnly;
Interlocked.CompareExchange(ref numInfo, temp, null);
}
return (numInfo);
}
- set {
- if (value == null) {
+ set
+ {
+ if (value == null)
+ {
throw new ArgumentNullException(nameof(value),
Environment.GetResourceString("ArgumentNull_Obj"));
}
@@ -1225,11 +1301,14 @@ namespace System.Globalization {
////////////////////////////////////////////////////////////////////////
- public virtual DateTimeFormatInfo DateTimeFormat {
- get {
+ public virtual DateTimeFormatInfo DateTimeFormat
+ {
+ get
+ {
Contract.Ensures(Contract.Result<DateTimeFormatInfo>() != null);
- if (dateTimeInfo == null) {
+ if (dateTimeInfo == null)
+ {
// Change the calendar of DTFI to the specified calendar of this CultureInfo.
DateTimeFormatInfo temp = new DateTimeFormatInfo(
this.m_cultureData, this.Calendar);
@@ -1239,8 +1318,10 @@ namespace System.Globalization {
return (dateTimeInfo);
}
- set {
- if (value == null) {
+ set
+ {
+ if (value == null)
+ {
throw new ArgumentNullException(nameof(value),
Environment.GetResourceString("ArgumentNull_Obj"));
}
@@ -1250,7 +1331,8 @@ namespace System.Globalization {
}
}
- public void ClearCachedData() {
+ public void ClearCachedData()
+ {
s_userDefaultUICulture = null;
s_userDefaultCulture = null;
@@ -1275,8 +1357,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(int calType)
+ {
+ if (calType == Calendar.CAL_GREGORIAN)
+ {
return (new GregorianCalendar());
}
return GetCalendarInstanceRare(calType);
@@ -1284,10 +1368,12 @@ 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");
+ internal static Calendar GetCalendarInstanceRare(int calType)
+ {
+ Debug.Assert(calType != Calendar.CAL_GREGORIAN, "calType!=Calendar.CAL_GREGORIAN");
- switch (calType) {
+ 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
@@ -1333,10 +1419,13 @@ namespace System.Globalization {
============================================================================*/
- public virtual Calendar Calendar {
- get {
+ public virtual Calendar Calendar
+ {
+ get
+ {
Contract.Ensures(Contract.Result<Calendar>() != null);
- if (calendar == null) {
+ if (calendar == null)
+ {
Debug.Assert(this.m_cultureData.CalendarIds.Length > 0, "this.m_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.
@@ -1358,16 +1447,19 @@ 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++) {
+ Calendar[] cals = new Calendar[calID.Length];
+ for (int i = 0; i < cals.Length; i++)
+ {
cals[i] = GetCalendarInstance(calID[i]);
}
return (cals);
@@ -1375,8 +1467,10 @@ namespace System.Globalization {
}
- public bool UseUserOverride {
- get {
+ public bool UseUserOverride
+ {
+ get
+ {
return (this.m_cultureData.UseUserOverride);
}
}
@@ -1404,7 +1498,7 @@ 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 (!m_isInherited)
+ if (!m_isInherited)
{
if (this.dateTimeInfo != null)
{
@@ -1414,36 +1508,38 @@ 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 +1548,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.m_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);
@@ -1484,14 +1584,18 @@ namespace System.Globalization {
}
- public bool IsReadOnly {
- get {
+ public bool IsReadOnly
+ {
+ get
+ {
return (m_isReadOnly);
}
}
- private void VerifyWritable() {
- if (m_isReadOnly) {
+ private void VerifyWritable()
+ {
+ if (m_isReadOnly)
+ {
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
}
Contract.EndContractBlock();
@@ -1526,7 +1630,7 @@ namespace System.Globalization {
{
name = CultureData.AnsiToLower(name);
}
-
+
if (altName != null)
{
altName = CultureData.AnsiToLower(altName);
@@ -1571,7 +1675,7 @@ namespace System.Globalization {
// 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];
+ retval = (CultureInfo)tempLcidHT[lcid];
if (retval != null)
{
return retval;
@@ -1583,7 +1687,7 @@ namespace System.Globalization {
// 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
@@ -1603,7 +1707,7 @@ namespace System.Globalization {
#endif
}
}
- catch(ArgumentException)
+ catch (ArgumentException)
{
return null;
}
@@ -1624,7 +1728,7 @@ namespace System.Globalization {
// 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
@@ -1648,7 +1752,7 @@ namespace System.Globalization {
#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;
@@ -1669,7 +1773,8 @@ 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) {
+ if (culture <= 0)
+ {
throw new ArgumentOutOfRangeException(nameof(culture),
Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
}
@@ -1702,7 +1807,6 @@ namespace System.Globalization {
{
throw new CultureNotFoundException(
nameof(name), name, Environment.GetResourceString("Argument_CultureNotSupported"));
-
}
return retval;
}
@@ -1729,8 +1833,8 @@ namespace System.Globalization {
{
throw new CultureNotFoundException(nameof(name) + " or " + nameof(altName),
String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString("Argument_OneOfCulturesNotSupported"),
+ CultureInfo.CurrentCulture,
+ Environment.GetResourceString("Argument_OneOfCulturesNotSupported"),
name,
altName));
}
@@ -1751,7 +1855,7 @@ namespace System.Globalization {
String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_CultureIetfNotSupported"), name)
);
}
-
+
CultureInfo ci = GetCultureInfo(name);
// Disallow alt sorts and es-es_TS
@@ -1762,7 +1866,7 @@ namespace System.Globalization {
String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_CultureIetfNotSupported"), name)
);
}
-
+
return ci;
}
@@ -1784,11 +1888,11 @@ namespace System.Globalization {
//
// 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);
@@ -1797,7 +1901,7 @@ namespace System.Globalization {
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)))
+ if (InternalGetDefaultLocaleName(localeType, JitHelpers.GetStringHandleOnStack(ref localeName)))
{
return localeName;
}
@@ -1813,13 +1917,13 @@ namespace System.Globalization {
private static String GetUserDefaultUILanguage()
{
string userDefaultUiLanguage = null;
- if(InternalGetUserDefaultUILanguage(JitHelpers.GetStringHandleOnStack(ref userDefaultUiLanguage)))
+ 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)]
@@ -1829,12 +1933,11 @@ namespace System.Globalization {
private static String GetSystemDefaultUILanguage()
{
string systemDefaultUiLanguage = null;
- if(InternalGetSystemDefaultUILanguage(JitHelpers.GetStringHandleOnStack(ref systemDefaultUiLanguage)))
+ if (InternalGetSystemDefaultUILanguage(JitHelpers.GetStringHandleOnStack(ref systemDefaultUiLanguage)))
{
return systemDefaultUiLanguage;
}
return String.Empty;
-
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
diff --git a/src/mscorlib/src/System/Globalization/CultureNotFoundException.cs b/src/mscorlib/src/System/Globalization/CultureNotFoundException.cs
index d4ab700a16..8752cf3f78 100644
--- a/src/mscorlib/src/System/Globalization/CultureNotFoundException.cs
+++ b/src/mscorlib/src/System/Globalization/CultureNotFoundException.cs
@@ -3,18 +3,19 @@
// 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;
-
+using System;
+using System.Runtime.Serialization;
+using System.Threading;
+using System.Diagnostics.Contracts;
+
+namespace System.Globalization
+{
[Serializable]
public partial class CultureNotFoundException : ArgumentException, ISerializable
{
- private string m_invalidCultureName; // unrecognized culture name
- private Nullable<int> m_invalidCultureId; // unrecognized culture Lcid
+ private string m_invalidCultureName; // unrecognized culture name
+ private Nullable<int> m_invalidCultureId; // unrecognized culture Lcid
public CultureNotFoundException()
: base(DefaultMessage)
@@ -60,13 +61,16 @@ namespace System.Globalization {
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));
+ 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) {
+ public override void GetObjectData(SerializationInfo info, StreamingContext context)
+ {
+ if (info == null)
+ {
throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
@@ -88,13 +92,13 @@ namespace System.Globalization {
private static String DefaultMessage
{
- get
+ get
{
return Environment.GetResourceString("Argument_CultureNotSupported");
}
}
-
- private String FormatedInvalidCultureId
+
+ private String FormatedInvalidCultureId
{
get
{
@@ -107,23 +111,22 @@ namespace System.Globalization {
}
}
- public override String Message
+ public override String Message
{
- get
+ get
{
String s = base.Message;
if (
- m_invalidCultureId != null ||
- m_invalidCultureName != null)
+ 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 + Environment.NewLine + valueMessage;
}
return s;
}
}
-
}
}
diff --git a/src/mscorlib/src/System/Globalization/CultureTypes.cs b/src/mscorlib/src/System/Globalization/CultureTypes.cs
index b19ab86bb1..3cb12d648c 100644
--- a/src/mscorlib/src/System/Globalization/CultureTypes.cs
+++ b/src/mscorlib/src/System/Globalization/CultureTypes.cs
@@ -6,25 +6,24 @@
// The enumeration constants used in CultureInfo.GetCultures().
//
// Note that this isn't exposed in Silverlight
-namespace System.Globalization {
-
-[Serializable]
+namespace System.Globalization
+{
+ [Serializable]
[Flags]
- public enum CultureTypes
+ 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.
+ 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.
+ 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.
+ 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
index 1ace207952..b87731ad74 100644
--- a/src/mscorlib/src/System/Globalization/DateTimeFormat.cs
+++ b/src/mscorlib/src/System/Globalization/DateTimeFormat.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.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;
+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;
+namespace System
+{
/*
Customized format patterns:
P.S. Format in the table below is the internal number format used to display the pattern.
@@ -121,25 +122,25 @@ namespace System {
(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 {
-
+ class DateTimeFormat
+ {
internal const int MaxSecondsFractionDigits = 7;
internal static readonly TimeSpan NullOffset = TimeSpan.MinValue;
-
- internal static char[] allStandardFormats =
+
+ internal static char[] allStandardFormats =
{
- 'd', 'D', 'f', 'F', 'g', 'G',
- 'm', 'M', 'o', 'O', 'r', 'R',
+ '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;
@@ -171,12 +172,14 @@ namespace System {
// The function can format to Int32.MaxValue.
//
////////////////////////////////////////////////////////////////////////////
- internal static void FormatDigits(StringBuilder outputBuffer, int value, int len) {
+ 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) {
+ 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
@@ -184,58 +187,61 @@ namespace System {
if (!overrideLengthLimit && len > 2)
{
len = 2;
- }
+ }
char* buffer = stackalloc char[16];
char* p = buffer + 16;
int n = value;
- do {
+ do
+ {
*--p = (char)(n % 10 + '0');
n /= 10;
- } while ((n != 0)&&(p > buffer));
-
- int digits = (int) (buffer + 16 - p);
-
+ } 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';
+ while ((digits < len) && (p > buffer))
+ {
+ *--p = '0';
digits++;
}
outputBuffer.Append(p, digits);
}
- private static void HebrewFormatDigits(StringBuilder outputBuffer, int 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))
+ 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");
+ Debug.Assert(month >= 1 && month <= 12, "month >=1 && month <= 12");
if (repeatCount == 3)
{
return (dtfi.GetAbbreviatedMonthName(month));
@@ -257,7 +263,7 @@ namespace System {
// 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
@@ -277,20 +283,23 @@ namespace System {
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))) {
+ 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) {
+ if (month >= 7)
+ {
month++;
}
- if (repeatCount == 3) {
+ 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.
@@ -303,35 +312,41 @@ namespace System {
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++];
+ char ch = format[pos++];
if (ch == quoteChar)
{
foundQuote = true;
break;
}
- else if (ch == '\\') {
+ 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) {
+ 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 {
+ }
+ 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.
@@ -340,13 +355,13 @@ namespace System {
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.
@@ -358,7 +373,7 @@ namespace System {
{
return (-1);
}
- return ((int)format[pos+1]);
+ return ((int)format[pos + 1]);
}
//
@@ -374,26 +389,30 @@ namespace System {
// 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) {
+ 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) {
+
+ if (i >= 0)
+ {
// Find a "d", so look back to see how many "d" that we can find.
- while (--i >= 0 && format[i] == patternToMatch) {
+ 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) {
+ 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
@@ -407,17 +426,20 @@ namespace System {
// Find first "d"
for (i = index + tokenLen; i < format.Length && format[i] != patternToMatch; i++) { /* Do nothing here */ };
- if (i < format.Length) {
+ 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) {
+ 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) {
+ if (repeat <= 1)
+ {
return (true);
}
}
@@ -430,9 +452,8 @@ namespace System {
//
// Actions: Format the DateTime instance using the specified format.
//
- private static String FormatCustomized(DateTime dateTime, String format, DateTimeFormatInfo dtfi, TimeSpan offset) {
-
-
+ 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.
@@ -440,14 +461,16 @@ namespace System {
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) {
+
+ while (i < format.Length)
+ {
char ch = format[i];
int nextChar;
- switch (ch) {
+ switch (ch)
+ {
case 'g':
tokenLen = ParseRepeatPattern(format, i, ch);
result.Append(dtfi.GetEraName(cal.GetEra(dateTime)));
@@ -476,34 +499,45 @@ namespace System {
case 'f':
case 'F':
tokenLen = ParseRepeatPattern(format, i, ch);
- if (tokenLen <= MaxSecondsFractionDigits) {
+ if (tokenLen <= MaxSecondsFractionDigits)
+ {
long fraction = (dateTime.Ticks % Calendar.TicksPerSecond);
fraction = fraction / (long)Math.Pow(10, 7 - tokenLen);
- if (ch == 'f') {
+ if (ch == 'f')
+ {
result.Append(((int)fraction).ToString(fixedNumberFormats[tokenLen - 1], CultureInfo.InvariantCulture));
}
- else {
+ else
+ {
int effectiveDigits = tokenLen;
- 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)
+ {
result.Append(((int)fraction).ToString(fixedNumberFormats[effectiveDigits - 1], CultureInfo.InvariantCulture));
}
- else {
+ else
+ {
// No fraction to emit, so see if we should remove decimal also.
- if (result.Length > 0 && result[result.Length - 1] == '.') {
+ if (result.Length > 0 && result[result.Length - 1] == '.')
+ {
result.Remove(result.Length - 1, 1);
}
}
}
- } else {
+ }
+ else
+ {
throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
}
break;
@@ -525,7 +559,6 @@ namespace System {
result.Append(dtfi.PMDesignator[0]);
}
}
-
}
else
{
@@ -543,13 +576,16 @@ namespace System {
if (tokenLen <= 2)
{
int day = cal.GetDayOfMonth(dateTime);
- if (isHebrewCalendar) {
+ if (isHebrewCalendar)
+ {
// For Hebrew calendar, we need to convert numbers to Hebrew text for yyyy, MM, and dd values.
HebrewFormatDigits(result, day);
- } else {
+ }
+ else
+ {
FormatDigits(result, day, tokenLen);
}
- }
+ }
else
{
int dayOfWeek = (int)cal.GetDayOfWeek(dateTime);
@@ -568,28 +604,38 @@ namespace System {
int month = cal.GetMonth(dateTime);
if (tokenLen <= 2)
{
- if (isHebrewCalendar) {
+ if (isHebrewCalendar)
+ {
// For Hebrew calendar, we need to convert numbers to Hebrew text for yyyy, MM, and dd values.
HebrewFormatDigits(result, month);
- } else {
+ }
+ else
+ {
FormatDigits(result, month, tokenLen);
}
- }
- else {
- if (isHebrewCalendar) {
+ }
+ else
+ {
+ if (isHebrewCalendar)
+ {
result.Append(FormatHebrewMonthName(dateTime, month, tokenLen, dtfi));
- } else {
- if ((dtfi.FormatFlags & DateTimeFormatFlags.UseGenitiveMonth) != 0 && tokenLen >= 4) {
+ }
+ else
+ {
+ if ((dtfi.FormatFlags & DateTimeFormatFlags.UseGenitiveMonth) != 0 && tokenLen >= 4)
+ {
result.Append(
dtfi.internalGetMonthName(
- month,
- IsUseGenitiveForm(format, i, tokenLen, 'd')? MonthNameStyles.Genitive : MonthNameStyles.Regular,
+ month,
+ IsUseGenitiveForm(format, i, tokenLen, 'd') ? MonthNameStyles.Genitive : MonthNameStyles.Regular,
false));
- } else {
- result.Append(FormatMonth(month, tokenLen, dtfi));
+ }
+ else
+ {
+ result.Append(FormatMonth(month, tokenLen, dtfi));
+ }
}
}
- }
bTimeOnly = false;
break;
case 'y':
@@ -600,17 +646,22 @@ namespace System {
int year = cal.GetYear(dateTime);
tokenLen = ParseRepeatPattern(format, i, ch);
- if (dtfi.HasForceTwoDigitYears) {
+ if (dtfi.HasForceTwoDigitYears)
+ {
FormatDigits(result, year, tokenLen <= 2 ? tokenLen : 2);
}
- else if (cal.ID == Calendar.CAL_HEBREW) {
+ else if (cal.ID == Calendar.CAL_HEBREW)
+ {
HebrewFormatDigits(result, year);
}
- else {
- if (tokenLen <= 2) {
+ else
+ {
+ if (tokenLen <= 2)
+ {
FormatDigits(result, year % 100, tokenLen);
}
- else {
+ else
+ {
String fmtPattern = "D" + tokenLen.ToString();
result.Append(year.ToString(fmtPattern, CultureInfo.InvariantCulture));
}
@@ -635,7 +686,7 @@ namespace System {
break;
case '\'':
case '\"':
- tokenLen = ParseQuoteString(format, i, result);
+ tokenLen = ParseQuoteString(format, i, result);
break;
case '%':
// Optional format character.
@@ -644,7 +695,8 @@ namespace System {
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)'%') {
+ if (nextChar >= 0 && nextChar != (int)'%')
+ {
result.Append(FormatCustomized(dateTime, ((char)nextChar).ToString(), dtfi, offset));
tokenLen = 2;
}
@@ -671,7 +723,7 @@ namespace System {
{
result.Append(((char)nextChar));
tokenLen = 2;
- }
+ }
else
{
//
@@ -692,44 +744,55 @@ namespace System {
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) {
+ 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) {
+ if (dateTimeFormat)
+ {
// No offset. The instance is a DateTime and the output should be the local time zone
-
- if (timeOnly && dateTime.Ticks < Calendar.TicksPerDay) {
+
+ 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) {
+ }
+ else if (dateTime.Kind == DateTimeKind.Utc)
+ {
offset = TimeSpan.Zero;
- } else {
+ }
+ else
+ {
offset = TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime);
}
}
- if (offset >= TimeSpan.Zero) {
+ if (offset >= TimeSpan.Zero)
+ {
result.Append('+');
}
- else {
+ 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) {
+ if (tokenLen <= 1)
+ {
// 'z' format e.g "-7"
result.AppendFormat(CultureInfo.InvariantCulture, "{0:0}", offset.Hours);
}
- else {
+ else
+ {
// 'zz' or longer format e.g "-07"
result.AppendFormat(CultureInfo.InvariantCulture, "{0:00}", offset.Hours);
- if (tokenLen >= 3) {
+ if (tokenLen >= 3)
+ {
// 'zzz*' or longer format e.g "-07:30"
result.AppendFormat(CultureInfo.InvariantCulture, ":{0:00}", offset.Minutes);
}
@@ -737,16 +800,18 @@ namespace System {
}
// output the 'K' format, which is for round-tripping the data
- private static void FormatCustomizedRoundripTimeZone(DateTime dateTime, TimeSpan offset, StringBuilder result) {
-
+ 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) {
+
+ if (offset == NullOffset)
+ {
// source is a date time, so behavior depends on the kind.
- switch (dateTime.Kind) {
- case DateTimeKind.Local:
+ 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
@@ -758,12 +823,14 @@ namespace System {
default:
// If the kind is unspecified, we output nothing here
return;
- }
+ }
}
- if (offset >= TimeSpan.Zero) {
- result.Append('+');
+ if (offset >= TimeSpan.Zero)
+ {
+ result.Append('+');
}
- else {
+ else
+ {
result.Append('-');
// get a positive offset, so that you don't need a separate code path for the negative numbers.
offset = offset.Negate();
@@ -773,12 +840,12 @@ namespace System {
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
@@ -834,47 +901,53 @@ namespace System {
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]) {
+ 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) {
+ if (offset != NullOffset)
+ {
// Convert to UTC invariants mean this will be in range
dateTime = dateTime - offset;
}
- else if (dateTime.Kind == DateTimeKind.Local) {
+ else if (dateTime.Kind == DateTimeKind.Local)
+ {
InvalidFormatForLocal(format, dateTime);
}
dtfi = DateTimeFormatInfo.InvariantInfo;
break;
case 's': // Sortable without Time Zone Info
dtfi = DateTimeFormatInfo.InvariantInfo;
- break;
+ break;
case 'u': // Universal time in sortable format.
- if (offset != NullOffset) {
+ if (offset != NullOffset)
+ {
// Convert to UTC invariants mean this will be in range
dateTime = dateTime - offset;
}
- else if (dateTime.Kind == DateTimeKind.Local) {
-
+ else if (dateTime.Kind == DateTimeKind.Local)
+ {
InvalidFormatForLocal(format, dateTime);
}
dtfi = DateTimeFormatInfo.InvariantInfo;
break;
case 'U': // Universal time in culture dependent format.
- if (offset != NullOffset) {
+ if (offset != NullOffset)
+ {
// This format is not supported by DateTimeOffset
throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
}
@@ -883,7 +956,8 @@ namespace System {
// Change the Calendar to be Gregorian Calendar.
//
dtfi = (DateTimeFormatInfo)dtfi.Clone();
- if (dtfi.Calendar.GetType() != typeof(GregorianCalendar)) {
+ if (dtfi.Calendar.GetType() != typeof(GregorianCalendar))
+ {
dtfi.Calendar = GregorianCalendar.GetDefaultInstance();
}
dateTime = dateTime.ToUniversalTime();
@@ -893,17 +967,20 @@ namespace System {
return (format);
}
- internal static String Format(DateTime dateTime, String format, DateTimeFormatInfo dtfi) {
+ 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) {
+ if (format == null || format.Length == 0)
+ {
Boolean timeOnlySpecialCase = false;
- if (dateTime.Ticks < Calendar.TicksPerDay) {
+ 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.
//
@@ -917,8 +994,9 @@ namespace System {
// 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:
+ switch (dtfi.Calendar.ID)
+ {
+ case Calendar.CAL_JAPAN:
case Calendar.CAL_TAIWAN:
case Calendar.CAL_HIJRI:
case Calendar.CAL_HEBREW:
@@ -927,32 +1005,37 @@ namespace System {
case Calendar.CAL_PERSIAN:
timeOnlySpecialCase = true;
dtfi = DateTimeFormatInfo.InvariantInfo;
- break;
- }
- }
- if (offset == NullOffset) {
+ break;
+ }
+ }
+ if (offset == NullOffset)
+ {
// Default DateTime.ToString case.
- if (timeOnlySpecialCase) {
- format = "s";
+ if (timeOnlySpecialCase)
+ {
+ format = "s";
}
- else {
- format = "G";
+ else
+ {
+ format = "G";
}
}
- else {
+ else
+ {
// Default DateTimeOffset.ToString case.
- if (timeOnlySpecialCase) {
+ if (timeOnlySpecialCase)
+ {
format = RoundtripDateTimeUnfixed;
}
- else {
+ else
+ {
format = dtfi.DateTimeOffsetPattern;
}
-
}
-
}
- if (format.Length == 1) {
+ if (format.Length == 1)
+ {
switch (format[0])
{
case 'O':
@@ -964,7 +1047,7 @@ namespace System {
}
format = ExpandPredefinedFormat(format, ref dateTime, ref dtfi, ref offset);
- }
+ }
return (FormatCustomized(dateTime, format, dtfi, offset));
}
@@ -1051,13 +1134,13 @@ namespace System {
internal static String[] GetAllDateTimes(DateTime dateTime, char format, DateTimeFormatInfo dtfi)
{
Contract.Requires(dtfi != null);
- String [] allFormats = null;
- String [] results = null;
-
+ String[] allFormats = null;
+ String[] results = null;
+
switch (format)
{
case 'd':
- case 'D':
+ case 'D':
case 'f':
case 'F':
case 'g':
@@ -1065,7 +1148,7 @@ namespace System {
case 'm':
case 'M':
case 't':
- case 'T':
+ case 'T':
case 'y':
case 'Y':
allFormats = dtfi.GetAllDateTimePatterns(format);
@@ -1083,7 +1166,7 @@ namespace System {
{
results[i] = Format(universalTime, allFormats[i], dtfi);
}
- break;
+ break;
//
// The following ones are special cases because these patterns are read-only in
// DateTimeFormatInfo.
@@ -1093,20 +1176,19 @@ namespace System {
case 'o':
case 'O':
case 's':
- case 'u':
- results = new String[] {Format(dateTime, new String(format, 1), dtfi)};
- break;
+ 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);
@@ -1119,12 +1201,11 @@ namespace System {
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) {
+ 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
index b2374ef0b2..892fa53d6d 100644
--- a/src/mscorlib/src/System/Globalization/DateTimeFormatInfo.cs
+++ b/src/mscorlib/src/System/Globalization/DateTimeFormatInfo.cs
@@ -3,7 +3,8 @@
// See the LICENSE file in the project root for more information.
-namespace System.Globalization {
+namespace System.Globalization
+{
using System;
using System.Security;
using System.Threading;
@@ -25,10 +26,11 @@ namespace System.Globalization {
//
[Flags]
- internal enum MonthNameStyles {
- Regular = 0x00000000,
- Genitive = 0x00000001,
- LeapYear = 0x00000002,
+ internal enum MonthNameStyles
+ {
+ Regular = 0x00000000,
+ Genitive = 0x00000001,
+ LeapYear = 0x00000002,
}
//
@@ -41,16 +43,17 @@ namespace System.Globalization {
// 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,
+ 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,
}
@@ -62,49 +65,49 @@ namespace System.Globalization {
// 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;
+ [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;
+ [NonSerialized] private String m_langName = null;
// CompareInfo usually used by the parser.
- [NonSerialized]private CompareInfo m_compareInfo = null;
+ [NonSerialized] private CompareInfo m_compareInfo = null;
// Culture matches current DTFI. mainly used for string comparisons during parsing.
- [NonSerialized]private CultureInfo m_cultureInfo = null;
+ [NonSerialized] private CultureInfo m_cultureInfo = null;
//
// Caches for various properties.
//
- internal String amDesignator = null;
- internal String pmDesignator = null;
+ internal String amDesignator = null;
+ internal String pmDesignator = null;
[OptionalField(VersionAdded = 1)]
- internal String dateSeparator = null; // derived from short date (whidbey expects, arrowhead doesn't)
+ 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)
+ 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;
+ 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'";
+ 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";
@@ -113,25 +116,25 @@ namespace System.Globalization {
//
// The following are affected by calendar settings.
//
- internal Calendar calendar = null;
+ 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 fullDateTimePattern = null; // long date + long time (whidbey expects, arrowhead doesn't)
- internal String[] abbreviatedDayNames = null;
+ internal String[] abbreviatedDayNames = null;
[OptionalField(VersionAdded = 2)]
- internal String[] m_superShortDayNames = null;
+ internal String[] m_superShortDayNames = null;
- internal String[] dayNames = null;
- internal String[] abbreviatedMonthNames = null;
- internal String[] monthNames = 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;
+ internal String[] genitiveMonthNames = null;
// Cache the abbreviated genitive month names that we retrieve from the data table.
[OptionalField(VersionAdded = 2)]
@@ -139,7 +142,7 @@ namespace System.Globalization {
// Cache the month names of a leap year that we retrieve from the data table.
[OptionalField(VersionAdded = 2)]
- internal String[] leapYearMonthNames = null;
+ internal String[] leapYearMonthNames = null;
// For our "patterns" arrays we have 2 variables, a string and a string[]
//
@@ -148,21 +151,21 @@ namespace System.Globalization {
// When we initially construct our string[], we set the string to string[0]
// The "default" Date/time patterns
- internal String longDatePattern = null;
+ internal String longDatePattern = null;
internal String shortDatePattern = null;
internal String yearMonthPattern = null;
- internal String longTimePattern = 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;
+ 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;
@@ -174,8 +177,8 @@ namespace System.Globalization {
private const int DEFAULT_ALL_DATETIMES_SIZE = 132;
// CultureInfo updates this
- internal bool m_isReadOnly=false;
-
+ 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)]
@@ -187,7 +190,7 @@ namespace System.Globalization {
{
if (m_name == null)
{
- m_name = this.m_cultureData.CultureName;
+ m_name = m_cultureData.CultureName;
}
return (m_name);
}
@@ -195,7 +198,7 @@ namespace System.Globalization {
private CultureInfo Culture
{
- get
+ get
{
if (m_cultureInfo == null)
{
@@ -211,7 +214,7 @@ namespace System.Globalization {
{
if (m_langName == null)
{
- m_langName = this.m_cultureData.SISO639LANGNAME;
+ m_langName = m_cultureData.SISO639LANGNAME;
}
return (m_langName);
}
@@ -228,7 +231,7 @@ namespace System.Globalization {
if (this.abbreviatedDayNames == null)
{
// Get the abbreviated day names for our current calendar
- this.abbreviatedDayNames = this.m_cultureData.AbbreviatedDayNames(Calendar.ID);
+ this.abbreviatedDayNames = m_cultureData.AbbreviatedDayNames(Calendar.ID);
Debug.Assert(this.abbreviatedDayNames.Length == 7, "[DateTimeFormatInfo.GetAbbreviatedDayOfWeekNames] Expected 7 day names in a week");
}
return (this.abbreviatedDayNames);
@@ -251,7 +254,7 @@ namespace System.Globalization {
if (this.m_superShortDayNames == null)
{
// Get the super short day names for our current calendar
- this.m_superShortDayNames = this.m_cultureData.SuperShortDayNames(Calendar.ID);
+ this.m_superShortDayNames = 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);
@@ -268,7 +271,7 @@ namespace System.Globalization {
if (this.dayNames == null)
{
// Get the day names for our current calendar
- this.dayNames = this.m_cultureData.DayNames(Calendar.ID);
+ this.dayNames = m_cultureData.DayNames(Calendar.ID);
Debug.Assert(this.dayNames.Length == 7, "[DateTimeFormatInfo.GetDayOfWeekNames] Expected 7 day names in a week");
}
return (this.dayNames);
@@ -285,7 +288,7 @@ namespace System.Globalization {
if (this.abbreviatedMonthNames == null)
{
// Get the month names for our current calendar
- this.abbreviatedMonthNames = this.m_cultureData.AbbreviatedMonthNames(Calendar.ID);
+ this.abbreviatedMonthNames = 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");
}
@@ -304,7 +307,7 @@ namespace System.Globalization {
if (this.monthNames == null)
{
// Get the month names for our current calendar
- this.monthNames = this.m_cultureData.MonthNames(Calendar.ID);
+ this.monthNames = 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");
}
@@ -317,7 +320,7 @@ namespace System.Globalization {
// Invariant DateTimeFormatInfo doesn't have user-overriden values
// Default calendar is gregorian
public DateTimeFormatInfo()
- : this(CultureInfo.InvariantCulture.m_cultureData,
+ : this(CultureInfo.InvariantCulture.m_cultureData,
GregorianCalendar.GetDefaultInstance())
{
}
@@ -328,7 +331,7 @@ namespace System.Globalization {
Contract.Requires(cal != null);
// Remember our culture
- this.m_cultureData = cultureData;
+ m_cultureData = cultureData;
// m_isDefaultCalendar is set in the setter of Calendar below.
this.Calendar = cal;
@@ -348,10 +351,10 @@ namespace System.Globalization {
if (this.timeSeparator == null) { this.timeSeparator = cultureData.TimeSeparator; }
if (this.dateSeparator == null) { this.dateSeparator = cultureData.DateSeparator(calendarID); }
- this.allLongTimePatterns = this.m_cultureData.LongTimes;
+ this.allLongTimePatterns = m_cultureData.LongTimes;
Debug.Assert(this.allLongTimePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some long time patterns");
- this.allShortTimePatterns = this.m_cultureData.ShortTimes;
+ this.allShortTimePatterns = m_cultureData.ShortTimes;
Debug.Assert(this.allShortTimePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some short time patterns");
this.allLongDatePatterns = cultureData.LongDates(calendarID);
@@ -360,20 +363,20 @@ namespace System.Globalization {
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");
+ allYearMonthPatterns = cultureData.YearMonths(calendarID);
+ Debug.Assert(allYearMonthPatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some year month patterns");
}
-#region Serialization
+ #region Serialization
// The following fields are defined to keep the serialization compatibility with .NET V1.0/V1.1.
[OptionalField(VersionAdded = 1)]
- private int CultureID;
+ private int CultureID;
[OptionalField(VersionAdded = 1)]
- private bool m_useUserOverride;
+ private bool m_useUserOverride;
[OptionalField(VersionAdded = 1)]
private bool bUseCalendarInfo;
[OptionalField(VersionAdded = 1)]
- private int nDataItem;
+ private int nDataItem;
[OptionalField(VersionAdded = 2)]
internal bool m_isDefaultCalendar; // NEVER USED, DO NOT USE THIS! (Serialized in Whidbey)
@@ -389,7 +392,7 @@ namespace System.Globalization {
{
m_cultureData = CultureData.GetCultureData(m_name, m_useUserOverride);
- if (this.m_cultureData == null)
+ if (m_cultureData == null)
throw new CultureNotFoundException(
nameof(m_name), m_name, Environment.GetResourceString("Argument_CultureNotSupported"));
}
@@ -401,7 +404,7 @@ namespace System.Globalization {
#endif
if (calendar == null)
{
- calendar = (Calendar) GregorianCalendar.GetDefaultInstance().Clone();
+ calendar = (Calendar)GregorianCalendar.GetDefaultInstance().Clone();
calendar.SetReadOnlyState(m_isReadOnly);
}
InitializeOverridableProperties(m_cultureData, calendar.ID);
@@ -414,12 +417,12 @@ namespace System.Globalization {
// 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 (longDatePattern != null) this.LongDatePattern = longDatePattern;
if (shortDatePattern != null) this.ShortDatePattern = shortDatePattern;
if (yearMonthPattern != null) this.YearMonthPattern = yearMonthPattern;
- if (longTimePattern != null) this.LongTimePattern = longTimePattern;
+ if (longTimePattern != null) this.LongTimePattern = longTimePattern;
if (shortTimePattern != null) this.ShortTimePattern = shortTimePattern;
-
+
m_isReadOnly = isReadOnly;
}
@@ -427,9 +430,9 @@ namespace System.Globalization {
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
+ CultureID = m_cultureData.ILANGUAGE; // Used for serialization compatibility with Whidbey which didn't always serialize the name
#endif
- m_useUserOverride = this.m_cultureData.UseUserOverride;
+ m_useUserOverride = m_cultureData.UseUserOverride;
// make sure the m_name is initialized.
m_name = this.CultureName;
@@ -449,15 +452,17 @@ namespace System.Globalization {
o = this.AllShortDatePatterns;
o = this.AllYearMonthPatterns;
}
-#endregion Serialization
+ #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 {
+ public static DateTimeFormatInfo InvariantInfo
+ {
+ get
+ {
Contract.Ensures(Contract.Result<DateTimeFormatInfo>() != null);
if (invariantInfo == null)
{
@@ -473,13 +478,17 @@ namespace System.Globalization {
// Returns the current culture's DateTimeFormatInfo. Used by Parse methods.
//
- public static DateTimeFormatInfo CurrentInfo {
- get {
+ public static DateTimeFormatInfo CurrentInfo
+ {
+ get
+ {
Contract.Ensures(Contract.Result<DateTimeFormatInfo>() != null);
System.Globalization.CultureInfo culture = System.Threading.Thread.CurrentThread.CurrentCulture;
- if (!culture.m_isInherited) {
+ if (!culture.m_isInherited)
+ {
DateTimeFormatInfo info = culture.dateTimeInfo;
- if (info != null) {
+ if (info != null)
+ {
return info;
}
}
@@ -488,7 +497,8 @@ namespace System.Globalization {
}
- public static DateTimeFormatInfo GetInstance(IFormatProvider provider) {
+ public static DateTimeFormatInfo GetInstance(IFormatProvider provider)
+ {
// Fast case for a regular CultureInfo
DateTimeFormatInfo info;
CultureInfo cultureProvider = provider as CultureInfo;
@@ -498,13 +508,16 @@ namespace System.Globalization {
}
// Fast case for a DTFI;
info = provider as DateTimeFormatInfo;
- if (info != null) {
+ if (info != null)
+ {
return info;
}
// Wasn't cultureInfo or DTFI, do it the slower way
- if (provider != null) {
+ if (provider != null)
+ {
info = provider.GetFormat(typeof(DateTimeFormatInfo)) as DateTimeFormatInfo;
- if (info != null) {
+ if (info != null)
+ {
return info;
}
}
@@ -513,30 +526,30 @@ namespace System.Globalization {
}
- public Object GetFormat(Type formatType)
+ public Object GetFormat(Type formatType)
{
- return (formatType == typeof(DateTimeFormatInfo)? this: null);
+ return (formatType == typeof(DateTimeFormatInfo) ? this : null);
}
- public Object Clone()
+ 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.calendar = (Calendar)this.Calendar.Clone();
n.m_isReadOnly = false;
return n;
}
- public String AMDesignator
- {
+ public String AMDesignator
+ {
get
{
if (this.amDesignator == null)
{
- this.amDesignator = this.m_cultureData.SAM1159;
+ this.amDesignator = m_cultureData.SAM1159;
}
Debug.Assert(this.amDesignator != null, "DateTimeFormatInfo.AMDesignator, amDesignator != null");
@@ -559,23 +572,28 @@ namespace System.Globalization {
}
- public Calendar Calendar {
- get {
+ public Calendar Calendar
+ {
+ get
+ {
Contract.Ensures(Contract.Result<Calendar>() != null);
-
+
Debug.Assert(this.calendar != null, "DateTimeFormatInfo.Calendar: calendar != null");
return (this.calendar);
}
- set {
+ set
+ {
if (IsReadOnly)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
- if (value == null) {
+ if (value == null)
+ {
throw new ArgumentNullException(nameof(value),
Environment.GetResourceString("ArgumentNull_Obj"));
}
Contract.EndContractBlock();
- if (value == calendar) {
+ if (value == calendar)
+ {
return;
}
@@ -593,39 +611,39 @@ namespace System.Globalization {
//
// These properites are in the order as appearing in calendar.xml.
- m_eraNames = null;
- m_abbrevEraNames = null;
+ m_eraNames = null;
+ m_abbrevEraNames = null;
m_abbrevEnglishEraNames = null;
- monthDayPattern = null;
+ monthDayPattern = null;
- dayNames = null;
- abbreviatedDayNames = null;
- m_superShortDayNames = null;
- monthNames = null;
- abbreviatedMonthNames = null;
- genitiveMonthNames = null;
+ dayNames = null;
+ abbreviatedDayNames = null;
+ m_superShortDayNames = null;
+ monthNames = null;
+ abbreviatedMonthNames = null;
+ genitiveMonthNames = null;
m_genitiveAbbreviatedMonthNames = null;
- leapYearMonthNames = null;
+ leapYearMonthNames = null;
formatFlags = DateTimeFormatFlags.NotInitialized;
- allShortDatePatterns = null;
- allLongDatePatterns = null;
- allYearMonthPatterns = null;
- dateTimeOffsetPattern = null;
+ allShortDatePatterns = null;
+ allLongDatePatterns = null;
+ allYearMonthPatterns = null;
+ dateTimeOffsetPattern = null;
// The defaults need reset as well:
- longDatePattern = null;
- shortDatePattern = null;
- yearMonthPattern = null;
+ 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
+ fullDateTimePattern = null; // Long date + long time
generalShortTimePattern = null; // short date + short time
- generalLongTimePattern = null; // short date + long time
-
+ generalLongTimePattern = null; // short date + long time
+
// Derived item that changes
- dateSeparator = null;
+ dateSeparator = null;
// We don't need to do these because they are not changed by changing calendar
// amDesignator
@@ -653,16 +671,19 @@ namespace System.Globalization {
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;
+ private int[] OptionalCalendars
+ {
+ get
+ {
+ if (this.optionalCalendars == null)
+ {
+ this.optionalCalendars = m_cultureData.CalendarIds;
}
return (this.optionalCalendars);
}
@@ -677,8 +698,10 @@ namespace System.Globalization {
============================================================================*/
- public int GetEra(String eraName) {
- if (eraName == null) {
+ public int GetEra(String eraName)
+ {
+ if (eraName == null)
+ {
throw new ArgumentNullException(nameof(eraName),
Environment.GetResourceString("ArgumentNull_String"));
}
@@ -689,7 +712,8 @@ namespace System.Globalization {
// 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) {
+ if (eraName.Length == 0)
+ {
return (-1);
}
@@ -699,25 +723,32 @@ namespace System.Globalization {
// 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++) {
+ 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);
+ 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++) {
+ 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);
+ if (String.Compare(eraName, m_abbrevEraNames[i], this.Culture, CompareOptions.IgnoreCase) == 0)
+ {
+ return (i + 1);
}
}
- for (int i = 0; i < AbbreviatedEnglishEraNames.Length; i++) {
+ 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);
+ if (String.Compare(eraName, m_abbrevEnglishEraNames[i], StringComparison.InvariantCultureIgnoreCase) == 0)
+ {
+ return (i + 1);
}
}
return (-1);
@@ -729,7 +760,7 @@ namespace System.Globalization {
{
if (this.m_eraNames == null)
{
- this.m_eraNames = this.m_cultureData.EraNames(Calendar.ID);;
+ this.m_eraNames = m_cultureData.EraNames(Calendar.ID); ;
}
return (this.m_eraNames);
}
@@ -745,15 +776,18 @@ namespace System.Globalization {
============================================================================*/
// Era names are 1 indexed
- public String GetEraName(int era) {
- if (era == Calendar.CurrentEra) {
+ 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)) {
+ if ((--era) < EraNames.Length && (era >= 0))
+ {
return (m_eraNames[era]);
}
throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
@@ -765,23 +799,27 @@ namespace System.Globalization {
{
if (this.m_abbrevEraNames == null)
{
- this.m_abbrevEraNames = this.m_cultureData.AbbrevEraNames(Calendar.ID);
+ this.m_abbrevEraNames = m_cultureData.AbbrevEraNames(Calendar.ID);
}
return (this.m_abbrevEraNames);
}
}
// Era names are 1 indexed
- public String GetAbbreviatedEraName(int era) {
- if (AbbreviatedEraNames.Length == 0) {
+ 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) {
+ if (era == Calendar.CurrentEra)
+ {
era = Calendar.CurrentEraValue;
}
- if ((--era) < m_abbrevEraNames.Length && (era >= 0)) {
+ if ((--era) < m_abbrevEraNames.Length && (era >= 0))
+ {
return (m_abbrevEraNames[era]);
}
throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
@@ -794,7 +832,7 @@ namespace System.Globalization {
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);
+ this.m_abbrevEnglishEraNames = m_cultureData.AbbreviatedEnglishEraNames(Calendar.ID);
}
return (this.m_abbrevEnglishEraNames);
}
@@ -803,24 +841,24 @@ namespace System.Globalization {
// 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
+ public String DateSeparator
{
get
{
if (this.dateSeparator == null)
{
- this.dateSeparator = this.m_cultureData.DateSeparator(Calendar.ID);
+ this.dateSeparator = m_cultureData.DateSeparator(Calendar.ID);
}
Debug.Assert(this.dateSeparator != null, "DateTimeFormatInfo.DateSeparator, dateSeparator != null");
return (this.dateSeparator);
}
- set
+ set
{
if (IsReadOnly)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
- if (value == null)
+ if (value == null)
{
throw new ArgumentNullException(nameof(value),
Environment.GetResourceString("ArgumentNull_String"));
@@ -832,25 +870,29 @@ namespace System.Globalization {
}
- public DayOfWeek FirstDayOfWeek
+ public DayOfWeek FirstDayOfWeek
{
get
{
if (this.firstDayOfWeek == -1)
{
- this.firstDayOfWeek = this.m_cultureData.IFIRSTDAYOFWEEK;
+ this.firstDayOfWeek = m_cultureData.IFIRSTDAYOFWEEK;
}
Debug.Assert(this.firstDayOfWeek != -1, "DateTimeFormatInfo.FirstDayOfWeek, firstDayOfWeek != -1");
return ((DayOfWeek)this.firstDayOfWeek);
}
- set {
+ set
+ {
if (IsReadOnly)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
- if (value >= DayOfWeek.Sunday && value <= DayOfWeek.Saturday) {
- firstDayOfWeek = (int)value;
- } else {
+ if (value >= DayOfWeek.Sunday && value <= DayOfWeek.Saturday)
+ {
+ firstDayOfWeek = (int)value;
+ }
+ else
+ {
throw new ArgumentOutOfRangeException(
nameof(value), Environment.GetResourceString("ArgumentOutOfRange_Range",
DayOfWeek.Sunday, DayOfWeek.Saturday));
@@ -859,25 +901,29 @@ namespace System.Globalization {
}
- public CalendarWeekRule CalendarWeekRule
+ public CalendarWeekRule CalendarWeekRule
{
get
{
if (this.calendarWeekRule == -1)
{
- this.calendarWeekRule = this.m_cultureData.IFIRSTWEEKOFYEAR;
+ this.calendarWeekRule = m_cultureData.IFIRSTWEEKOFYEAR;
}
Debug.Assert(this.calendarWeekRule != -1, "DateTimeFormatInfo.CalendarWeekRule, calendarWeekRule != -1");
return ((CalendarWeekRule)this.calendarWeekRule);
}
- set {
+ set
+ {
if (IsReadOnly)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
- if (value >= CalendarWeekRule.FirstDay && value <= CalendarWeekRule.FirstFourDayWeek) {
+ if (value >= CalendarWeekRule.FirstDay && value <= CalendarWeekRule.FirstFourDayWeek)
+ {
calendarWeekRule = (int)value;
- } else {
+ }
+ else
+ {
throw new ArgumentOutOfRangeException(
nameof(value), Environment.GetResourceString("ArgumentOutOfRange_Range",
CalendarWeekRule.FirstDay, CalendarWeekRule.FirstFourDayWeek));
@@ -887,7 +933,7 @@ namespace System.Globalization {
- public String FullDateTimePattern
+ public String FullDateTimePattern
{
get
{
@@ -898,10 +944,12 @@ namespace System.Globalization {
return (fullDateTimePattern);
}
- set {
+ set
+ {
if (IsReadOnly)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
- if (value == null) {
+ if (value == null)
+ {
throw new ArgumentNullException(nameof(value),
Environment.GetResourceString("ArgumentNull_String"));
}
@@ -916,8 +964,8 @@ namespace System.Globalization {
// 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
- {
+ public String LongDatePattern
+ {
get
{
// Initialize our long date pattern from the 1st array value if not set
@@ -926,14 +974,16 @@ namespace System.Globalization {
// Initialize our data
this.longDatePattern = this.UnclonedLongDatePatterns[0];
}
-
+
return this.longDatePattern;
}
- set {
+ set
+ {
if (IsReadOnly)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
- if (value == null) {
+ if (value == null)
+ {
throw new ArgumentNullException(nameof(value),
Environment.GetResourceString("ArgumentNull_String"));
}
@@ -955,9 +1005,9 @@ namespace System.Globalization {
// 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
+ public String LongTimePattern
{
- get
+ get
{
// Initialize our long time pattern from the 1st array value if not set
if (this.longTimePattern == null)
@@ -965,14 +1015,16 @@ namespace System.Globalization {
// Initialize our data
this.longTimePattern = this.UnclonedLongTimePatterns[0];
}
-
- return this.longTimePattern;
+
+ return this.longTimePattern;
}
- set {
+ set
+ {
if (IsReadOnly)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
- if (value == null) {
+ if (value == null)
+ {
throw new ArgumentNullException(nameof(value),
Environment.GetResourceString("ArgumentNull_String"));
}
@@ -983,7 +1035,7 @@ namespace System.Globalization {
// 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
@@ -993,23 +1045,25 @@ namespace System.Globalization {
// Note: just to be confusing there's only 1 month day pattern, not a whole list
- public String MonthDayPattern
+ public String MonthDayPattern
{
- get
+ get
{
- if (this.monthDayPattern == null)
+ if (this.monthDayPattern == null)
{
Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.MonthDayPattern] Expected calID > 0");
- this.monthDayPattern = this.m_cultureData.MonthDay(Calendar.ID);
+ this.monthDayPattern = m_cultureData.MonthDay(Calendar.ID);
}
Debug.Assert(this.monthDayPattern != null, "DateTimeFormatInfo.MonthDayPattern, monthDayPattern != null");
return (this.monthDayPattern);
}
- set {
+ set
+ {
if (IsReadOnly)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
- if (value == null) {
+ if (value == null)
+ {
throw new ArgumentNullException(nameof(value),
Environment.GetResourceString("ArgumentNull_String"));
}
@@ -1020,23 +1074,25 @@ namespace System.Globalization {
}
- public String PMDesignator
+ public String PMDesignator
{
get
{
if (this.pmDesignator == null)
{
- this.pmDesignator = this.m_cultureData.SPM2359;
+ this.pmDesignator = m_cultureData.SPM2359;
}
Debug.Assert(this.pmDesignator != null, "DateTimeFormatInfo.PMDesignator, pmDesignator != null");
return (this.pmDesignator);
}
- set {
+ set
+ {
if (IsReadOnly)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
- if (value == null) {
+ if (value == null)
+ {
throw new ArgumentNullException(nameof(value),
Environment.GetResourceString("ArgumentNull_String"));
}
@@ -1045,11 +1101,10 @@ namespace System.Globalization {
pmDesignator = value;
}
-
}
- public String RFC1123Pattern
+ public String RFC1123Pattern
{
get
{
@@ -1062,7 +1117,7 @@ namespace System.Globalization {
// 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
+ public String ShortDatePattern
{
get
{
@@ -1072,7 +1127,7 @@ namespace System.Globalization {
// Initialize our data
this.shortDatePattern = this.UnclonedShortDatePatterns[0];
}
-
+
return this.shortDatePattern;
}
@@ -1104,7 +1159,7 @@ namespace System.Globalization {
// 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
+ public String ShortTimePattern
{
get
{
@@ -1117,29 +1172,33 @@ namespace System.Globalization {
return this.shortTimePattern;
}
- set {
+ set
+ {
if (IsReadOnly)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
- if (value == null) {
+ if (value == null)
+ {
throw new ArgumentNullException(nameof(value),
Environment.GetResourceString("ArgumentNull_String"));
}
Contract.EndContractBlock();
// Remember the new string
- this.shortTimePattern= value;
+ 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 {
+ public String SortableDateTimePattern
+ {
+ get
+ {
return (sortableDateTimePattern);
}
}
@@ -1151,9 +1210,12 @@ namespace System.Globalization {
** concatation every time somebody asks for the general format.
==============================================================================*/
- internal String GeneralShortTimePattern {
- get {
- if (generalShortTimePattern == null) {
+ internal String GeneralShortTimePattern
+ {
+ get
+ {
+ if (generalShortTimePattern == null)
+ {
generalShortTimePattern = ShortDatePattern + " " + ShortTimePattern;
}
return (generalShortTimePattern);
@@ -1167,9 +1229,12 @@ namespace System.Globalization {
** concatation every time somebody asks for the general format.
==============================================================================*/
- internal String GeneralLongTimePattern {
- get {
- if (generalLongTimePattern == null) {
+ internal String GeneralLongTimePattern
+ {
+ get
+ {
+ if (generalLongTimePattern == null)
+ {
generalLongTimePattern = ShortDatePattern + " " + LongTimePattern;
}
return (generalLongTimePattern);
@@ -1190,19 +1255,23 @@ namespace System.Globalization {
** concatation every time somebody uses this form
==============================================================================*/
- internal String DateTimeOffsetPattern {
- get {
- if (dateTimeOffsetPattern == null) {
-
+ 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]) {
+ 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;
@@ -1210,13 +1279,18 @@ namespace System.Globalization {
break;
case '\'':
case '\"':
- if (inQuote && (quote == LongTimePattern[i])) {
+ 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) {
+ }
+ else if (!inQuote)
+ {
quote = LongTimePattern[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;
@@ -1229,7 +1303,8 @@ namespace System.Globalization {
}
}
- if (!foundZ) {
+ if (!foundZ)
+ {
dateTimePattern = dateTimePattern + " zzz";
}
@@ -1241,24 +1316,24 @@ namespace System.Globalization {
// 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
+ public String TimeSeparator
{
get
{
if (timeSeparator == null)
{
- timeSeparator = this.m_cultureData.TimeSeparator;
+ timeSeparator = m_cultureData.TimeSeparator;
}
Debug.Assert(this.timeSeparator != null, "DateTimeFormatInfo.TimeSeparator, timeSeparator != null");
return (timeSeparator);
}
- set
+ set
{
if (IsReadOnly)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
- if (value == null)
+ if (value == null)
{
throw new ArgumentNullException(nameof(value),
Environment.GetResourceString("ArgumentNull_String"));
@@ -1271,14 +1346,14 @@ namespace System.Globalization {
}
- public String UniversalSortableDateTimePattern
+ 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.
@@ -1297,10 +1372,12 @@ namespace System.Globalization {
return this.yearMonthPattern;
}
- set {
+ set
+ {
if (IsReadOnly)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
- if (value == null) {
+ if (value == null)
+ {
throw new ArgumentNullException(nameof(value),
Environment.GetResourceString("ArgumentNull_String"));
}
@@ -1317,11 +1394,14 @@ namespace System.Globalization {
//
// Check if a string array contains a null value, and throw ArgumentNullException with parameter name "value"
//
- static private void CheckNullValue(String[] values, int length) {
+ 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) {
+ for (int i = 0; i < length; i++)
+ {
+ if (values[i] == null)
+ {
throw new ArgumentNullException("value",
Environment.GetResourceString("ArgumentNull_ArrayValue"));
}
@@ -1329,21 +1409,24 @@ namespace System.Globalization {
}
- public String[] AbbreviatedDayNames
- {
+ public String[] AbbreviatedDayNames
+ {
get
{
return ((String[])internalGetAbbreviatedDayOfWeekNames().Clone());
}
- set {
+ set
+ {
if (IsReadOnly)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
- if (value == null) {
+ if (value == null)
+ {
throw new ArgumentNullException(nameof(value),
Environment.GetResourceString("ArgumentNull_Array"));
}
- if (value.Length != 7) {
+ if (value.Length != 7)
+ {
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidArrayLength", 7), nameof(value));
}
Contract.EndContractBlock();
@@ -1363,10 +1446,12 @@ namespace System.Globalization {
return ((String[])internalGetSuperShortDayNames().Clone());
}
- set {
+ set
+ {
if (IsReadOnly)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
- if (value == null) {
+ if (value == null)
+ {
throw new ArgumentNullException(nameof(value),
Environment.GetResourceString("ArgumentNull_Array"));
}
@@ -1381,17 +1466,19 @@ namespace System.Globalization {
}
- public String[] DayNames
- {
+ public String[] DayNames
+ {
get
{
return ((String[])internalGetDayOfWeekNames().Clone());
}
- set {
+ set
+ {
if (IsReadOnly)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
- if (value == null) {
+ if (value == null)
+ {
throw new ArgumentNullException(nameof(value),
Environment.GetResourceString("ArgumentNull_Array"));
}
@@ -1408,15 +1495,19 @@ namespace System.Globalization {
}
- public String[] AbbreviatedMonthNames {
- get {
+ public String[] AbbreviatedMonthNames
+ {
+ get
+ {
return ((String[])internalGetAbbreviatedMonthNames().Clone());
}
- set {
+ set
+ {
if (IsReadOnly)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
- if (value == null) {
+ if (value == null)
+ {
throw new ArgumentNullException(nameof(value),
Environment.GetResourceString("ArgumentNull_Array"));
}
@@ -1432,17 +1523,19 @@ namespace System.Globalization {
}
- public String[] MonthNames
- {
+ public String[] MonthNames
+ {
get
{
return ((String[])internalGetMonthNames().Clone());
}
- set {
+ set
+ {
if (IsReadOnly)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
- if (value == null) {
+ if (value == null)
+ {
throw new ArgumentNullException(nameof(value),
Environment.GetResourceString("ArgumentNull_Array"));
}
@@ -1459,16 +1552,20 @@ namespace System.Globalization {
// Whitespaces that we allow in the month names.
// U+00a0 is non-breaking space.
- static char[] MonthSpaces = {' ', '\u00a0'};
+ private static char[] MonthSpaces = { ' ', '\u00a0' };
- internal bool HasSpacesInMonthNames {
- get {
+ internal bool HasSpacesInMonthNames
+ {
+ get
+ {
return (FormatFlags & DateTimeFormatFlags.UseSpacesInMonthNames) != 0;
}
}
- internal bool HasSpacesInDayNames {
- get {
+ internal bool HasSpacesInDayNames
+ {
+ get
+ {
return (FormatFlags & DateTimeFormatFlags.UseSpacesInDayNames) != 0;
}
}
@@ -1486,13 +1583,15 @@ namespace System.Globalization {
// Exceptions:
// ArgumentOutOfRangeException When month name is invalid.
//
- internal String internalGetMonthName(int month, MonthNameStyles style, bool abbreviated) {
+ 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) {
+ switch (style)
+ {
case MonthNameStyles.Genitive:
monthNamesArray = internalGetGenitiveMonthNames(abbreviated);
break;
@@ -1500,17 +1599,18 @@ namespace System.Globalization {
monthNamesArray = internalGetLeapYearMonthNames(/*abbreviated*/);
break;
default:
- monthNamesArray = (abbreviated ? internalGetAbbreviatedMonthNames(): internalGetMonthNames());
+ 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)) {
+ if ((month < 1) || (month > monthNamesArray.Length))
+ {
throw new ArgumentOutOfRangeException(
nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Range",
1, monthNamesArray.Length));
}
- return (monthNamesArray[month-1]);
+ return (monthNamesArray[month - 1]);
}
//
@@ -1521,11 +1621,13 @@ namespace System.Globalization {
// Arguments:
// abbreviated When true, return abbreviated form. Otherwise, return a full form.
//
- private String[] internalGetGenitiveMonthNames(bool abbreviated) {
- if (abbreviated) {
+ private String[] internalGetGenitiveMonthNames(bool abbreviated)
+ {
+ if (abbreviated)
+ {
if (this.m_genitiveAbbreviatedMonthNames == null)
{
- this.m_genitiveAbbreviatedMonthNames = this.m_cultureData.AbbreviatedGenitiveMonthNames(this.Calendar.ID);
+ this.m_genitiveAbbreviatedMonthNames = m_cultureData.AbbreviatedGenitiveMonthNames(this.Calendar.ID);
Debug.Assert(this.m_genitiveAbbreviatedMonthNames.Length == 13,
"[DateTimeFormatInfo.GetGenitiveMonthNames] Expected 13 abbreviated genitive month names in a year");
}
@@ -1534,7 +1636,7 @@ namespace System.Globalization {
if (this.genitiveMonthNames == null)
{
- this.genitiveMonthNames = this.m_cultureData.GenitiveMonthNames(this.Calendar.ID);
+ this.genitiveMonthNames = m_cultureData.GenitiveMonthNames(this.Calendar.ID);
Debug.Assert(this.genitiveMonthNames.Length == 13,
"[DateTimeFormatInfo.GetGenitiveMonthNames] Expected 13 genitive month names in a year");
}
@@ -1548,11 +1650,12 @@ namespace System.Globalization {
// 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*/) {
+ 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);
+ this.leapYearMonthNames = m_cultureData.LeapYearMonthNames(Calendar.ID);
Debug.Assert(this.leapYearMonthNames.Length == 13,
"[DateTimeFormatInfo.internalGetLeapYearMonthNames] Expepcted 13 leap year month names");
}
@@ -1560,10 +1663,10 @@ namespace System.Globalization {
}
- public String GetAbbreviatedDayName(DayOfWeek dayofweek)
+ public String GetAbbreviatedDayName(DayOfWeek dayofweek)
{
-
- if ((int)dayofweek < 0 || (int)dayofweek > 6) {
+ if ((int)dayofweek < 0 || (int)dayofweek > 6)
+ {
throw new ArgumentOutOfRangeException(
nameof(dayofweek), Environment.GetResourceString("ArgumentOutOfRange_Range",
DayOfWeek.Sunday, DayOfWeek.Saturday));
@@ -1578,10 +1681,10 @@ namespace System.Globalization {
// Returns the super short day of week names for the specified day of week.
- public String GetShortestDayName(DayOfWeek dayOfWeek)
+ public String GetShortestDayName(DayOfWeek dayOfWeek)
{
-
- if ((int)dayOfWeek < 0 || (int)dayOfWeek > 6) {
+ if ((int)dayOfWeek < 0 || (int)dayOfWeek > 6)
+ {
throw new ArgumentOutOfRangeException(
nameof(dayOfWeek), Environment.GetResourceString("ArgumentOutOfRange_Range",
DayOfWeek.Sunday, DayOfWeek.Saturday));
@@ -1595,7 +1698,7 @@ namespace System.Globalization {
}
// Get all possible combination of inputs
- static private String[] GetCombinedPatterns(String[] patterns1, String[] patterns2, String connectString)
+ static private String[] GetCombinedPatterns(String[] patterns1, String[] patterns2, String connectString)
{
Contract.Requires(patterns1 != null);
Contract.Requires(patterns2 != null);
@@ -1619,7 +1722,7 @@ namespace System.Globalization {
}
- public String[] GetAllDateTimePatterns()
+ public String[] GetAllDateTimePatterns()
{
List<String> results = new List<String>(DEFAULT_ALL_DATETIMES_SIZE);
@@ -1635,10 +1738,10 @@ namespace System.Globalization {
}
- public String[] GetAllDateTimePatterns(char format)
+ public String[] GetAllDateTimePatterns(char format)
{
Contract.Ensures(Contract.Result<String[]>() != null);
- String [] result = null;
+ String[] result = null;
switch (format)
{
@@ -1663,18 +1766,18 @@ namespace System.Globalization {
break;
case 'm':
case 'M':
- result = new String[] {MonthDayPattern};
+ result = new String[] { MonthDayPattern };
break;
case 'o':
case 'O':
- result = new String[] {DateTimeFormat.RoundtripFormat};
+ result = new String[] { DateTimeFormat.RoundtripFormat };
break;
case 'r':
case 'R':
- result = new String[] {rfc1123Pattern};
+ result = new String[] { rfc1123Pattern };
break;
case 's':
- result = new String[] {sortableDateTimePattern};
+ result = new String[] { sortableDateTimePattern };
break;
case 't':
result = this.AllShortTimePatterns;
@@ -1683,7 +1786,7 @@ namespace System.Globalization {
result = this.AllLongTimePatterns;
break;
case 'u':
- result = new String[] {UniversalSortableDateTimePattern};
+ result = new String[] { UniversalSortableDateTimePattern };
break;
case 'y':
case 'Y':
@@ -1696,9 +1799,10 @@ namespace System.Globalization {
}
- public String GetDayName(DayOfWeek dayofweek)
+ public String GetDayName(DayOfWeek dayofweek)
{
- if ((int)dayofweek < 0 || (int)dayofweek > 6) {
+ if ((int)dayofweek < 0 || (int)dayofweek > 6)
+ {
throw new ArgumentOutOfRangeException(
nameof(dayofweek), Environment.GetResourceString("ArgumentOutOfRange_Range",
DayOfWeek.Sunday, DayOfWeek.Saturday));
@@ -1711,29 +1815,31 @@ namespace System.Globalization {
- public String GetAbbreviatedMonthName(int month)
+ public String GetAbbreviatedMonthName(int month)
{
- if (month < 1 || month > 13) {
+ 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]);
+ return (internalGetAbbreviatedMonthNames()[month - 1]);
}
- public String GetMonthName(int month)
+ public String GetMonthName(int month)
{
- if (month < 1 || month > 13) {
+ 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]);
+ return (internalGetMonthNames()[month - 1]);
}
// For our "patterns" arrays we have 2 variables, a string and a string[]
@@ -1743,11 +1849,11 @@ namespace System.Globalization {
// 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)
+ 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,
+ 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
@@ -1803,7 +1909,7 @@ namespace System.Globalization {
return GetMergedPatterns(this.UnclonedYearMonthPatterns, this.YearMonthPattern);
}
}
-
+
private String[] AllShortDatePatterns
{
get
@@ -1819,7 +1925,7 @@ namespace System.Globalization {
return GetMergedPatterns(this.UnclonedShortTimePatterns, this.ShortTimePattern);
}
}
-
+
private String[] AllLongDatePatterns
{
get
@@ -1842,29 +1948,29 @@ namespace System.Globalization {
{
get
{
- if (this.allYearMonthPatterns == null)
+ if (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,
+ Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedYearMonthPatterns] Expected Calendar.ID > 0");
+ allYearMonthPatterns = m_cultureData.YearMonths(this.Calendar.ID);
+ Debug.Assert(allYearMonthPatterns.Length > 0,
"[DateTimeFormatInfo.UnclonedYearMonthPatterns] Expected some year month patterns");
}
- return this.allYearMonthPatterns;
+ return 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
+ 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);
+ this.allShortDatePatterns = m_cultureData.ShortDates(this.Calendar.ID);
Debug.Assert(this.allShortDatePatterns.Length > 0,
"[DateTimeFormatInfo.UnclonedShortDatePatterns] Expected some short date patterns");
}
@@ -1882,7 +1988,7 @@ namespace System.Globalization {
if (allLongDatePatterns == null)
{
Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedLongDatePatterns] Expected Calendar.ID > 0");
- this.allLongDatePatterns = this.m_cultureData.LongDates(this.Calendar.ID);
+ this.allLongDatePatterns = m_cultureData.LongDates(this.Calendar.ID);
Debug.Assert(this.allLongDatePatterns.Length > 0,
"[DateTimeFormatInfo.UnclonedLongDatePatterns] Expected some long date patterns");
}
@@ -1899,11 +2005,11 @@ namespace System.Globalization {
{
if (this.allShortTimePatterns == null)
{
- this.allShortTimePatterns = this.m_cultureData.ShortTimes;
+ this.allShortTimePatterns = m_cultureData.ShortTimes;
Debug.Assert(this.allShortTimePatterns.Length > 0,
"[DateTimeFormatInfo.UnclonedShortTimePatterns] Expected some short time patterns");
}
-
+
return this.allShortTimePatterns;
}
}
@@ -1916,22 +2022,25 @@ namespace System.Globalization {
{
if (this.allLongTimePatterns == null)
{
- this.allLongTimePatterns = this.m_cultureData.LongTimes;
+ this.allLongTimePatterns = 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) {
+ public static DateTimeFormatInfo ReadOnly(DateTimeFormatInfo dtfi)
+ {
+ if (dtfi == null)
+ {
throw new ArgumentNullException(nameof(dtfi),
Environment.GetResourceString("ArgumentNull_Obj"));
}
Contract.EndContractBlock();
- if (dtfi.IsReadOnly) {
+ if (dtfi.IsReadOnly)
+ {
return (dtfi);
}
DateTimeFormatInfo newInfo = (DateTimeFormatInfo)(dtfi.MemberwiseClone());
@@ -1943,8 +2052,10 @@ namespace System.Globalization {
}
- public bool IsReadOnly {
- get {
+ public bool IsReadOnly
+ {
+ get
+ {
return (m_isReadOnly);
}
}
@@ -1985,7 +2096,8 @@ namespace System.Globalization {
{
if (IsReadOnly)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
- if (patterns == null) {
+ if (patterns == null)
+ {
throw new ArgumentNullException(nameof(patterns),
Environment.GetResourceString("ArgumentNull_Array"));
}
@@ -1996,7 +2108,7 @@ namespace System.Globalization {
}
Contract.EndContractBlock();
- for (int i=0; i<patterns.Length; i++)
+ for (int i = 0; i < patterns.Length; i++)
{
if (patterns[i] == null)
{
@@ -2011,17 +2123,17 @@ namespace System.Globalization {
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];
@@ -2029,10 +2141,10 @@ namespace System.Globalization {
case 'y':
case 'Y':
- this.allYearMonthPatterns = patterns;
- this.yearMonthPattern = this.allYearMonthPatterns[0];
+ allYearMonthPatterns = patterns;
+ this.yearMonthPattern = allYearMonthPatterns[0];
break;
-
+
default:
throw new ArgumentException(Environment.GetResourceString("Format_BadFormatSpecifier"), nameof(format));
}
@@ -2066,12 +2178,12 @@ namespace System.Globalization {
Contract.EndContractBlock();
CheckNullValue(value, value.Length - 1);
ClearTokenHashTable();
- this.m_genitiveAbbreviatedMonthNames= value;
+ this.m_genitiveAbbreviatedMonthNames = value;
}
}
public String[] MonthGenitiveNames
- {
+ {
get
{
return ((String[])internalGetGenitiveMonthNames(false).Clone());
@@ -2092,7 +2204,7 @@ namespace System.Globalization {
}
Contract.EndContractBlock();
CheckNullValue(value, value.Length - 1);
- genitiveMonthNames= value;
+ genitiveMonthNames = value;
ClearTokenHashTable();
}
}
@@ -2102,7 +2214,7 @@ namespace System.Globalization {
//
[NonSerialized]
private string m_fullTimeSpanPositivePattern;
- internal String FullTimeSpanPositivePattern
+ internal String FullTimeSpanPositivePattern
{
get
{
@@ -2114,7 +2226,7 @@ namespace System.Globalization {
else
cultureDataWithoutUserOverrides = m_cultureData;
String decimalSeparator = new NumberFormatInfo(cultureDataWithoutUserOverrides).NumberDecimalSeparator;
-
+
m_fullTimeSpanPositivePattern = "d':'h':'mm':'ss'" + decimalSeparator + "'FFFFFFF";
}
return m_fullTimeSpanPositivePattern;
@@ -2126,7 +2238,7 @@ namespace System.Globalization {
//
[NonSerialized]
private string m_fullTimeSpanNegativePattern;
- internal String FullTimeSpanNegativePattern
+ internal String FullTimeSpanNegativePattern
{
get
{
@@ -2141,7 +2253,7 @@ namespace System.Globalization {
//
internal CompareInfo CompareInfo
{
- get
+ get
{
if (m_compareInfo == null)
{
@@ -2149,7 +2261,7 @@ namespace System.Globalization {
// CompareInfo cache. otherwise we would just create CompareInfo using m_cultureData.
m_compareInfo = CompareInfo.GetCompareInfo(m_cultureData.SCOMPAREINFO);
}
-
+
return m_compareInfo;
}
}
@@ -2160,16 +2272,20 @@ namespace System.Globalization {
| DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeLocal
| DateTimeStyles.AssumeUniversal | DateTimeStyles.RoundtripKind);
- internal static void ValidateStyles(DateTimeStyles style, String parameterName) {
- if ((style & InvalidDateTimeStyles) != 0) {
+ 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)) {
+ 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)) {
+ && ((style & (DateTimeStyles.AssumeLocal | DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal)) != 0))
+ {
throw new ArgumentException(Environment.GetResourceString("Argument_ConflictingDateTimeRoundtripStyles"), parameterName);
}
}
@@ -2191,14 +2307,16 @@ namespace System.Globalization {
formatFlags |= (DateTimeFormatFlags)DateTimeFormatInfoScanner.GetFormatFlagUseSpaceInMonthNames(
MonthNames, internalGetGenitiveMonthNames(false), AbbreviatedMonthNames, internalGetGenitiveMonthNames(true));
formatFlags |= (DateTimeFormatFlags)DateTimeFormatInfoScanner.GetFormatFlagUseSpaceInDayNames(DayNames, AbbreviatedDayNames);
- formatFlags |= (DateTimeFormatFlags)DateTimeFormatInfoScanner.GetFormatFlagUseHebrewCalendar((int)Calendar.ID);
+ formatFlags |= (DateTimeFormatFlags)DateTimeFormatInfoScanner.GetFormatFlagUseHebrewCalendar((int)Calendar.ID);
}
return (formatFlags);
}
}
- internal Boolean HasForceTwoDigitYears {
- get {
+ internal Boolean HasForceTwoDigitYears
+ {
+ get
+ {
switch (calendar.ID)
{
// If is y/yy, do not get (year % 100). "y" will print
@@ -2217,8 +2335,10 @@ namespace System.Globalization {
}
// Returns whether the YearMonthAdjustment function has any fix-up work to do for this culture/calendar.
- internal Boolean HasYearMonthAdjustment {
- get {
+ internal Boolean HasYearMonthAdjustment
+ {
+ get
+ {
return ((FormatFlags & DateTimeFormatFlags.UseHebrewRule) != 0);
}
}
@@ -2228,31 +2348,38 @@ namespace System.Globalization {
// 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) {
-
+ 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) {
+ 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)) {
+ 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) {
+ if (parsedMonthName)
+ {
+ if (!Calendar.IsLeapYear(year))
+ {
+ if (month >= 8)
+ {
month--;
}
- else if (month == 7) {
+ else if (month == 7)
+ {
return false;
}
}
@@ -2265,7 +2392,7 @@ namespace System.Globalization {
// DateTimeFormatInfo tokenizer. This is used by DateTime.Parse() to break input string into tokens.
//
[NonSerialized]
- TokenHashValue[] m_dtfiTokenHash;
+ private TokenHashValue[] m_dtfiTokenHash;
private const int TOKEN_HASH_SIZE = 199;
private const int SECOND_PRIME = 197;
@@ -2276,31 +2403,31 @@ namespace System.Globalization {
//
// Common Ignorable Symbols
//
- internal const String IgnorablePeriod = ".";
- internal const String IgnorableComma = ",";
+ 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 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 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 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 CJKHourSuff = "\u6642";
+ internal const String ChineseHourSuff = "\u65f6";
- internal const String CJKMinuteSuff = "\u5206";
- internal const String CJKSecondSuff = "\u79d2";
+ internal const String CJKMinuteSuff = "\u5206";
+ internal const String CJKSecondSuff = "\u79d2";
- internal const String LocalTimeMark = "T";
+ internal const String LocalTimeMark = "T";
internal const String KoreanLangName = "ko";
internal const String JapaneseLangName = "ja";
@@ -2315,18 +2442,22 @@ namespace System.Globalization {
// does not use Japanese calendar.
// The created instance is stored in global s_jajpDTFI.
//
- internal static DateTimeFormatInfo GetJapaneseCalendarDTFI() {
+ internal static DateTimeFormatInfo GetJapaneseCalendarDTFI()
+ {
DateTimeFormatInfo temp = s_jajpDTFI;
- if (temp == null) {
+ if (temp == null)
+ {
temp = new CultureInfo("ja-JP", false).DateTimeFormat;
temp.Calendar = JapaneseCalendar.GetDefaultInstance();
s_jajpDTFI = temp;
}
return (temp);
}
- internal static DateTimeFormatInfo GetTaiwanCalendarDTFI() {
+ internal static DateTimeFormatInfo GetTaiwanCalendarDTFI()
+ {
DateTimeFormatInfo temp = s_zhtwDTFI;
- if (temp == null) {
+ if (temp == null)
+ {
temp = new CultureInfo("zh-TW", false).DateTimeFormat;
temp.Calendar = TaiwanCalendar.GetDefaultInstance();
s_zhtwDTFI = temp;
@@ -2342,18 +2473,21 @@ namespace System.Globalization {
formatFlags = DateTimeFormatFlags.NotInitialized;
}
- internal TokenHashValue[] CreateTokenHashTable() {
+ internal TokenHashValue[] CreateTokenHashTable()
+ {
TokenHashValue[] temp = m_dtfiTokenHash;
- if (temp == null) {
+ 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 (IgnorableComma != sep) InsertHash(temp, IgnorableComma, TokenType.IgnorableSymbol, 0);
if (IgnorablePeriod != sep) InsertHash(temp, IgnorablePeriod, TokenType.IgnorableSymbol, 0);
-
- if (KoreanHourSuff != sep && CJKHourSuff != sep && ChineseHourSuff != sep) {
+
+ 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
@@ -2366,7 +2500,8 @@ namespace System.Globalization {
InsertHash(temp, this.AMDesignator, TokenType.SEP_Am | TokenType.Am, 0);
InsertHash(temp, this.PMDesignator, TokenType.SEP_Pm | TokenType.Pm, 1);
- if (LanguageName.Equals("sq")) {
+ 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);
@@ -2385,18 +2520,21 @@ namespace System.Globalization {
InsertHash(temp, CJKMinuteSuff, TokenType.SEP_MinuteSuff, 0);
InsertHash(temp, CJKSecondSuff, TokenType.SEP_SecondSuff, 0);
- if (koreanLanguage) {
+ 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")) {
+
+ 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 {
+ else
+ {
InsertHash(temp, dateSeparatorOrTimeZoneOffset, TokenType.SEP_DateOrOffset, 0);
}
@@ -2415,7 +2553,7 @@ namespace System.Globalization {
// 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)
{
@@ -2443,7 +2581,8 @@ namespace System.Globalization {
break;
default:
InsertHash(temp, dateWords[i], TokenType.DateWordToken, 0);
- if (LanguageName.Equals("eu")) {
+ if (LanguageName.Equals("eu"))
+ {
// Basque has date words with leading dots
InsertHash(temp, IgnorablePeriod + dateWords[i], TokenType.DateWordToken, 0);
}
@@ -2461,28 +2600,34 @@ namespace System.Globalization {
AddMonthNames(temp, null);
// Add the abbreviated month names.
- for (int i = 1; i <= 13; i++) {
+ 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++) {
+
+ 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++) {
+ 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++) {
+ 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);
@@ -2490,37 +2635,44 @@ namespace System.Globalization {
str = GetAbbreviatedDayName((DayOfWeek)i);
InsertHash(temp, str, TokenType.DayOfWeekToken, i);
-
}
int[] eras = calendar.Eras;
- for (int i = 1; i <= eras.Length; i++) {
+ 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)) {
+ if (LanguageName.Equals(JapaneseLangName))
+ {
// Japanese allows day of week forms like: "(Tue)"
- for (int i = 0; i < 7; i++) {
+ for (int i = 0; i < 7; i++)
+ {
String specialDayOfWeek = "(" + GetAbbreviatedDayName((DayOfWeek)i) + ")";
InsertHash(temp, specialDayOfWeek, TokenType.DayOfWeekToken, i);
}
- if (this.Calendar.GetType() != typeof(JapaneseCalendar)) {
+ 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++) {
+ 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);
+ InsertHash(temp, jaDtfi.AbbreviatedEnglishEraNames[i - 1], TokenType.JapaneseEraToken, i);
}
}
}
- else if (CultureName.Equals("zh-TW")) {
+ 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) {
+ for (int i = 1; i <= twDtfi.Calendar.Eras.Length; i++)
+ {
+ if (twDtfi.GetEraName(i).Length > 0)
+ {
InsertHash(temp, twDtfi.GetEraName(i), TokenType.TEraToken, i);
}
}
@@ -2530,7 +2682,8 @@ namespace System.Globalization {
InsertHash(temp, InvariantInfo.PMDesignator, TokenType.SEP_Pm | TokenType.Pm, 1);
// Add invariant month names and day names.
- for (int i = 1; i <= 12; i++) {
+ 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
@@ -2538,20 +2691,21 @@ namespace System.Globalization {
str = InvariantInfo.GetMonthName(i);
InsertHash(temp, str, TokenType.MonthToken, i);
str = InvariantInfo.GetAbbreviatedMonthName(i);
- InsertHash(temp, str, TokenType.MonthToken, i);
+ InsertHash(temp, str, TokenType.MonthToken, i);
}
- for (int i = 0; i < 7; 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++) {
+ 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);
}
@@ -2570,18 +2724,22 @@ namespace System.Globalization {
private void AddMonthNames(TokenHashValue[] temp, String monthPostfix)
{
- for (int i = 1; i <= 13; i++) {
+ 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) {
+ 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
+ }
+ else
{
InsertHash(temp, str, TokenType.MonthToken, i);
}
@@ -2589,7 +2747,6 @@ namespace System.Globalization {
str = GetAbbreviatedMonthName(i);
InsertHash(temp, str, TokenType.MonthToken, i);
}
-
}
////////////////////////////////////////////////////////////////////////
@@ -2608,13 +2765,14 @@ namespace System.Globalization {
private static bool TryParseHebrewNumber(
ref __DTString str,
out Boolean badFormat,
- out int number) {
-
+ out int number)
+ {
number = -1;
badFormat = false;
int i = str.Index;
- if (!HebrewNumber.IsDigit(str.Value[i])) {
+ 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);
@@ -2623,9 +2781,11 @@ namespace System.Globalization {
HebrewNumberParsingContext context = new HebrewNumberParsingContext(0);
HebrewNumberParsingState state;
- do {
+ do
+ {
state = HebrewNumber.ParseByChar(str.Value[i++], ref context);
- switch (state) {
+ 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.
@@ -2637,7 +2797,8 @@ namespace System.Globalization {
Debug.Assert(state == HebrewNumberParsingState.ContinueParsing || state == HebrewNumberParsingState.FoundEndOfHebrewNumber,
"Invalid returned state from HebrewNumber.ParseByChar()");
- if (state != HebrewNumberParsingState.FoundEndOfHebrewNumber) {
+ if (state != HebrewNumberParsingState.FoundEndOfHebrewNumber)
+ {
// We reach end of the string but we can't find a terminal state in parsing Hebrew number.
return (false);
}
@@ -2651,11 +2812,13 @@ namespace System.Globalization {
return (true);
}
- private static bool IsHebrewChar(char ch) {
+ 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) {
+ internal bool Tokenize(TokenType TokenMask, out TokenType tokenType, out int tokenValue, ref __DTString str)
+ {
tokenType = TokenType.UnknownToken;
tokenValue = 0;
@@ -2664,12 +2827,16 @@ namespace System.Globalization {
char ch = str.m_current;
bool isLetter = Char.IsLetter(ch);
- if (isLetter) {
+ if (isLetter)
+ {
ch = Char.ToLower(ch, this.Culture);
- if (IsHebrewChar(ch) && TokenMask == TokenType.RegularTokenMask) {
+ if (IsHebrewChar(ch) && TokenMask == TokenType.RegularTokenMask)
+ {
bool badFormat;
- if (TryParseHebrewNumber(ref str, out badFormat, out tokenValue)) {
- if (badFormat) {
+ if (TryParseHebrewNumber(ref str, out badFormat, out tokenValue))
+ {
+ if (badFormat)
+ {
tokenType = TokenType.UnknownToken;
return (false);
}
@@ -2688,25 +2855,33 @@ namespace System.Globalization {
int i = 0;
TokenHashValue[] hashTable = m_dtfiTokenHash;
- if (hashTable == null) {
+ if (hashTable == null)
+ {
hashTable = CreateTokenHashTable();
}
- do {
+ do
+ {
value = hashTable[hashcode];
- if (value == null) {
+ 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 (((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) {
+ 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)) {
+ if (Char.IsLetter(nextCh))
+ {
return (false);
}
}
@@ -2715,19 +2890,25 @@ namespace System.Globalization {
tokenValue = value.tokenValue;
str.Advance(value.tokenString.Length);
return (true);
- } else if (value.tokenType == TokenType.MonthToken && HasSpacesInMonthNames) {
+ }
+ 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)) {
+ 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) {
+ }
+ 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)) {
+ if (str.MatchSpecifiedWords(value.tokenString, true, ref matchStrLen))
+ {
tokenType = value.tokenType & TokenMask;
tokenValue = value.tokenValue;
str.Advance(matchStrLen);
@@ -2738,76 +2919,92 @@ namespace System.Globalization {
i++;
hashcode += hashProbe;
if (hashcode >= TOKEN_HASH_SIZE) hashcode -= TOKEN_HASH_SIZE;
- }while (i < 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) {
+ private 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);;
+ hashTable[hashcode] = new TokenHashValue(str, tokenType, tokenValue); ;
- while (++pos < TOKEN_HASH_SIZE) {
+ 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) {
+ 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) {
+ 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) {
+ private 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) {
+ 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])) {
+ 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 {
+ do
+ {
value = hashTable[hashcode];
- if (value == null) {
+ if (value == null)
+ {
//// Console.WriteLine(" Put Key: {0} in {1}", str, hashcode);
hashTable[hashcode] = new TokenHashValue(str, tokenType, tokenValue);
return;
- } else {
+ }
+ else
+ {
// Collision happens. Find another slot.
- if (str.Length >= value.tokenString.Length) {
+ 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) {
+ 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 {
+ }
+ 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.
@@ -2844,12 +3041,14 @@ namespace System.Globalization {
}
} // class DateTimeFormatInfo
- internal class TokenHashValue {
+ internal class TokenHashValue
+ {
internal String tokenString;
internal TokenType tokenType;
internal int tokenValue;
- internal TokenHashValue(String tokenString, TokenType tokenType, 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
index 4555bb2463..630d345cd9 100644
--- a/src/mscorlib/src/System/Globalization/DateTimeFormatInfoScanner.cs
+++ b/src/mscorlib/src/System/Globalization/DateTimeFormatInfoScanner.cs
@@ -18,7 +18,7 @@
//
////////////////////////////////////////////////////////////////////////////
-namespace System.Globalization
+namespace System.Globalization
{
using System;
using System.Globalization;
@@ -31,14 +31,15 @@ namespace System.Globalization
//
//; 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.
+ 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.
}
//
@@ -48,37 +49,38 @@ namespace System.Globalization
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
+ 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.
@@ -86,7 +88,7 @@ namespace System.Globalization
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.
@@ -95,33 +97,33 @@ namespace System.Globalization
// "." 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';
+ 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 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 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 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 CJKHourSuff = "\u6642";
+ internal const String ChineseHourSuff = "\u65f6";
- internal const String CJKMinuteSuff = "\u5206";
- internal const String CJKSecondSuff = "\u79d2";
+ 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
+ private static Dictionary<String, String> KnownWords
{
get
{
@@ -186,14 +188,15 @@ namespace System.Globalization
continue;
}
// Fall thru to check if this is a letter.
- } else
+ }
+ else
{
// End of string
break;
}
}
if (Char.IsLetter(ch) || ch == '\'' || ch == '.')
- {
+ {
break;
}
// Skip the current char since it is not a letter.
@@ -239,7 +242,8 @@ namespace System.Globalization
{
m_dateWords.Add(temp);
}
- } else
+ }
+ else
{
if (!m_dateWords.Contains(str))
{
@@ -251,14 +255,12 @@ namespace System.Globalization
String strWithoutDot = str.Substring(0, str.Length - 1);
if (!m_dateWords.Contains(strWithoutDot))
{
- m_dateWords.Add(strWithoutDot);
+ m_dateWords.Add(strWithoutDot);
}
-
}
}
}
}
-
}
////////////////////////////////////////////////////////////////////////////
@@ -283,18 +285,18 @@ namespace System.Globalization
if (newIndex != index && formatPostfix != null)
{
// There are whitespaces. This will not be a postfix.
- formatPostfix = null;
+ 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();
+ 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 == '\'')
{
@@ -303,12 +305,13 @@ namespace System.Globalization
AddDateWordOrPostfix(formatPostfix, dateWord.ToString());
index++;
break;
- } else if (ch == '\\')
+ }
+ else if (ch == '\\')
{
//
// Escaped character. Look ahead one character
//
-
+
// Skip escaped backslash.
index++;
if (index < pattern.Length)
@@ -316,7 +319,8 @@ namespace System.Globalization
dateWord.Append(pattern[index]);
index++;
}
- } else if (Char.IsWhiteSpace(ch))
+ }
+ else if (Char.IsWhiteSpace(ch))
{
// Found a whitespace. We have to add the current date word/postfix.
AddDateWordOrPostfix(formatPostfix, dateWord.ToString());
@@ -328,12 +332,13 @@ namespace System.Globalization
// Reset the dateWord.
dateWord.Length = 0;
index++;
- } else
+ }
+ else
{
- dateWord.Append(ch);
+ dateWord.Append(ch);
index++;
}
- }
+ }
return (index);
}
@@ -345,11 +350,12 @@ namespace System.Globalization
internal static int ScanRepeatChar(String pattern, char ch, int index, out int count)
{
count = 1;
- while (++index < pattern.Length && pattern[index] == ch) {
+ while (++index < pattern.Length && pattern[index] == ch)
+ {
count++;
}
// Return the updated position.
- return (index);
+ return (index);
}
////////////////////////////////////////////////////////////////////////////
@@ -366,7 +372,7 @@ namespace System.Globalization
// condition.
//
////////////////////////////////////////////////////////////////////////////
-
+
internal void AddIgnorableSymbols(String text)
{
if (m_dateWords == null)
@@ -386,17 +392,17 @@ namespace System.Globalization
//
// Flag used to trace the date patterns (yy/yyyyy/M/MM/MMM/MMM/d/dd) that we have seen.
//
- enum FoundDatePattern
+ private enum FoundDatePattern
{
- None = 0x0000,
- FoundYearPatternFlag = 0x0001,
+ None = 0x0000,
+ FoundYearPatternFlag = 0x0001,
FoundMonthPatternFlag = 0x0002,
- FoundDayPatternFlag = 0x0004,
- FoundYMDPatternFlag = 0x0007, // FoundYearPatternFlag | FoundMonthPatternFlag | FoundDayPatternFlag;
+ FoundDayPatternFlag = 0x0004,
+ FoundYMDPatternFlag = 0x0007, // FoundYearPatternFlag | FoundMonthPatternFlag | FoundDayPatternFlag;
}
// Check if we have found all of the year/month/day pattern.
- FoundDatePattern m_ymdFlags = FoundDatePattern.None;
+ private FoundDatePattern m_ymdFlags = FoundDatePattern.None;
////////////////////////////////////////////////////////////////////////////
@@ -423,21 +429,20 @@ namespace System.Globalization
////////////////////////////////////////////////////////////////////////////
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];
+ char ch = pattern[i];
int chCount;
-
+
switch (ch)
{
case '\'':
// Find a beginning quote. Search until the end quote.
- i = AddDateWords(pattern, i+1, null);
+ i = AddDateWords(pattern, i + 1, null);
break;
case 'M':
i = ScanRepeatChar(pattern, 'M', i, out chCount);
@@ -445,7 +450,7 @@ namespace System.Globalization
{
if (i < pattern.Length && pattern[i] == '\'')
{
- i = AddDateWords(pattern, i+1, "MMMM");
+ i = AddDateWords(pattern, i + 1, "MMMM");
}
}
m_ymdFlags |= FoundDatePattern.FoundMonthPatternFlag;
@@ -488,8 +493,8 @@ namespace System.Globalization
// We are not in quote. Skip the current character.
i++;
break;
- }
- }
+ }
+ }
}
////////////////////////////////////////////////////////////////////////////
@@ -497,17 +502,18 @@ namespace System.Globalization
// Given a DTFI, get all of the date words from date patterns and time patterns.
//
////////////////////////////////////////////////////////////////////////////
-
- internal String[] GetDateWordsOfDTFI(DateTimeFormatInfo dtfi) {
+
+ 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');
@@ -520,24 +526,24 @@ namespace System.Globalization
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)
@@ -574,7 +580,7 @@ namespace System.Globalization
{
// 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);
+ ? FORMATFLAGS.UseGenitiveMonth : 0);
}
////////////////////////////////////////////////////////////////////////////
@@ -585,16 +591,16 @@ namespace System.Globalization
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 |= (ArrayElementsBeginWithDigit(monthNames) ||
+ ArrayElementsBeginWithDigit(genitveMonthNames) ||
+ ArrayElementsBeginWithDigit(abbrevMonthNames) ||
+ ArrayElementsBeginWithDigit(genetiveAbbrevMonthNames)
? FORMATFLAGS.UseDigitPrefixInTokens : 0);
- formatFlags |= (ArrayElementsHaveSpace(monthNames) ||
- ArrayElementsHaveSpace(genitveMonthNames) ||
- ArrayElementsHaveSpace(abbrevMonthNames) ||
- ArrayElementsHaveSpace(genetiveAbbrevMonthNames)
+ formatFlags |= (ArrayElementsHaveSpace(monthNames) ||
+ ArrayElementsHaveSpace(genitveMonthNames) ||
+ ArrayElementsHaveSpace(abbrevMonthNames) ||
+ ArrayElementsHaveSpace(genetiveAbbrevMonthNames)
? FORMATFLAGS.UseSpacesInMonthNames : 0);
return (formatFlags);
}
@@ -606,10 +612,9 @@ namespace System.Globalization
////////////////////////////////////////////////////////////////////////////
internal static FORMATFLAGS GetFormatFlagUseSpaceInDayNames(String[] dayNames, String[] abbrevDayNames)
{
- return ((ArrayElementsHaveSpace(dayNames) ||
- ArrayElementsHaveSpace(abbrevDayNames))
+ return ((ArrayElementsHaveSpace(dayNames) ||
+ ArrayElementsHaveSpace(abbrevDayNames))
? FORMATFLAGS.UseSpacesInDayNames : 0);
-
}
////////////////////////////////////////////////////////////////////////////
@@ -630,8 +635,8 @@ namespace System.Globalization
// array equals to all elmentsof the second array.
// otherwise it returns false.
//-----------------------------------------------------------------------------
-
- private static bool EqualStringArrays(string [] array1, string [] array2)
+
+ private static bool EqualStringArrays(string[] array1, string[] array2)
{
// Shortcut if they're the same array
if (array1 == array2)
@@ -646,7 +651,7 @@ namespace System.Globalization
}
// Check each string
- for (int i=0; i<array1.Length; i++)
+ for (int i = 0; i < array1.Length; i++)
{
if (!array1[i].Equals(array2[i]))
{
@@ -663,17 +668,16 @@ namespace System.Globalization
// 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++)
+ 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++)
+ for (int j = 0; j < array[i].Length; j++)
{
- if ( Char.IsWhiteSpace(array[i][j]) )
+ if (Char.IsWhiteSpace(array[i][j]))
{
return true;
}
@@ -681,7 +685,7 @@ namespace System.Globalization
}
return false;
- }
+ }
////////////////////////////////////////////////////////////////////////////
@@ -689,10 +693,9 @@ namespace System.Globalization
// Check if any element of the array start with a digit.
//
////////////////////////////////////////////////////////////////////////////
- private static bool ArrayElementsBeginWithDigit(string [] array)
+ private static bool ArrayElementsBeginWithDigit(string[] array)
{
-
- for (int i=0; i<array.Length; i++)
+ 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.
@@ -707,7 +710,7 @@ namespace System.Globalization
}
if (index == array[i].Length)
{
- return (false);
+ return (false);
}
if (index == array[i].Length - 1)
@@ -728,20 +731,18 @@ namespace System.Globalization
// 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] == ' ' &&
+ 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
index 363747cfc3..cddfc29092 100644
--- a/src/mscorlib/src/System/Globalization/DateTimeParse.cs
+++ b/src/mscorlib/src/System/Globalization/DateTimeParse.cs
@@ -9,7 +9,8 @@
//
////////////////////////////////////////////////////////////////////////////
-namespace System {
+namespace System
+{
using System;
using System.Text;
using System.Globalization;
@@ -27,57 +28,67 @@ namespace System {
//This class contains only static members
internal static
- class DateTimeParse {
-
+ 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) {
+ 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)) {
+ if (TryParseExact(s, format, dtfi, style, ref result))
+ {
return result.parsedDate;
}
- else {
+ else
+ {
throw GetDateTimeParseException(ref result);
}
}
- internal static DateTime ParseExact(String s, String format, DateTimeFormatInfo dtfi, DateTimeStyles style, out TimeSpan offset) {
+ 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)) {
+ if (TryParseExact(s, format, dtfi, style, ref result))
+ {
offset = result.timeZoneOffset;
return result.parsedDate;
}
- else {
+ else
+ {
throw GetDateTimeParseException(ref result);
}
}
- internal static bool TryParseExact(String s, String format, DateTimeFormatInfo dtfi, DateTimeStyles style, out DateTime 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)) {
+ 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) {
+ 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)) {
+ if (TryParseExact(s, format, dtfi, style, ref resultData))
+ {
result = resultData.parsedDate;
offset = resultData.timeZoneOffset;
return true;
@@ -85,21 +96,26 @@ namespace System {
return false;
}
- internal static bool TryParseExact(String s, String format, DateTimeFormatInfo dtfi, DateTimeStyles style, ref DateTimeResult result) {
- if (s == null) {
+ 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) {
+ if (format == null)
+ {
result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, nameof(format));
return false;
}
- if (s.Length == 0) {
+ if (s.Length == 0)
+ {
result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
return false;
}
- if (format.Length == 0) {
+ if (format.Length == 0)
+ {
result.SetFailure(ParseFailureKind.Format, "Format_BadFormatSpecifier", null);
return false;
}
@@ -110,41 +126,49 @@ namespace System {
}
internal static DateTime ParseExactMultiple(String s, String[] formats,
- DateTimeFormatInfo dtfi, DateTimeStyles style) {
+ 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)) {
+ if (TryParseExactMultiple(s, formats, dtfi, style, ref result))
+ {
return result.parsedDate;
}
- else {
+ else
+ {
throw GetDateTimeParseException(ref result);
}
}
internal static DateTime ParseExactMultiple(String s, String[] formats,
- DateTimeFormatInfo dtfi, DateTimeStyles style, out TimeSpan offset) {
+ 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)) {
+ if (TryParseExactMultiple(s, formats, dtfi, style, ref result))
+ {
offset = result.timeZoneOffset;
return result.parsedDate;
}
- else {
+ else
+ {
throw GetDateTimeParseException(ref result);
}
}
internal static bool TryParseExactMultiple(String s, String[] formats,
- DateTimeFormatInfo dtfi, DateTimeStyles style, out DateTime result, out TimeSpan offset) {
+ 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)) {
+ if (TryParseExactMultiple(s, formats, dtfi, style, ref resultData))
+ {
result = resultData.parsedDate;
offset = resultData.timeZoneOffset;
return true;
@@ -154,11 +178,13 @@ namespace System {
internal static bool TryParseExactMultiple(String s, String[] formats,
- DateTimeFormatInfo dtfi, DateTimeStyles style, out DateTime result) {
+ 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)) {
+ if (TryParseExactMultiple(s, formats, dtfi, style, ref resultData))
+ {
result = resultData.parsedDate;
return true;
}
@@ -166,22 +192,27 @@ namespace System {
}
internal static bool TryParseExactMultiple(String s, String[] formats,
- DateTimeFormatInfo dtfi, DateTimeStyles style, ref DateTimeResult result) {
- if (s == null) {
+ DateTimeFormatInfo dtfi, DateTimeStyles style, ref DateTimeResult result)
+ {
+ if (s == null)
+ {
result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, nameof(s));
return false;
}
- if (formats == null) {
+ if (formats == null)
+ {
result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, nameof(formats));
return false;
}
- if (s.Length == 0) {
+ if (s.Length == 0)
+ {
result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
return false;
}
- if (formats.Length == 0) {
+ if (formats.Length == 0)
+ {
result.SetFailure(ParseFailureKind.Format, "Format_BadFormatSpecifier", null);
return false;
}
@@ -192,8 +223,10 @@ namespace System {
// 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", null);
return false;
}
@@ -201,8 +234,9 @@ namespace System {
// 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)) {
+ innerResult.flags = result.flags;
+ if (TryParseExact(s, formats[i], dtfi, style, ref innerResult))
+ {
result.parsedDate = innerResult.parsedDate;
result.timeZoneOffset = innerResult.timeZoneOffset;
return (true);
@@ -222,37 +256,38 @@ namespace System {
//
////////////////////////////////////////////////////////////////////////////
- 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'
+ 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
+ Unk = 18, // unknown
+ NumLocalTimeMark = 19, // Num + 'T'
+ Max = 20, // marker
}
- internal enum TM {
- NotSet = -1,
- AM = 0,
- PM = 1,
+ internal enum TM
+ {
+ NotSet = -1,
+ AM = 0,
+ PM = 1,
}
@@ -262,61 +297,62 @@ namespace System {
//
////////////////////////////////////////////////////////////////////////////
- internal enum DS {
- BEGIN = 0,
- N = 1, // have one number
- NN = 2, // have two numbers
+ 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
+ // 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_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_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.
+ 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
+ // 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
+ T_Nt = 18, // have num followed by time separator
+ T_NNt = 19, // have two numbers followed by time separator
- ERROR = 20,
+ ERROR = 20,
- // The following are terminal states. These all have an action
- // associated with them; and transition back to BEGIN.
+ // 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_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,
+ 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,
}
////////////////////////////////////////////////////////////////////////////
@@ -329,8 +365,8 @@ namespace System {
//
////////////////////////////////////////////////////////////////////////////
-// End NumEnd NumAmPm NumSpace NumDaySep NumTimesep MonthEnd MonthSpace MonthDSep NumDateSuff NumTimeSuff DayOfWeek YearSpace YearDateSep YearEnd TimeZone Era UTCTimeMark
-private static DS[][] dateParsingStates = {
+ // 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},
@@ -390,9 +426,8 @@ new DS[] { DS.ERROR, DS.TX_NN, DS.TX_NN, DS.TX_NN, DS.ERROR, DS.T_NNt,
// 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
+ // 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";
@@ -403,25 +438,30 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
private static bool MatchWord(ref __DTString str, String target)
{
int length = target.Length;
- if (length > (str.Value.Length - str.Index)) {
+ if (length > (str.Value.Length - str.Index))
+ {
return false;
}
-
+
if (str.CompareInfo.Compare(str.Value, str.Index, length,
- target, 0, length, CompareOptions.IgnoreCase)!=0) {
+ target, 0, length, CompareOptions.IgnoreCase) != 0)
+ {
return (false);
}
int nextCharIndex = str.Index + target.Length;
- if (nextCharIndex < str.Value.Length) {
+ if (nextCharIndex < str.Value.Length)
+ {
char nextCh = str.Value[nextCharIndex];
- if (Char.IsLetter(nextCh)) {
+ if (Char.IsLetter(nextCh))
+ {
return (false);
}
}
str.Index = nextCharIndex;
- if (str.Index < str.len) {
+ if (str.Index < str.len)
+ {
str.m_current = str.Value[str.Index];
}
@@ -434,18 +474,21 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
//
private static bool GetTimeZoneName(ref __DTString str)
{
- if (MatchWord(ref str, GMTName)) {
+ if (MatchWord(ref str, GMTName))
+ {
return (true);
}
- if (MatchWord(ref str, ZuluName)) {
+ if (MatchWord(ref str, ZuluName))
+ {
return (true);
}
return (false);
}
- internal static bool IsDigit(char ch) {
+ internal static bool IsDigit(char ch)
+ {
return (ch >= '0' && ch <= '9');
}
@@ -461,13 +504,15 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
**Exceptions:
============================================================================*/
- private static bool ParseFraction(ref __DTString str, out double result) {
+ 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)) {
+ && IsDigit(ch = str.m_current))
+ {
result += (ch - '0') * decimalBase;
decimalBase *= 0.1;
digits++;
@@ -486,7 +531,8 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
** FormatException if invalid timezone format is found.
============================================================================*/
- private static bool ParseTimeZone(ref __DTString str, ref TimeSpan result) {
+ private static bool ParseTimeZone(ref __DTString str, ref TimeSpan result)
+ {
// The hour/minute offset for timezone.
int hourOffset = 0;
int minuteOffset = 0;
@@ -494,56 +540,66 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
// Consume the +/- character that has already been read
sub = str.GetSubString();
- if (sub.length != 1) {
+ if (sub.length != 1)
+ {
return false;
}
char offsetChar = sub[0];
- if (offsetChar != '+' && offsetChar != '-') {
+ if (offsetChar != '+' && offsetChar != '-')
+ {
return false;
}
str.ConsumeSubString(sub);
sub = str.GetSubString();
- if (sub.type != DTSubStringType.Number) {
+ if (sub.type != DTSubStringType.Number)
+ {
return false;
}
int value = sub.value;
int length = sub.length;
- if (length == 1 || length == 2) {
+ 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] == ':') {
+ 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) {
+ 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) {
+ else if (length == 3 || length == 4)
+ {
// Parsing "+800" or "+0800"
hourOffset = value / 100;
minuteOffset = value % 100;
str.ConsumeSubString(sub);
}
- else {
+ 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) {
+ if (minuteOffset < 0 || minuteOffset >= 60)
+ {
return false;
}
result = new TimeSpan(hourOffset, minuteOffset, 0);
- if (offsetChar == '-') {
+ if (offsetChar == '-')
+ {
result = result.Negate();
}
return true;
@@ -552,38 +608,42 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
// 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)) {
+ 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) {
+ while (Char.IsWhiteSpace(nextCh) && str.Index + whitespaceCount < str.len - 1)
+ {
whitespaceCount++;
nextCh = str.Value[str.Index + whitespaceCount];
}
- if (nextCh == '+' || nextCh == '-') {
+ if (nextCh == '+' || nextCh == '-')
+ {
str.Index += whitespaceCount;
- if ((result.flags & ParseFlags.TimeZoneUsed) != 0) {
+ 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)) {
+ 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;
@@ -602,17 +662,20 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
// COMPlus_LogToConsole=1
// COMPlus_LogLevel=9
// COMPlus_ManagedLogFacility=0x00001000
- if (_tracingEnabled) {
+ 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) {
+ switch (tokenType)
+ {
case TokenType.NumberToken:
case TokenType.YearNumberToken:
- if (raw.numCount == 3 || tokenValue == -1) {
+ if (raw.numCount == 3 || tokenValue == -1)
+ {
result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
LexTraceExit("0010", dps);
return false;
@@ -628,10 +691,13 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
// 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)) {
+ if (dps == DS.T_NNt)
+ {
+ if ((str.Index < str.len - 1))
+ {
char nextCh = str.Value[str.Index];
- if (nextCh == '.') {
+ 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
@@ -640,14 +706,16 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
}
}
}
- if (dps == DS.T_NNt || dps == DS.T_Nt) {
- if ((str.Index < str.len - 1)) {
+ 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;
@@ -661,25 +729,29 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
// we assume this number is a year. Save the currnet raw.numCount in
// raw.year.
//
- switch (sep = str.GetSeparatorToken(dtfi, out indexBeforeSeparator, out charBeforeSeparator)) {
+ switch (sep = str.GetSeparatorToken(dtfi, out indexBeforeSeparator, out charBeforeSeparator))
+ {
case TokenType.SEP_End:
- dtok.dtt = DTT.YearEnd;
+ dtok.dtt = DTT.YearEnd;
break;
case TokenType.SEP_Am:
case TokenType.SEP_Pm:
- if (raw.timeMark == TM.NotSet) {
+ if (raw.timeMark == TM.NotSet)
+ {
raw.timeMark = (sep == TokenType.SEP_Am ? TM.AM : TM.PM);
- dtok.dtt = DTT.YearSpace;
- } else {
+ 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;
+ dtok.dtt = DTT.YearSpace;
break;
case TokenType.SEP_Date:
- dtok.dtt = DTT.YearDateSep;
+ dtok.dtt = DTT.YearDateSep;
break;
case TokenType.SEP_Time:
if (!raw.hasSameDateAndTimeSeparators)
@@ -696,26 +768,28 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
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)) {
+ 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 {
+ else
+ {
dtok.dtt = DTT.YearDateSep;
}
- break;
+ break;
case TokenType.SEP_YearSuff:
case TokenType.SEP_MonthSuff:
case TokenType.SEP_DaySuff:
- dtok.dtt = DTT.NumDatesuff;
+ 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.dtt = DTT.NumTimesuff;
dtok.suffix = sep;
break;
default:
@@ -746,7 +820,8 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
break;
case TokenType.SEP_Am:
case TokenType.SEP_Pm:
- if (raw.timeMark == TM.NotSet) {
+ 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"
@@ -759,11 +834,14 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
}
raw.AddNumber(dtok.num);
- } else {
+ }
+ else
+ {
result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
break;
}
- if (dps == DS.T_NNt || dps == DS.T_Nt) {
+ if (dps == DS.T_NNt || dps == DS.T_Nt)
+ {
if (false == HandleTimeZone(ref str, ref result))
{
LexTraceExit("0070 (HandleTimeZone returned false)", dps);
@@ -782,17 +860,19 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
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)) {
+ 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 {
+ else
+ {
dtok.dtt = DTT.NumDatesep;
}
raw.AddNumber(dtok.num);
- break;
+ 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))
@@ -806,26 +886,28 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
raw.AddNumber(dtok.num);
break;
case TokenType.SEP_YearSuff:
- try {
+ try
+ {
dtok.num = dtfi.Calendar.ToFourDigitYear(tokenValue);
}
- catch (ArgumentOutOfRangeException e) {
+ catch (ArgumentOutOfRangeException e)
+ {
result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", e);
LexTraceExit("0075 (Calendar.ToFourDigitYear failed)", dps);
return false;
- }
- dtok.dtt = DTT.NumDatesuff;
+ }
+ dtok.dtt = DTT.NumDatesuff;
dtok.suffix = sep;
break;
case TokenType.SEP_MonthSuff:
case TokenType.SEP_DaySuff:
- dtok.dtt = DTT.NumDatesuff;
+ 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.dtt = DTT.NumTimesuff;
dtok.suffix = sep;
break;
case TokenType.SEP_LocalTimeMark:
@@ -840,16 +922,19 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
}
break;
case TokenType.HebrewNumber:
- if (tokenValue >= 100) {
+ if (tokenValue >= 100)
+ {
// This is a year number
- if (raw.year == -1) {
+ 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)) {
+ switch (sep = str.GetSeparatorToken(dtfi, out indexBeforeSeparator, out charBeforeSeparator))
+ {
case TokenType.SEP_End:
dtok.dtt = DTT.YearEnd;
break;
@@ -859,7 +944,8 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
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) {
+ if (dateParsingStates[(int)dps][(int)DTT.YearSpace] > DS.ERROR)
+ {
str.Index = indexBeforeSeparator;
str.m_current = charBeforeSeparator;
dtok.dtt = DTT.YearSpace;
@@ -872,18 +958,23 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
LexTraceExit("0090", dps);
return false;
}
- } else {
+ }
+ else
+ {
// Invalid separator after number number.
result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
LexTraceExit("0100", dps);
return false;
}
- } else {
+ }
+ else
+ {
// This is a day number
dtok.num = tokenValue;
raw.AddNumber(dtok.num);
- switch (sep = str.GetSeparatorToken(dtfi, out indexBeforeSeparator, out charBeforeSeparator)) {
+ 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.
@@ -898,13 +989,15 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
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)) {
+ 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 {
+ else
+ {
dtok.dtt = DTT.NumDatesep;
}
break;
@@ -924,7 +1017,9 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
//
raw.dayOfWeek = tokenValue;
dtok.dtt = DTT.DayOfWeek;
- } else {
+ }
+ else
+ {
result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
LexTraceExit("0120 (DayOfWeek seen more than 1x)", dps);
return false;
@@ -936,7 +1031,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
//
// This is a month name
//
- switch(sep=str.GetSeparatorToken(dtfi, out indexBeforeSeparator, out charBeforeSeparator))
+ switch (sep = str.GetSeparatorToken(dtfi, out indexBeforeSeparator, out charBeforeSeparator))
{
case TokenType.SEP_End:
dtok.dtt = DTT.MonthEnd;
@@ -962,13 +1057,15 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
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)) {
+ 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 {
+ else
+ {
dtok.dtt = DTT.MonthDatesep;
}
break;
@@ -979,17 +1076,22 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
return false;
}
raw.month = tokenValue;
- } else {
+ }
+ 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) {
+ if (result.era != -1)
+ {
result.era = tokenValue;
dtok.dtt = DTT.Era;
- } else {
+ }
+ else
+ {
result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
LexTraceExit("0150 (EraToken seen when result.era already set)", dps);
return false;
@@ -999,10 +1101,13 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
// 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) {
+ if (result.era != -1)
+ {
result.era = tokenValue;
dtok.dtt = DTT.Era;
- } else {
+ }
+ else
+ {
result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
LexTraceExit("0160 (JapaneseEraToken seen when result.era already set)", dps);
return false;
@@ -1011,10 +1116,13 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
case TokenType.TEraToken:
result.calendar = TaiwanCalendar.GetDefaultInstance();
dtfi = DateTimeFormatInfo.GetTaiwanCalendarDTFI();
- if (result.era != -1) {
+ if (result.era != -1)
+ {
result.era = tokenValue;
dtok.dtt = DTT.Era;
- } else {
+ }
+ else
+ {
result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
LexTraceExit("0170 (TEraToken seen when result.era already set)", dps);
return false;
@@ -1026,7 +1134,8 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
//
// NOTENOTE : for now, we only support "GMT" and "Z" (for Zulu time).
//
- if ((result.flags & ParseFlags.TimeZoneUsed) != 0) {
+ 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);
@@ -1046,38 +1155,46 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
break;
case TokenType.Am:
case TokenType.Pm:
- if (raw.timeMark == TM.NotSet) {
+ if (raw.timeMark == TM.NotSet)
+ {
raw.timeMark = (TM)tokenValue;
- } else {
+ }
+ 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);
+ 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)) {
+ if ((str.m_current == '-' || str.m_current == '+') && ((result.flags & ParseFlags.TimeZoneUsed) == 0))
+ {
Int32 originalIndex = str.Index;
- if (ParseTimeZone(ref str, ref result.timeZoneOffset)) {
+ if (ParseTimeZone(ref str, ref result.timeZoneOffset))
+ {
result.flags |= ParseFlags.TimeZoneUsed;
LexTraceExit("0220 (success)", dps);
return true;
}
- else {
+ 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)) {
+ if (VerifyValidPunctuation(ref str))
+ {
LexTraceExit("0230 (success)", dps);
return true;
}
@@ -1090,53 +1207,69 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
LexTraceExit("0250 (success)", dps);
return true;
}
-
- private static Boolean VerifyValidPunctuation(ref __DTString str) {
+
+ private static Boolean VerifyValidPunctuation(ref __DTString str)
+ {
// Compatability Behavior. Allow trailing nulls and surrounding hashes
Char ch = str.Value[str.Index];
- if (ch == '#') {
+ if (ch == '#')
+ {
bool foundStart = false;
bool foundEnd = false;
- for (int i = 0; i < str.len; i++) {
+ for (int i = 0; i < str.len; i++)
+ {
ch = str.Value[i];
- if (ch == '#') {
- if (foundStart) {
- if (foundEnd) {
+ if (ch == '#')
+ {
+ if (foundStart)
+ {
+ if (foundEnd)
+ {
// Having more than two hashes is invalid
return false;
}
- else {
+ else
+ {
foundEnd = true;
}
}
- else {
+ else
+ {
foundStart = true;
}
}
- else if (ch == '\0') {
+ else if (ch == '\0')
+ {
// Allow nulls only at the end
- if (!foundEnd) {
+ if (!foundEnd)
+ {
return false;
}
}
- else if ((!Char.IsWhiteSpace(ch))) {
+ else if ((!Char.IsWhiteSpace(ch)))
+ {
// Anthyhing other than whitespace outside hashes is invalid
- if (!foundStart || foundEnd) {
+ if (!foundStart || foundEnd)
+ {
return false;
}
}
}
- if (!foundEnd) {
+ if (!foundEnd)
+ {
// The has was un-paired
return false;
}
// Valid Hash usage: eat the hash and continue.
- str.GetNext();
- return true;
+ str.GetNext();
+ return true;
}
- else if (ch == '\0') {
- for (int i = str.Index; i < str.len; i++) {
- if (str.Value[i] != '\0') {
+ 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;
}
@@ -1145,17 +1278,17 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
str.Index = str.len;
return true;
}
- return false;
+ 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.
+ 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.
@@ -1164,10 +1297,10 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
//
private static Boolean GetYearMonthDayOrder(String datePattern, DateTimeFormatInfo dtfi, out int order)
{
- int yearOrder = -1;
- int monthOrder = -1;
- int dayOrder = -1;
- int orderCount = 0;
+ int yearOrder = -1;
+ int monthOrder = -1;
+ int dayOrder = -1;
+ int orderCount = 0;
bool inQuote = false;
@@ -1194,7 +1327,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
//
// Skip all year pattern charaters.
//
- for(; i+1 < datePattern.Length && datePattern[i+1] == 'y'; i++)
+ for (; i + 1 < datePattern.Length && datePattern[i + 1] == 'y'; i++)
{
// Do nothing here.
}
@@ -1205,19 +1338,18 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
//
// Skip all month pattern characters.
//
- for(; i+1 < datePattern.Length && datePattern[i+1] == 'M'; i++)
+ 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++)
+ for (; i + 1 < datePattern.Length && datePattern[i + 1] == 'd'; i++)
{
patternCount++;
}
@@ -1263,9 +1395,9 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
//
private static Boolean GetYearMonthOrder(String pattern, DateTimeFormatInfo dtfi, out int order)
{
- int yearOrder = -1;
- int monthOrder = -1;
- int orderCount = 0;
+ int yearOrder = -1;
+ int monthOrder = -1;
+ int orderCount = 0;
bool inQuote = false;
for (int i = 0; i < pattern.Length && orderCount < 2; i++)
@@ -1291,7 +1423,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
//
// Skip all year pattern charaters.
//
- for(; i+1 < pattern.Length && pattern[i+1] == 'y'; i++)
+ for (; i + 1 < pattern.Length && pattern[i + 1] == 'y'; i++)
{
}
}
@@ -1301,7 +1433,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
//
// Skip all month pattern characters.
//
- for(; i+1 < pattern.Length && pattern[i+1] == 'M'; i++)
+ for (; i + 1 < pattern.Length && pattern[i + 1] == 'M'; i++)
{
}
}
@@ -1329,9 +1461,9 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
//
private static Boolean GetMonthDayOrder(String pattern, DateTimeFormatInfo dtfi, out int order)
{
- int monthOrder = -1;
- int dayOrder = -1;
- int orderCount = 0;
+ int monthOrder = -1;
+ int dayOrder = -1;
+ int orderCount = 0;
bool inQuote = false;
for (int i = 0; i < pattern.Length && orderCount < 2; i++)
@@ -1356,7 +1488,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
//
// Skip all day pattern charaters.
//
- for(; i+1 < pattern.Length && pattern[i+1] == 'd'; i++)
+ for (; i + 1 < pattern.Length && pattern[i + 1] == 'd'; i++)
{
patternCount++;
}
@@ -1368,7 +1500,6 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
{
dayOrder = orderCount++;
}
-
}
else if (ch == 'M')
{
@@ -1376,7 +1507,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
//
// Skip all month pattern characters.
//
- for(; i+1 < pattern.Length && pattern[i+1] == 'M'; i++)
+ for (; i + 1 < pattern.Length && pattern[i + 1] == 'M'; i++)
{
}
}
@@ -1404,17 +1535,19 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
{
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;
- }
+ 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;
@@ -1424,7 +1557,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
{
// 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))
+ if (result.calendar.IsValidDay(year, month, day, result.era))
{
result.SetDate(year, month, day); // YMD
return (true);
@@ -1446,16 +1579,18 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
{
return (SetDateYMD(ref result, year, month, day));
}
-
- private static void GetDefaultYear(ref DateTimeResult result, ref DateTimeStyles styles) {
+
+ 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) {
+ 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;
@@ -1467,7 +1602,8 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
GetDefaultYear(ref result, ref styles);
int order;
- if (!GetMonthDayOrder(dtfi.MonthDayPattern, dtfi, out order)) {
+ if (!GetMonthDayOrder(dtfi.MonthDayPattern, dtfi, out order))
+ {
result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_BadDatePattern", dtfi.MonthDayPattern);
return false;
}
@@ -1479,7 +1615,9 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
result.flags |= ParseFlags.HaveDate;
return true;
}
- } else {
+ }
+ else
+ {
// ORDER_DM
if (SetDateYMD(ref result, result.Year, n2, n1)) // DM
{
@@ -1494,42 +1632,51 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
// Processing teriminal case: DS.DX_NNN
private static Boolean GetDayOfNNN(ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi)
{
- if ((result.flags & ParseFlags.HaveDate) != 0) {
+ 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 n2 = raw.GetNumber(1); ;
int n3 = raw.GetNumber(2);
int order;
- if (!GetYearMonthDayOrder(dtfi.ShortDatePattern, dtfi, out 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 (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) {
+ }
+ 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) {
+ }
+ 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) {
+ }
+ else if (order == ORDER_YDM)
+ {
if (TryAdjustYear(ref result, n1, out year) && SetDateYDM(ref result, year, n2, n3)) // YDM
{
result.flags |= ParseFlags.HaveDate;
@@ -1540,9 +1687,10 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
return false;
}
- private static Boolean GetDayOfMN(ref DateTimeResult result, ref DateTimeStyles styles, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi) {
-
- if ((result.flags & ParseFlags.HaveDate) != 0) {
+ 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;
@@ -1561,19 +1709,24 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
// than a 2 digit year.
int monthDayOrder;
- if (!GetMonthDayOrder(dtfi.MonthDayPattern, dtfi, out monthDayOrder)) {
+ if (!GetMonthDayOrder(dtfi.MonthDayPattern, dtfi, out monthDayOrder))
+ {
result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_BadDatePattern", dtfi.MonthDayPattern);
return false;
}
- if (monthDayOrder == ORDER_DM) {
+ if (monthDayOrder == ORDER_DM)
+ {
int yearMonthOrder;
- if (!GetYearMonthOrder(dtfi.YearMonthPattern, dtfi, out yearMonthOrder)) {
+ if (!GetYearMonthOrder(dtfi.YearMonthPattern, dtfi, out yearMonthOrder))
+ {
result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_BadDatePattern", dtfi.YearMonthPattern);
return false;
}
- if (yearMonthOrder == ORDER_MY) {
+ if (yearMonthOrder == ORDER_MY)
+ {
int year;
- if (!TryAdjustYear(ref result, raw.GetNumber(0), out year) || !SetDateYMD(ref result, year, raw.month, 1)) {
+ 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;
}
@@ -1581,13 +1734,13 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
}
}
- GetDefaultYear(ref result, ref styles);
- if (!SetDateYMD(ref result, result.Year, raw.month, raw.GetNumber(0))) {
+ 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;
-
}
////////////////////////////////////////////////////////////////////////
@@ -1599,7 +1752,8 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
private static Boolean GetHebrewDayOfNM(ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi)
{
int monthDayOrder;
- if (!GetMonthDayOrder(dtfi.MonthDayPattern, dtfi, out monthDayOrder)) {
+ if (!GetMonthDayOrder(dtfi.MonthDayPattern, dtfi, out monthDayOrder))
+ {
result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_BadDatePattern", dtfi.MonthDayPattern);
return false;
}
@@ -1608,7 +1762,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
{
if (result.calendar.IsValidDay(result.Year, result.Month, raw.GetNumber(0), result.era))
{
- result.Day = raw.GetNumber(0);
+ result.Day = raw.GetNumber(0);
return true;
}
}
@@ -1618,7 +1772,8 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
private static Boolean GetDayOfNM(ref DateTimeResult result, ref DateTimeStyles styles, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi)
{
- if ((result.flags & ParseFlags.HaveDate) != 0) {
+ if ((result.flags & ParseFlags.HaveDate) != 0)
+ {
// Multiple dates in the input string
result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
return false;
@@ -1637,19 +1792,24 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
// than a 2 digit year.
int monthDayOrder;
- if (!GetMonthDayOrder(dtfi.MonthDayPattern, dtfi, out monthDayOrder)) {
+ if (!GetMonthDayOrder(dtfi.MonthDayPattern, dtfi, out monthDayOrder))
+ {
result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_BadDatePattern", dtfi.MonthDayPattern);
return false;
}
- if (monthDayOrder == ORDER_MD) {
+ if (monthDayOrder == ORDER_MD)
+ {
int yearMonthOrder;
- if (!GetYearMonthOrder(dtfi.YearMonthPattern, dtfi, out yearMonthOrder)) {
+ if (!GetYearMonthOrder(dtfi.YearMonthPattern, dtfi, out yearMonthOrder))
+ {
result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_BadDatePattern", dtfi.YearMonthPattern);
return false;
}
- if (yearMonthOrder == ORDER_YM) {
+ if (yearMonthOrder == ORDER_YM)
+ {
int year;
- if (!TryAdjustYear(ref result, raw.GetNumber(0), out year) || !SetDateYMD(ref result, year, raw.month, 1)) {
+ 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;
}
@@ -1658,7 +1818,8 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
}
GetDefaultYear(ref result, ref styles);
- if (!SetDateYMD(ref result, result.Year, raw.month, raw.GetNumber(0))) {
+ if (!SetDateYMD(ref result, result.Year, raw.month, raw.GetNumber(0)))
+ {
result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
return false;
}
@@ -1667,7 +1828,8 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
private static Boolean GetDayOfMNN(ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi)
{
- if ((result.flags & ParseFlags.HaveDate) != 0) {
+ if ((result.flags & ParseFlags.HaveDate) != 0)
+ {
// Multiple dates in the input string
result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
return false;
@@ -1677,7 +1839,8 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
int n2 = raw.GetNumber(1);
int order;
- if (!GetYearMonthDayOrder(dtfi.ShortDatePattern, dtfi, out order)) {
+ if (!GetYearMonthDayOrder(dtfi.ShortDatePattern, dtfi, out order))
+ {
result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_BadDatePattern", dtfi.ShortDatePattern);
return false;
}
@@ -1733,9 +1896,10 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
return false;
}
- private static Boolean GetDayOfYNN(ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi) {
-
- if ((result.flags & ParseFlags.HaveDate) != 0) {
+ 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;
@@ -1747,14 +1911,18 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
// 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)) {
+ 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)) {
+ else
+ {
+ if (SetDateYMD(ref result, raw.year, n1, n2))
+ {
result.flags |= ParseFlags.HaveDate;
return true; // Year + MD
}
@@ -1763,9 +1931,10 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
return false;
}
- private static Boolean GetDayOfNNY(ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi) {
-
- if ((result.flags & ParseFlags.HaveDate) != 0) {
+ 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;
@@ -1775,18 +1944,24 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
int n2 = raw.GetNumber(1);
int order;
- if (!GetYearMonthDayOrder(dtfi.ShortDatePattern, dtfi, out 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)) {
+ 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)) {
+ }
+ else
+ {
+ if (SetDateYMD(ref result, raw.year, n2, n1))
+ {
result.flags |= ParseFlags.HaveDate;
return true; // DM + Year
}
@@ -1796,15 +1971,17 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
}
- private static Boolean GetDayOfYMN(ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi) {
-
- if ((result.flags & ParseFlags.HaveDate) != 0) {
+ 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))) {
+ if (SetDateYMD(ref result, raw.year, raw.month, raw.GetNumber(0)))
+ {
result.flags |= ParseFlags.HaveDate;
return true;
}
@@ -1814,7 +1991,8 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
private static Boolean GetDayOfYN(ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi)
{
- if ((result.flags & ParseFlags.HaveDate) != 0) {
+ if ((result.flags & ParseFlags.HaveDate) != 0)
+ {
// Multiple dates in the input string
result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
return false;
@@ -1831,7 +2009,8 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
private static Boolean GetDayOfYM(ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi)
{
- if ((result.flags & ParseFlags.HaveDate) != 0) {
+ if ((result.flags & ParseFlags.HaveDate) != 0)
+ {
// Multiple dates in the input string
result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
return false;
@@ -1846,19 +2025,24 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
return false;
}
- private static void AdjustTimeMark(DateTimeFormatInfo dtfi, ref DateTimeRawInfo raw) {
+ 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) {
+ 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) {
+ if (dtfi.PMDesignator.Length == 0 && dtfi.AMDesignator.Length != 0)
+ {
raw.timeMark = TM.PM;
}
}
@@ -1868,20 +2052,26 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
//
// 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) {
+ 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) {
+ else
+ {
+ if (hour < 0 || hour > 23)
+ {
return false;
}
- if (hour < 12) {
+ if (hour < 12)
+ {
hour += 12;
}
}
@@ -1891,7 +2081,8 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
private static Boolean GetTimeOfN(DateTimeFormatInfo dtfi, ref DateTimeResult result, ref DateTimeRawInfo raw)
{
- if ((result.flags & ParseFlags.HaveTime) != 0) {
+ if ((result.flags & ParseFlags.HaveTime) != 0)
+ {
// Multiple times in the input string
result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
return false;
@@ -1912,29 +2103,31 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
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) {
+ 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.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) {
+ 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.Minute = raw.GetNumber(1);
+ result.Second = raw.GetNumber(2);
result.flags |= ParseFlags.HaveTime;
return true;
}
@@ -1971,7 +2164,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
{
// the year value is out of range
result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
+ return false;
}
result.Day = 1;
return true;
@@ -1979,33 +2172,42 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
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))) {
+ 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)) {
+ 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)) {
+ 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))) {
+ 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))){
+ else
+ {
+ if (TryAdjustYear(ref result, raw.GetNumber(1), out year) && SetDateYMD(ref result, year, result.Month, raw.GetNumber(0)))
+ {
return true;
}
}
@@ -2023,42 +2225,48 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
switch (dtok.suffix)
{
case TokenType.SEP_YearSuff:
- if ((result.flags & ParseFlags.HaveYear) != 0) {
+ 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) {
+ if ((result.flags & ParseFlags.HaveMonth) != 0)
+ {
return false;
}
result.flags |= ParseFlags.HaveMonth;
- result.Month= raw.month = dtok.num;
+ result.Month = raw.month = dtok.num;
break;
case TokenType.SEP_DaySuff:
- if ((result.flags & ParseFlags.HaveDay) != 0) {
+ if ((result.flags & ParseFlags.HaveDay) != 0)
+ {
return false;
}
result.flags |= ParseFlags.HaveDay;
- result.Day = dtok.num;
+ result.Day = dtok.num;
break;
case TokenType.SEP_HourSuff:
- if ((result.flags & ParseFlags.HaveHour) != 0) {
+ 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) {
+ 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) {
+ if ((result.flags & ParseFlags.HaveSecond) != 0)
+ {
return false;
}
result.flags |= ParseFlags.HaveSecond;
@@ -2066,7 +2274,6 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
break;
}
return true;
-
}
////////////////////////////////////////////////////////////////////////
@@ -2077,27 +2284,33 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
//
////////////////////////////////////////////////////////////////////////
- internal static Boolean ProcessHebrewTerminalState(DS dps, ref DateTimeResult result, ref DateTimeStyles styles, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi) {
+ 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) {
+ 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)) {
+ 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)) {
+ 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)) {
+ 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)) {
+ if (!GetDayOfYMN(ref result, ref raw, dtfi))
+ {
return false;
}
break;
@@ -2105,44 +2318,50 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
case DS.DX_MN:
// Deal with Month/Day pattern.
GetDefaultYear(ref result, ref styles);
- if (!dtfi.YearMonthAdjustment(ref result.Year, ref raw.month, true)) {
+ 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)) {
+ 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)) {
+ 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)) {
+ 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)) {
+ if (!GetTimeOfN(dtfi, ref result, ref raw))
+ {
return false;
}
break;
case DS.TX_NN:
- if (!GetTimeOfNN(dtfi, ref result, ref raw)) {
+ if (!GetTimeOfNN(dtfi, ref result, ref raw))
+ {
return false;
}
break;
case DS.TX_NNN:
- if (!GetTimeOfNNN(dtfi, ref result, ref raw)) {
+ if (!GetTimeOfNNN(dtfi, ref result, ref raw))
+ {
return false;
}
break;
default:
result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
return false;
-
}
if (dps > DS.ERROR)
{
@@ -2160,7 +2379,6 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
//
internal static Boolean ProcessTerminaltState(DS dps, ref DateTimeResult result, ref DateTimeStyles styles, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi)
{
-
bool passed = true;
switch (dps)
{
@@ -2223,7 +2441,8 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
}
PTSTraceExit(dps, passed);
- if (!passed) {
+ if (!passed)
+ {
return false;
}
@@ -2237,49 +2456,59 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
return true;
}
- internal static DateTime Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles) {
+ 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)) {
+ if (TryParse(s, dtfi, styles, ref result))
+ {
return result.parsedDate;
}
- else {
+ else
+ {
throw GetDateTimeParseException(ref result);
}
}
- internal static DateTime Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles, out TimeSpan offset) {
+ 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)) {
+ if (TryParse(s, dtfi, styles, ref result))
+ {
offset = result.timeZoneOffset;
return result.parsedDate;
}
- else {
+ else
+ {
throw GetDateTimeParseException(ref result);
}
}
- internal static bool TryParse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles, out DateTime 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)) {
+ 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) {
+
+ 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)) {
+ if (TryParse(s, dtfi, styles, ref parseResult))
+ {
result = parseResult.parsedDate;
offset = parseResult.timeZoneOffset;
return true;
@@ -2287,16 +2516,19 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
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) {
+ 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) {
+ if (s.Length == 0)
+ {
result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
return false;
}
@@ -2312,14 +2544,15 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
// First try the predefined format.
//
- DS dps = DS.BEGIN; // Date Parsing State.
+ DS dps = DS.BEGIN; // Date Parsing State.
bool reachTerminalState = false;
- DateTimeToken dtok = new DateTimeToken(); // The buffer to store the parsing token.
+ 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];
+ 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);
@@ -2338,7 +2571,8 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
//
// The following loop will break out when we reach the end of the str.
//
- do {
+ do
+ {
//
// Call the lexer to get the next token.
//
@@ -2362,7 +2596,8 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
//
if (dtok.suffix != TokenType.SEP_Unk)
{
- if (!ProcessDateTimeSuffix(ref result, ref raw, ref dtok)) {
+ if (!ProcessDateTimeSuffix(ref result, ref raw, ref dtok))
+ {
result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
TPTraceExit("0010", dps);
return false;
@@ -2371,14 +2606,17 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
dtok.suffix = TokenType.SEP_Unk; // Reset suffix to SEP_Unk;
}
- if (dtok.dtt == DTT.NumLocalTimeMark) {
- if (dps == DS.D_YNd || dps == DS.D_YN) {
+ 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 {
+ else
+ {
result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
TPTraceExit("0030", dps);
return false;
@@ -2421,7 +2659,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
// 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);
@@ -2430,13 +2668,18 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
}
else if (dps > DS.ERROR)
{
- if ((dtfi.FormatFlags & DateTimeFormatFlags.UseHebrewRule) != 0) {
- if (!ProcessHebrewTerminalState(dps, ref result, ref styles, ref raw, dtfi)) {
+ 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)) {
+ }
+ else
+ {
+ if (!ProcessTerminaltState(dps, ref result, ref styles, ref raw, dtfi))
+ {
TPTraceExit("0060 (ProcessTerminaltState)", dps);
return false;
}
@@ -2453,14 +2696,16 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
}
} while (dtok.dtt != DTT.End && dtok.dtt != DTT.NumEnd && dtok.dtt != DTT.MonthEnd);
- if (!reachTerminalState) {
+ 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)) {
+ if (!AdjustHour(ref result.Hour, raw.timeMark))
+ {
result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
TPTraceExit("0080 (AdjustHour)", dps);
return false;
@@ -2473,18 +2718,21 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
// 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)) {
+ 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.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) {
+ if (raw.fraction > 0)
+ {
time = time.AddTicks((long)Math.Round(raw.fraction * Calendar.TicksPerSecond));
}
@@ -2492,11 +2740,13 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
// 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) {
+ if (raw.dayOfWeek != -1)
+ {
//
// Check if day of week is correct.
//
- if (raw.dayOfWeek != (int)result.calendar.GetDayOfWeek(time)) {
+ if (raw.dayOfWeek != (int)result.calendar.GetDayOfWeek(time))
+ {
result.SetFailure(ParseFailureKind.Format, "Format_BadDayOfWeek", null);
TPTraceExit("0110 (dayOfWeek check)", dps);
return false;
@@ -2505,7 +2755,8 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
result.parsedDate = time;
- if (!DetermineTimeZoneAdjustments(ref result, styles, bTimeOnly)) {
+ if (!DetermineTimeZoneAdjustments(ref result, styles, bTimeOnly))
+ {
TPTraceExit("0120 (DetermineTimeZoneAdjustments)", dps);
return false;
}
@@ -2515,26 +2766,29 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
// 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) {
+ 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 {
+ else
+ {
Int64 offsetTicks = result.timeZoneOffset.Ticks;
// the DateTime offset must be within +- 14:00 hours.
- if (offsetTicks < DateTimeOffset.MinOffset || offsetTicks > DateTimeOffset.MaxOffset) {
+ 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 ((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
@@ -2542,83 +2796,99 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
// 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) {
+ if ((styles & DateTimeStyles.AssumeLocal) != 0)
+ {
+ if ((styles & DateTimeStyles.AdjustToUniversal) != 0)
+ {
result.flags |= ParseFlags.TimeZoneUsed;
result.timeZoneOffset = TimeZoneInfo.GetLocalUtcOffset(result.parsedDate, TimeZoneInfoOptions.NoThrowOnInvalidTime);
}
- else {
+ else
+ {
result.parsedDate = DateTime.SpecifyKind(result.parsedDate, DateTimeKind.Local);
return true;
}
}
- else if ((styles & DateTimeStyles.AssumeUniversal) != 0) {
- if ((styles & DateTimeStyles.AdjustToUniversal) != 0) {
+ else if ((styles & DateTimeStyles.AssumeUniversal) != 0)
+ {
+ if ((styles & DateTimeStyles.AdjustToUniversal) != 0)
+ {
result.parsedDate = DateTime.SpecifyKind(result.parsedDate, DateTimeKind.Utc);
return true;
}
- else {
+ else
+ {
result.flags |= ParseFlags.TimeZoneUsed;
result.timeZoneOffset = TimeSpan.Zero;
}
}
- else {
+ 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)) {
+ 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) {
+ 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) {
-
+ 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) {
+ 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 {
+ 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) {
+ 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) {
+ 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)) {
+ 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;
@@ -2630,10 +2900,10 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
result.parsedDate = new DateTime(utcTicks, DateTimeKind.Utc);
result.timeZoneOffset = TimeSpan.Zero;
}
-
- return true;
+
+ return true;
}
-
+
//
// Adjust the specified time to universal time based on the supplied timezone.
@@ -2641,14 +2911,17 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
// 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) {
+ private static Boolean AdjustTimeZoneToUniversal(ref DateTimeResult result)
+ {
long resultTicks = result.parsedDate.Ticks;
resultTicks -= result.timeZoneOffset.Ticks;
- if (resultTicks < 0) {
+ if (resultTicks < 0)
+ {
resultTicks += Calendar.TicksPerDay;
}
- if (resultTicks < DateTime.MinTicks || resultTicks > DateTime.MaxTicks) {
+ if (resultTicks < DateTime.MinTicks || resultTicks > DateTime.MaxTicks)
+ {
result.SetFailure(ParseFailureKind.Format, "Format_DateOutOfRange", null);
return false;
}
@@ -2663,12 +2936,14 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
// 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) {
+ 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) {
+ if (resultTicks < Calendar.TicksPerDay)
+ {
//
// This is time of day.
//
@@ -2676,26 +2951,33 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
// 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;
+ resultTicks += tz.GetUtcOffset(bTimeOnly ? DateTime.Now : result.parsedDate, TimeZoneInfoOptions.NoThrowOnInvalidTime).Ticks;
- if (resultTicks < 0) {
+ if (resultTicks < 0)
+ {
resultTicks += Calendar.TicksPerDay;
}
- } else {
+ }
+ else
+ {
// Adjust timezone to GMT.
resultTicks -= result.timeZoneOffset.Ticks;
- if (resultTicks < DateTime.MinTicks || resultTicks > DateTime.MaxTicks) {
+ 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 {
+ }
+ 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) {
+ if (resultTicks < DateTime.MinTicks || resultTicks > DateTime.MaxTicks)
+ {
result.parsedDate = DateTime.MinValue;
result.SetFailure(ParseFailureKind.Format, "Format_DateOutOfRange", null);
return false;
@@ -2708,8 +2990,10 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
// 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) {
+ 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;
@@ -2717,29 +3001,36 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
double partSecond = 0;
str.SkipWhiteSpaces();
- if (!ParseDigits(ref str, 2, out hour)) {
+ if (!ParseDigits(ref str, 2, out hour))
+ {
result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
return false;
}
str.SkipWhiteSpaces();
- if (!str.Match(':')) {
+ if (!str.Match(':'))
+ {
result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
return false;
}
str.SkipWhiteSpaces();
- if (!ParseDigits(ref str, 2, out minute)) {
+ if (!ParseDigits(ref str, 2, out minute))
+ {
result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
return false;
}
str.SkipWhiteSpaces();
- if (str.Match(':')) {
+ if (str.Match(':'))
+ {
str.SkipWhiteSpaces();
- if (!ParseDigits(ref str, 2, out second)) {
+ 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)) {
+ if (str.Match('.'))
+ {
+ if (!ParseFraction(ref str, out partSecond))
+ {
result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
return false;
}
@@ -2747,36 +3038,48 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
}
str.SkipWhiteSpaces();
}
- if (str.GetNext()) {
+ if (str.GetNext())
+ {
char ch = str.GetChar();
- if (ch == '+' || ch == '-') {
+ if (ch == '+' || ch == '-')
+ {
result.flags |= ParseFlags.TimeZoneUsed;
- if (!ParseTimeZone(ref str, ref result.timeZoneOffset)) {
+ if (!ParseTimeZone(ref str, ref result.timeZoneOffset))
+ {
result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
return false;
}
- } else if (ch == 'Z' || ch == 'z') {
+ }
+ else if (ch == 'Z' || ch == 'z')
+ {
result.flags |= ParseFlags.TimeZoneUsed;
result.timeZoneOffset = TimeSpan.Zero;
result.flags |= ParseFlags.TimeZoneUtc;
- } else {
+ }
+ else
+ {
str.Index--;
}
str.SkipWhiteSpaces();
- if (str.Match('#')) {
- if (!VerifyValidPunctuation(ref str)) {
+ if (str.Match('#'))
+ {
+ if (!VerifyValidPunctuation(ref str))
+ {
result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
+ return false;
}
str.SkipWhiteSpaces();
}
- if (str.Match('\0')) {
- if (!VerifyValidPunctuation(ref str)) {
+ if (str.Match('\0'))
+ {
+ if (!VerifyValidPunctuation(ref str))
+ {
result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
+ return false;
}
}
- if (str.GetNext()) {
+ 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;
@@ -2786,14 +3089,16 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
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)) {
+ 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)) {
+ if (!DetermineTimeZoneAdjustments(ref result, styles, false))
+ {
return false;
}
return true;
@@ -2808,7 +3113,8 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
//
////////////////////////////////////////////////////////////////////////
- internal static bool MatchHebrewDigits(ref __DTString str, int digitLen, out int number) {
+ 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.
@@ -2817,11 +3123,13 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
// 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()) {
+ while (state == HebrewNumberParsingState.ContinueParsing && str.GetNext())
+ {
state = HebrewNumber.ParseByChar(str.GetChar(), ref context);
}
- if (state == HebrewNumberParsingState.FoundEndOfHebrewNumber) {
+ if (state == HebrewNumberParsingState.FoundEndOfHebrewNumber)
+ {
// If we have reached a terminal state, update the result and returns.
number = context.result;
return (true);
@@ -2843,32 +3151,39 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
**Exceptions: FormatException if error in parsing number.
==============================================================================*/
- internal static bool ParseDigits(ref __DTString str, int digitLen, out int result) {
- if (digitLen == 1) {
+ 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 {
+ else
+ {
return ParseDigits(ref str, digitLen, digitLen, out result);
}
}
- internal static bool ParseDigits(ref __DTString str, int minDigitLen, int maxDigitLen, out int 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()) {
+ while (tokenLength < maxDigitLen)
+ {
+ if (!str.GetNextDigit())
+ {
str.Index--;
break;
}
result = result * 10 + str.GetDigit();
tokenLength++;
}
- if (tokenLength < minDigitLen) {
+ if (tokenLength < minDigitLen)
+ {
str.Index = startingIndex;
return false;
}
@@ -2885,16 +3200,20 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
**Exceptions: FormatException if error in parsing number.
==============================================================================*/
- private static bool ParseFractionExact(ref __DTString str, int maxDigitLen, ref double result) {
- if (!str.GetNextDigit()) {
+ 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()) {
+ for (; digitLen < maxDigitLen; digitLen++)
+ {
+ if (!str.GetNextDigit())
+ {
str.Index--;
break;
}
@@ -2914,16 +3233,21 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
** symbol is not found.
==============================================================================*/
- private static bool ParseSign(ref __DTString str, ref bool result) {
- if (!str.GetNext()) {
+ 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 == '+') {
+ if (ch == '+')
+ {
result = true;
return (true);
- } else if (ch == '-') {
+ }
+ else if (ch == '-')
+ {
result = false;
return (true);
}
@@ -2940,51 +3264,64 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
**Exceptions: FormatException if errors in parsing.
==============================================================================*/
- private static bool ParseTimeZoneOffset(ref __DTString str, int len, ref TimeSpan result) {
+ private static bool ParseTimeZoneOffset(ref __DTString str, int len, ref TimeSpan result)
+ {
bool isPositive = true;
int hourOffset;
int minuteOffset = 0;
- switch (len) {
+ switch (len)
+ {
case 1:
case 2:
- if (!ParseSign(ref str, ref isPositive)) {
+ if (!ParseSign(ref str, ref isPositive))
+ {
return (false);
}
- if (!ParseDigits(ref str, len, out hourOffset)) {
+ if (!ParseDigits(ref str, len, out hourOffset))
+ {
return (false);
}
break;
default:
- if (!ParseSign(ref str, ref isPositive)) {
+ if (!ParseSign(ref str, ref isPositive))
+ {
return (false);
}
// Parsing 1 digit will actually parse 1 or 2.
- if (!ParseDigits(ref str, 1, out hourOffset)) {
+ if (!ParseDigits(ref str, 1, out hourOffset))
+ {
return (false);
}
// ':' is optional.
- if (str.Match(":")) {
+ if (str.Match(":"))
+ {
// Found ':'
- if (!ParseDigits(ref str, 2, out minuteOffset)) {
+ if (!ParseDigits(ref str, 2, out minuteOffset))
+ {
return (false);
}
- } else {
+ }
+ else
+ {
// Since we can not match ':', put the char back.
str.Index--;
- if (!ParseDigits(ref str, 2, out minuteOffset)) {
+ if (!ParseDigits(ref str, 2, out minuteOffset))
+ {
return (false);
}
}
break;
}
- if (minuteOffset < 0 || minuteOffset >= 60) {
+ if (minuteOffset < 0 || minuteOffset >= 60)
+ {
return false;
}
result = (new TimeSpan(hourOffset, minuteOffset, 0));
- if (!isPositive) {
+ if (!isPositive)
+ {
result = result.Negate();
}
return (true);
@@ -2998,24 +3335,29 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
**Exceptions: FormatException if an abbreviated month name can not be found.
==============================================================================*/
- private static bool MatchAbbreviatedMonthName(ref __DTString str, DateTimeFormatInfo dtfi, ref int result) {
+ private static bool MatchAbbreviatedMonthName(ref __DTString str, DateTimeFormatInfo dtfi, ref int result)
+ {
int maxMatchStrLen = 0;
result = -1;
- if (str.GetNext()) {
+ 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++) {
+ 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
+ if (dtfi.HasSpacesInMonthNames
? str.MatchSpecifiedWords(searchStr, false, ref matchStrLen)
- : str.MatchSpecifiedWord(searchStr)) {
- if (matchStrLen > maxMatchStrLen) {
+ : str.MatchSpecifiedWord(searchStr))
+ {
+ if (matchStrLen > maxMatchStrLen)
+ {
maxMatchStrLen = matchStrLen;
result = i;
}
@@ -3023,19 +3365,20 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
}
// Search leap year form.
- if ((dtfi.FormatFlags & DateTimeFormatFlags.UseLeapYearMonth) != 0) {
+ 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) {
+ if (tempResult >= 0)
+ {
result = tempResult + 1;
}
}
-
-
}
- if (result > 0) {
+ if (result > 0)
+ {
str.Index += (maxMatchStrLen - 1);
return (true);
}
@@ -3050,24 +3393,29 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
**Exceptions: FormatException if a month name can not be found.
==============================================================================*/
- private static bool MatchMonthName(ref __DTString str, DateTimeFormatInfo dtfi, ref int result) {
+ private static bool MatchMonthName(ref __DTString str, DateTimeFormatInfo dtfi, ref int result)
+ {
int maxMatchStrLen = 0;
result = -1;
- if (str.GetNext()) {
+ 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++) {
+ 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
+ if (dtfi.HasSpacesInMonthNames
? str.MatchSpecifiedWords(searchStr, false, ref matchStrLen)
- : str.MatchSpecifiedWord(searchStr)) {
- if (matchStrLen > maxMatchStrLen) {
+ : str.MatchSpecifiedWord(searchStr))
+ {
+ if (matchStrLen > maxMatchStrLen)
+ {
maxMatchStrLen = matchStrLen;
result = i;
}
@@ -3075,31 +3423,34 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
}
// Search genitive form.
- if ((dtfi.FormatFlags & DateTimeFormatFlags.UseGenitiveMonth) != 0) {
+ 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) {
+ if (tempResult >= 0)
+ {
result = tempResult + 1;
}
}
// Search leap year form.
- if ((dtfi.FormatFlags & DateTimeFormatFlags.UseLeapYearMonth) != 0) {
+ 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) {
+ if (tempResult >= 0)
+ {
result = tempResult + 1;
}
}
-
-
}
- if (result > 0) {
+ if (result > 0)
+ {
str.Index += (maxMatchStrLen - 1);
return (true);
}
@@ -3114,24 +3465,30 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
**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) {
+ 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++) {
+ if (str.GetNext())
+ {
+ for (DayOfWeek i = DayOfWeek.Sunday; i <= DayOfWeek.Saturday; i++)
+ {
String searchStr = dtfi.GetAbbreviatedDayName(i);
int matchStrLen = searchStr.Length;
- if ( dtfi.HasSpacesInDayNames
+ if (dtfi.HasSpacesInDayNames
? str.MatchSpecifiedWords(searchStr, false, ref matchStrLen)
- : str.MatchSpecifiedWord(searchStr)) {
- if (matchStrLen > maxMatchStrLen) {
+ : str.MatchSpecifiedWord(searchStr))
+ {
+ if (matchStrLen > maxMatchStrLen)
+ {
maxMatchStrLen = matchStrLen;
result = (int)i;
}
}
}
}
- if (result >= 0) {
+ if (result >= 0)
+ {
str.Index += maxMatchStrLen - 1;
return (true);
}
@@ -3146,25 +3503,31 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
**Exceptions: FormatException if a day of week name can not be found.
==============================================================================*/
- private static bool MatchDayName(ref __DTString str, DateTimeFormatInfo dtfi, ref int result) {
+ 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++) {
+ if (str.GetNext())
+ {
+ for (DayOfWeek i = DayOfWeek.Sunday; i <= DayOfWeek.Saturday; i++)
+ {
String searchStr = dtfi.GetDayName(i);
int matchStrLen = searchStr.Length;
- if ( dtfi.HasSpacesInDayNames
+ if (dtfi.HasSpacesInDayNames
? str.MatchSpecifiedWords(searchStr, false, ref matchStrLen)
- : str.MatchSpecifiedWord(searchStr)) {
- if (matchStrLen > maxMatchStrLen) {
+ : str.MatchSpecifiedWord(searchStr))
+ {
+ if (matchStrLen > maxMatchStrLen)
+ {
maxMatchStrLen = matchStrLen;
result = (int)i;
}
}
}
}
- if (result >= 0) {
+ if (result >= 0)
+ {
str.Index += maxMatchStrLen - 1;
return (true);
}
@@ -3179,20 +3542,26 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
**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()) {
+ 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++) {
+ if (eras != null)
+ {
+ for (int i = 0; i < eras.Length; i++)
+ {
String searchStr = dtfi.GetEraName(eras[i]);
- if (str.MatchSpecifiedWord(searchStr)) {
+ if (str.MatchSpecifiedWord(searchStr))
+ {
str.Index += (searchStr.Length - 1);
result = eras[i];
return (true);
}
searchStr = dtfi.GetAbbreviatedEraName(eras[i]);
- if (str.MatchSpecifiedWord(searchStr)) {
+ if (str.MatchSpecifiedWord(searchStr))
+ {
str.Index += (searchStr.Length - 1);
result = eras[i];
return (true);
@@ -3211,20 +3580,26 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
**Exceptions: FormatException if a time mark can not be found.
==============================================================================*/
- private static bool MatchTimeMark(ref __DTString str, DateTimeFormatInfo dtfi, ref TM result) {
+ 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) {
+ if (dtfi.AMDesignator.Length == 0)
+ {
result = TM.AM;
}
- if (dtfi.PMDesignator.Length == 0) {
+ if (dtfi.PMDesignator.Length == 0)
+ {
result = TM.PM;
}
- if (str.GetNext()) {
+ if (str.GetNext())
+ {
String searchStr = dtfi.AMDesignator;
- if (searchStr.Length > 0) {
- if (str.MatchSpecifiedWord(searchStr)) {
+ if (searchStr.Length > 0)
+ {
+ if (str.MatchSpecifiedWord(searchStr))
+ {
// Found an AM timemark with length > 0.
str.Index += (searchStr.Length - 1);
result = TM.AM;
@@ -3232,8 +3607,10 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
}
}
searchStr = dtfi.PMDesignator;
- if (searchStr.Length > 0) {
- if (str.MatchSpecifiedWord(searchStr)) {
+ if (searchStr.Length > 0)
+ {
+ if (str.MatchSpecifiedWord(searchStr))
+ {
// Found a PM timemark with length > 0.
str.Index += (searchStr.Length - 1);
result = TM.PM;
@@ -3242,7 +3619,8 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
}
str.Index--; // Undo the GetNext call.
}
- if (result != TM.NotSet) {
+ if (result != TM.NotSet)
+ {
// If one of the AM/PM marks is empty string, return the result.
return (true);
}
@@ -3257,17 +3635,20 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
**Exceptions: FormatException if a abbreviated time mark can not be found.
==============================================================================*/
- private static bool MatchAbbreviatedTimeMark(ref __DTString str, DateTimeFormatInfo dtfi, ref TM result) {
+ 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]) {
+ if (str.GetChar() == dtfi.AMDesignator[0])
+ {
result = TM.AM;
return (true);
}
- if (str.GetChar() == dtfi.PMDesignator[0]) {
+ if (str.GetChar() == dtfi.PMDesignator[0])
+ {
result = TM.PM;
return (true);
}
@@ -3285,12 +3666,17 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
**Exceptions:
==============================================================================*/
- private static bool CheckNewValue(ref int currentValue, int newValue, char patternChar, ref DateTimeResult result) {
- if (currentValue == -1) {
+ 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) {
+ }
+ else
+ {
+ if (newValue != currentValue)
+ {
result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_RepeatDateTimePattern", patternChar);
return (false);
}
@@ -3298,13 +3684,17 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
return (true);
}
- private static DateTime GetDateTimeNow(ref DateTimeResult result, ref DateTimeStyles styles) {
- if ((result.flags & ParseFlags.CaptureOffset) != 0) {
- if ((result.flags & ParseFlags.TimeZoneUsed) != 0) {
+ 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) {
+ else if ((styles & DateTimeStyles.AssumeUniversal) != 0)
+ {
// assume the offset is Utc
return DateTime.UtcNow;
}
@@ -3314,9 +3704,10 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
return DateTime.Now;
}
- private static bool CheckDefaultDateTime(ref DateTimeResult result, ref Calendar cal, DateTimeStyles styles) {
-
- if ((result.flags & ParseFlags.CaptureOffset) != 0) {
+ 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
@@ -3327,15 +3718,17 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
//
// 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) ) {
+ 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)) {
+ 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.
@@ -3355,41 +3748,53 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
-- -- -- 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 (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 {
+ }
+ else
+ {
// Year/Month/Day are all missing.
result.Year = cal.GetYear(now);
result.Month = cal.GetMonth(now);
result.Day = cal.GetDayOfMonth(now);
}
- } else {
+ }
+ else
+ {
// Month/Day are both missing.
result.Month = 1;
result.Day = 1;
}
- } else {
- if (result.Year == -1) {
+ }
+ else
+ {
+ if (result.Year == -1)
+ {
result.Year = cal.GetYear(now);
}
- if (result.Month == -1) {
+ if (result.Month == -1)
+ {
result.Month = 1;
}
- if (result.Day == -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.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;
@@ -3401,12 +3806,14 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
// 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) {
+ 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]) {
+ switch (format[0])
+ {
case 'o':
case 'O': // Round Trip Format
parseInfo.calendar = GregorianCalendar.GetDefaultInstance();
@@ -3416,8 +3823,9 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
case 'R': // RFC 1123 Standard. (in Universal time)
parseInfo.calendar = GregorianCalendar.GetDefaultInstance();
dtfi = DateTimeFormatInfo.InvariantInfo;
-
- if ((result.flags & ParseFlags.CaptureOffset) != 0) {
+
+ if ((result.flags & ParseFlags.CaptureOffset) != 0)
+ {
result.flags |= ParseFlags.Rfc1123Pattern;
}
break;
@@ -3429,7 +3837,8 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
parseInfo.calendar = GregorianCalendar.GetDefaultInstance();
dtfi = DateTimeFormatInfo.InvariantInfo;
- if ((result.flags & ParseFlags.CaptureOffset) != 0) {
+ if ((result.flags & ParseFlags.CaptureOffset) != 0)
+ {
result.flags |= ParseFlags.UtcSortPattern;
}
break;
@@ -3438,7 +3847,8 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
result.flags |= ParseFlags.TimeZoneUsed;
result.timeZoneOffset = new TimeSpan(0);
result.flags |= ParseFlags.TimeZoneUtc;
- if (dtfi.Calendar.GetType() != typeof(GregorianCalendar)) {
+ if (dtfi.Calendar.GetType() != typeof(GregorianCalendar))
+ {
dtfi = (DateTimeFormatInfo)dtfi.Clone();
dtfi.Calendar = GregorianCalendar.GetDefaultInstance();
}
@@ -3462,8 +3872,8 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
ref __DTString format,
ref ParsingInfo parseInfo,
DateTimeFormatInfo dtfi,
- ref DateTimeResult result) {
-
+ ref DateTimeResult result)
+ {
int tokenLen = 0;
int tempYear = 0, tempMonth = 0, tempDay = 0, tempDayOfWeek = 0, tempHour = 0, tempMinute = 0, tempSecond = 0;
double tempFraction = 0;
@@ -3471,89 +3881,119 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
char ch = format.GetChar();
- switch (ch) {
+ switch (ch)
+ {
case 'y':
tokenLen = format.GetRepeatCount();
bool parseResult;
- if (dtfi.HasForceTwoDigitYears) {
+ if (dtfi.HasForceTwoDigitYears)
+ {
parseResult = ParseDigits(ref str, 1, 4, out tempYear);
}
- else {
- if (tokenLen <= 2) {
+ else
+ {
+ if (tokenLen <= 2)
+ {
parseInfo.fUseTwoDigitYear = true;
}
parseResult = ParseDigits(ref str, tokenLen, out tempYear);
}
- if (!parseResult && parseInfo.fCustomNumberParser) {
+ if (!parseResult && parseInfo.fCustomNumberParser)
+ {
parseResult = parseInfo.parseNumberDelegate(ref str, tokenLen, out tempYear);
}
- if (!parseResult) {
+ if (!parseResult)
+ {
result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
return (false);
}
- if (!CheckNewValue(ref result.Year, tempYear, ch, ref result)) {
+ 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 (tokenLen <= 2)
+ {
+ if (!ParseDigits(ref str, tokenLen, out tempMonth))
+ {
if (!parseInfo.fCustomNumberParser ||
- !parseInfo.parseNumberDelegate(ref str, tokenLen, out tempMonth)) {
+ !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)) {
+ }
+ 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)) {
+ }
+ 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)) {
+ if (!CheckNewValue(ref result.Month, tempMonth, ch, ref result))
+ {
return (false);
}
break;
case 'd':
// Day & Day of week
tokenLen = format.GetRepeatCount();
- if (tokenLen <= 2) {
+ if (tokenLen <= 2)
+ {
// "d" & "dd"
- if (!ParseDigits(ref str, tokenLen, out tempDay)) {
+ if (!ParseDigits(ref str, tokenLen, out tempDay))
+ {
if (!parseInfo.fCustomNumberParser ||
- !parseInfo.parseNumberDelegate(ref str, tokenLen, out tempDay)) {
+ !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)) {
+ if (!CheckNewValue(ref result.Day, tempDay, ch, ref result))
+ {
return (false);
}
- } else {
- if (tokenLen == 3) {
+ }
+ else
+ {
+ if (tokenLen == 3)
+ {
// "ddd"
- if (!MatchAbbreviatedDayName(ref str, dtfi, ref tempDayOfWeek)) {
+ if (!MatchAbbreviatedDayName(ref str, dtfi, ref tempDayOfWeek))
+ {
result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
return (false);
}
- } else {
+ }
+ else
+ {
// "dddd*"
- if (!MatchDayName(ref str, dtfi, ref tempDayOfWeek)) {
+ 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)) {
+ if (!CheckNewValue(ref parseInfo.dayOfWeek, tempDayOfWeek, ch, ref result))
+ {
return (false);
}
}
@@ -3561,7 +4001,8 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
case 'g':
tokenLen = format.GetRepeatCount();
// Put the era value in result.era.
- if (!MatchEraName(ref str, dtfi, ref result.era)) {
+ if (!MatchEraName(ref str, dtfi, ref result.era))
+ {
result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
return (false);
}
@@ -3569,87 +4010,112 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
case 'h':
parseInfo.fUseHour12 = true;
tokenLen = format.GetRepeatCount();
- if (!ParseDigits(ref str, (tokenLen < 2? 1 : 2), out tempHour)) {
+ 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)) {
+ 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)) {
+ 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)) {
+ 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)) {
+ 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)) {
+ 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)) {
+ 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)) {
+ 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') {
+ 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) {
+ if (result.fraction < 0)
+ {
result.fraction = tempFraction;
- } else {
- if (tempFraction != result.fraction) {
+ }
+ else
+ {
+ if (tempFraction != result.fraction)
+ {
result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_RepeatDateTimePattern", ch);
return (false);
}
}
- } else {
+ }
+ else
+ {
result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
return (false);
}
break;
- case 't':
+ case 't':
// AM/PM designator
tokenLen = format.GetRepeatCount();
- if (tokenLen == 1) {
- if (!MatchAbbreviatedTimeMark(ref str, dtfi, ref tempTimeMark)) {
+ 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)) {
+ }
+ else
+ {
+ if (!MatchTimeMark(ref str, dtfi, ref tempTimeMark))
+ {
result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
return (false);
}
}
- if (parseInfo.timeMark == TM.NotSet) {
+ if (parseInfo.timeMark == TM.NotSet)
+ {
parseInfo.timeMark = tempTimeMark;
}
- else {
- if (parseInfo.timeMark != tempTimeMark) {
+ else
+ {
+ if (parseInfo.timeMark != tempTimeMark)
+ {
result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_RepeatDateTimePattern", ch);
return (false);
}
@@ -3660,11 +4126,13 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
tokenLen = format.GetRepeatCount();
{
TimeSpan tempTimeZoneOffset = new TimeSpan(0);
- if (!ParseTimeZoneOffset(ref str, tokenLen, ref tempTimeZoneOffset)) {
+ 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) {
+ if ((result.flags & ParseFlags.TimeZoneUsed) != 0 && tempTimeZoneOffset != result.timeZoneOffset)
+ {
result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_RepeatDateTimePattern", 'z');
return (false);
}
@@ -3673,7 +4141,8 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
}
break;
case 'Z':
- if ((result.flags & ParseFlags.TimeZoneUsed) != 0 && result.timeZoneOffset != TimeSpan.Zero) {
+ if ((result.flags & ParseFlags.TimeZoneUsed) != 0 && result.timeZoneOffset != TimeSpan.Zero)
+ {
result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_RepeatDateTimePattern", 'Z');
return (false);
}
@@ -3687,7 +4156,8 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
// method from inside ParseExact we need to adjust this. Long term, we should try to
// eliminate this discrepancy.
str.Index++;
- if (!GetTimeZoneName(ref str)) {
+ if (!GetTimeZoneName(ref str))
+ {
result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
return false;
}
@@ -3695,8 +4165,10 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
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) {
+ if (str.Match('Z'))
+ {
+ if ((result.flags & ParseFlags.TimeZoneUsed) != 0 && result.timeZoneOffset != TimeSpan.Zero)
+ {
result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_RepeatDateTimePattern", 'K');
return (false);
}
@@ -3705,14 +4177,17 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
result.timeZoneOffset = new TimeSpan(0);
result.flags |= ParseFlags.TimeZoneUtc;
}
- else if (str.Match('+') || str.Match('-')) {
+ 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)) {
+ 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) {
+ if ((result.flags & ParseFlags.TimeZoneUsed) != 0 && tempTimeZoneOffset != result.timeZoneOffset)
+ {
result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_RepeatDateTimePattern", 'K');
return (false);
}
@@ -3724,8 +4199,9 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
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)) {
+ 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;
@@ -3734,7 +4210,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
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('/')) &&
+ if (((dtfi.DateSeparator.Length > 1 && dtfi.DateSeparator[0] == '/') || !str.Match('/')) &&
!str.Match(dtfi.DateSeparator))
{
// A date separator is expected.
@@ -3746,7 +4222,8 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
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)) {
+ if (!TryParseQuoteString(format.Value, format.Index, enquotedString, out tokenLen))
+ {
result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_BadQuote", ch);
return (false);
}
@@ -3757,10 +4234,14 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
// in the quoted string.
String quotedStr = enquotedString.ToString();
- for (int i = 0; i < quotedStr.Length; i++) {
- if (quotedStr[i] == ' ' && parseInfo.fAllowInnerWhite) {
+ for (int i = 0; i < quotedStr.Length; i++)
+ {
+ if (quotedStr[i] == ' ' && parseInfo.fAllowInnerWhite)
+ {
str.SkipWhiteSpaces();
- } else if (!str.Match(quotedStr[i])) {
+ }
+ else if (!str.Match(quotedStr[i]))
+ {
// Can not find the matching quoted string.
result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
return false;
@@ -3771,12 +4252,15 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
// 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) {
+ 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) {
+ else if ((result.flags & ParseFlags.UtcSortPattern) != 0 && quotedStr == ZuluName)
+ {
result.flags |= ParseFlags.TimeZoneUsed;
result.timeZoneOffset = TimeSpan.Zero;
}
@@ -3788,7 +4272,8 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
// 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] == '%') {
+ if (format.Index >= format.Value.Length - 1 || format.Value[format.Index + 1] == '%')
+ {
result.SetFailure(ParseFailureKind.Format, "Format_BadFormatSpecifier", null);
return false;
}
@@ -3797,23 +4282,30 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
// 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())) {
+ 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 {
+ }
+ else
+ {
result.SetFailure(ParseFailureKind.Format, "Format_BadFormatSpecifier", null);
return false;
}
break;
- case '.':
- if (!str.Match(ch)) {
- if (format.GetNext()) {
+ 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')) {
+ if (format.Match('F'))
+ {
format.GetRepeatCount();
break;
}
@@ -3823,12 +4315,17 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
}
break;
default:
- if (ch == ' ') {
- if (parseInfo.fAllowInnerWhite) {
+ if (ch == ' ')
+ {
+ if (parseInfo.fAllowInnerWhite)
+ {
// Skip whitespaces if AllowInnerWhite.
// Do nothing here.
- } else {
- if (!str.Match(ch)) {
+ }
+ 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.
@@ -3838,9 +4335,12 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
// 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)) {
+ if (parseInfo.fAllowTrailingWhite)
+ {
+ if (format.GetNext())
+ {
+ if (ParseByFormat(ref str, ref format, ref parseInfo, dtfi, ref result))
+ {
return (true);
}
}
@@ -3850,18 +4350,24 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
}
// Found a macth.
}
- } else {
- if (format.MatchSpecifiedWord(GMTName)) {
+ }
+ 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)) {
+ if (!str.Match(GMTName))
+ {
result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
return false;
}
- } else if (!str.Match(ch)) {
+ }
+ else if (!str.Match(ch))
+ {
// ch is expected.
result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
return false;
@@ -3876,7 +4382,8 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
// 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) {
+ 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.
//
@@ -3886,32 +4393,41 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
char quoteChar = format[pos++]; // Get the character used to quote the following string.
bool foundQuote = false;
- while (pos < formatLen) {
+ while (pos < formatLen)
+ {
char ch = format[pos++];
- if (ch == quoteChar) {
+ if (ch == quoteChar)
+ {
foundQuote = true;
break;
}
- else if (ch == '\\') {
+ 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) {
+ if (pos < formatLen)
+ {
result.Append(format[pos++]);
- } else {
+ }
+ else
+ {
//
// This means that '\' is at the end of the formatting string.
//
return false;
}
- } else {
+ }
+ else
+ {
result.Append(ch);
}
}
- if (!foundQuote) {
+ if (!foundQuote)
+ {
// Here we can't find the matching quote.
return false;
}
@@ -3947,10 +4463,8 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
String formatParam,
DateTimeStyles styles,
DateTimeFormatInfo dtfi,
- ref DateTimeResult result) {
-
-
-
+ ref DateTimeResult result)
+ {
ParsingInfo parseInfo = new ParsingInfo();
parseInfo.Init();
@@ -3961,19 +4475,22 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
// 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') {
+ 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) {
+ if (parseInfo.calendar.ID == Calendar.CAL_HEBREW)
+ {
parseInfo.parseNumberDelegate = m_hebrewNumberParser;
parseInfo.fCustomNumberParser = true;
}
@@ -3985,14 +4502,16 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
__DTString format = new __DTString(formatParam, dtfi, false);
__DTString str = new __DTString(s, dtfi, false);
- if (parseInfo.fAllowTrailingWhite) {
+ if (parseInfo.fAllowTrailingWhite)
+ {
// Trim trailing spaces if AllowTrailingWhite.
format.TrimTail();
format.RemoveTrailingInQuoteSpaces();
str.TrimTail();
}
- if ((styles & DateTimeStyles.AllowLeadingWhite) != 0) {
+ if ((styles & DateTimeStyles.AllowLeadingWhite) != 0)
+ {
format.SkipWhiteSpaces();
format.RemoveLeadingInQuoteSpaces();
str.SkipWhiteSpaces();
@@ -4001,40 +4520,50 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
//
// Scan every character in format and match the pattern in str.
//
- while (format.GetNext()) {
+ while (format.GetNext())
+ {
// We trim inner spaces here, so that we will not eat trailing spaces when
// AllowTrailingWhite is not used.
- if (parseInfo.fAllowInnerWhite) {
+ if (parseInfo.fAllowInnerWhite)
+ {
str.SkipWhiteSpaces();
}
- if (!ParseByFormat(ref str, ref format, ref parseInfo, dtfi, ref result)) {
- return (false);
+ if (!ParseByFormat(ref str, ref format, ref parseInfo, dtfi, ref result))
+ {
+ return (false);
}
- }
+ }
- if (str.Index < str.Value.Length - 1) {
+ 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)) {
+ 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) {
+ if (result.Year >= 100)
+ {
result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
return false;
}
- try {
+ try
+ {
result.Year = parseInfo.calendar.ToFourDigitYear(result.Year);
}
- catch (ArgumentOutOfRangeException e) {
+ catch (ArgumentOutOfRangeException e)
+ {
result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", e);
return false;
}
}
- if (parseInfo.fUseHour12) {
- if (parseInfo.timeMark == TM.NotSet) {
+ 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.
@@ -4042,27 +4571,33 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
// and ParseExact() throws on me (because I didn't use the 24-hour clock 'HH').
parseInfo.timeMark = TM.AM;
}
- if (result.Hour > 12) {
+ 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) {
+ if (parseInfo.timeMark == TM.AM)
+ {
+ if (result.Hour == 12)
+ {
result.Hour = 0;
}
- } else {
+ }
+ 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)) {
+ // 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;
}
@@ -4071,22 +4606,27 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
// 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)) {
+ 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))) {
+ 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.Hour, result.Minute, result.Second, 0, result.era, out result.parsedDate))
+ {
result.SetFailure(ParseFailureKind.FormatBadDateTimeCalendar, "Format_BadDateTimeCalendar", null);
return false;
}
- if (result.fraction > 0) {
+ if (result.fraction > 0)
+ {
result.parsedDate = result.parsedDate.AddTicks((long)Math.Round(result.fraction * Calendar.TicksPerSecond));
}
@@ -4095,25 +4635,30 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
// It is because the value of day of week may change after adjusting
// to the time zone.
//
- if (parseInfo.dayOfWeek != -1) {
+ if (parseInfo.dayOfWeek != -1)
+ {
//
// Check if day of week is correct.
//
- if (parseInfo.dayOfWeek != (int)parseInfo.calendar.GetDayOfWeek(result.parsedDate)) {
+ if (parseInfo.dayOfWeek != (int)parseInfo.calendar.GetDayOfWeek(result.parsedDate))
+ {
result.SetFailure(ParseFailureKind.Format, "Format_BadDayOfWeek", null);
return false;
}
}
- if (!DetermineTimeZoneAdjustments(ref result, styles, bTimeOnly)) {
+ if (!DetermineTimeZoneAdjustments(ref result, styles, bTimeOnly))
+ {
return false;
}
return true;
}
- private static Exception GetDateTimeParseException(ref DateTimeResult result) {
- switch (result.failure) {
+ 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:
@@ -4125,7 +4670,6 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
default:
Debug.Assert(false, "Unkown DateTimeParseFailure: " + result);
return null;
-
}
}
@@ -4138,7 +4682,8 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
// COMPlus_ManagedLogFacility=0x00001000
[Pure]
[Conditional("_LOGGING")]
- internal static void LexTraceExit(string message, DS dps) {
+ internal static void LexTraceExit(string message, DS dps)
+ {
#if _LOGGING
if (!_tracingEnabled)
return;
@@ -4147,7 +4692,8 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
}
[Pure]
[Conditional("_LOGGING")]
- internal static void PTSTraceExit(DS dps, bool passed) {
+ internal static void PTSTraceExit(DS dps, bool passed)
+ {
#if _LOGGING
if (!_tracingEnabled)
return;
@@ -4156,7 +4702,8 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
}
[Pure]
[Conditional("_LOGGING")]
- internal static void TPTraceExit(string message, DS dps) {
+ internal static void TPTraceExit(string message, DS dps)
+ {
#if _LOGGING
if (!_tracingEnabled)
return;
@@ -4165,7 +4712,8 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
}
[Pure]
[Conditional("_LOGGING")]
- internal static void DTFITrace(DateTimeFormatInfo dtfi) {
+ internal static void DTFITrace(DateTimeFormatInfo dtfi)
+ {
#if _LOGGING
if (!_tracingEnabled)
return;
@@ -4189,33 +4737,37 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
#if _LOGGING
[Pure]
// return a string in the form: "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
- internal static string Hex(string[] strs) {
+ 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 curLineLength = 0;
+ int maxLineLength = 55;
int newLinePadding = 20;
//invariant: strs.Length >= 2
- StringBuilder buffer = new StringBuilder();
+ StringBuilder buffer = new StringBuilder();
buffer.Append(Hex(strs[0]));
curLineLength = buffer.Length;
String s;
- for (int i = 1; i < strs.Length-1; i++) {
+ for (int i = 1; i < strs.Length - 1; i++)
+ {
s = Hex(strs[i]);
- if (s.Length > maxLineLength || (curLineLength + s.Length + 2) > maxLineLength) {
+ if (s.Length > maxLineLength || (curLineLength + s.Length + 2) > maxLineLength)
+ {
buffer.Append(',');
buffer.Append(Environment.NewLine);
buffer.Append(' ', newLinePadding);
curLineLength = 0;
}
- else {
+ else
+ {
buffer.Append(", ");
curLineLength += 2;
}
@@ -4224,12 +4776,14 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
}
buffer.Append(',');
- s = Hex(strs[strs.Length-1]);
- if (s.Length > maxLineLength || (curLineLength + s.Length + 6) > maxLineLength) {
+ s = Hex(strs[strs.Length - 1]);
+ if (s.Length > maxLineLength || (curLineLength + s.Length + 6) > maxLineLength)
+ {
buffer.Append(Environment.NewLine);
buffer.Append(' ', newLinePadding);
}
- else {
+ else
+ {
buffer.Append(' ');
}
buffer.Append(s);
@@ -4237,10 +4791,12 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
}
[Pure]
// return a string in the form: "Sun"
- internal static string Hex(string str) {
+ internal static string Hex(string str)
+ {
StringBuilder buffer = new StringBuilder();
buffer.Append("\"");
- for (int i = 0; i < str.Length; i++) {
+ for (int i = 0; i < str.Length; i++)
+ {
if (str[i] <= '\x007f')
buffer.Append(str[i]);
else
@@ -4251,7 +4807,8 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
}
[Pure]
// return an unicode escaped string form of char c
- internal static String Hex(char c) {
+ internal static String Hex(char c)
+ {
if (c <= '\x007f')
return c.ToString(CultureInfo.InvariantCulture);
else
@@ -4260,7 +4817,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
internal static bool _tracingEnabled = BCLDebug.CheckEnabled("DATETIME");
#endif // _LOGGING
- }
+ }
//
@@ -4271,7 +4828,6 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
internal
struct __DTString
{
-
//
// Value propery: stores the real string to be parsed.
//
@@ -4292,8 +4848,8 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
// 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)
+
+ internal __DTString(String str, DateTimeFormatInfo dtfi, bool checkDigitToken) : this(str, dtfi)
{
m_checkDigitToken = checkDigitToken;
}
@@ -4304,12 +4860,13 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
Value = str;
len = Value.Length;
- m_current = '\0';
+ m_current = '\0';
if (dtfi != null)
{
m_info = dtfi.CompareInfo;
m_checkDigitToken = ((dtfi.FormatFlags & DateTimeFormatFlags.UseDigitPrefixInTokens) != 0);
- } else
+ }
+ else
{
m_info = Thread.CurrentThread.CurrentCulture.CompareInfo;
m_checkDigitToken = false;
@@ -4330,9 +4887,11 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
// {
// char ch = str.GetChar()
// }
- internal bool GetNext() {
+ internal bool GetNext()
+ {
Index++;
- if (Index < len) {
+ if (Index < len)
+ {
m_current = Value[Index];
return (true);
}
@@ -4344,10 +4903,12 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
return Index < len ? false : true;
}
- internal bool Advance(int count) {
+ internal bool Advance(int count)
+ {
Debug.Assert(Index + count <= len, "__DTString::Advance: Index + count <= len");
Index += count;
- if (Index < len) {
+ if (Index < len)
+ {
m_current = Value[Index];
return (true);
}
@@ -4356,17 +4917,20 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
// Used by DateTime.Parse() to get the next token.
- internal void GetRegularToken(out TokenType tokenType, out int tokenValue, DateTimeFormatInfo dtfi) {
+ internal void GetRegularToken(out TokenType tokenType, out int tokenValue, DateTimeFormatInfo dtfi)
+ {
tokenValue = 0;
- if (Index >= len) {
+ if (Index >= len)
+ {
tokenType = TokenType.EndOfString;
return;
}
tokenType = TokenType.UnknownToken;
-Start:
- if (DateTimeParse.IsDigit(m_current)) {
+ Start:
+ if (DateTimeParse.IsDigit(m_current))
+ {
// This is a digit.
tokenValue = m_current - '0';
int value;
@@ -4379,18 +4943,26 @@ Start:
{
m_current = Value[Index];
value = m_current - '0';
- if (value >= 0 && value <= 9) {
+ if (value >= 0 && value <= 9)
+ {
tokenValue = tokenValue * 10 + value;
- } else {
+ }
+ else
+ {
break;
}
}
- if (Index - start > DateTimeParse.MaxDateTimeNumberDigits) {
+ if (Index - start > DateTimeParse.MaxDateTimeNumberDigits)
+ {
tokenType = TokenType.NumberToken;
tokenValue = -1;
- } else if (Index - start < 3) {
+ }
+ else if (Index - start < 3)
+ {
tokenType = TokenType.NumberToken;
- } else {
+ }
+ else
+ {
// If there are more than 3 digits, assume that it's a year value.
tokenType = TokenType.YearNumberToken;
}
@@ -4410,47 +4982,58 @@ Start:
tokenType = tempType;
tokenValue = tempValue;
// This is a token, so the Index has been advanced propertly in DTFI.Tokenizer().
- } else
+ }
+ else
{
// Use the number token value.
// Restore the index.
Index = save;
m_current = saveCh;
}
-
- }
-
- } else if (Char.IsWhiteSpace( m_current)) {
+ }
+ }
+ else if (Char.IsWhiteSpace(m_current))
+ {
// Just skip to the next character.
- while (++Index < len) {
+ while (++Index < len)
+ {
m_current = Value[Index];
- if (!(Char.IsWhiteSpace(m_current))) {
+ if (!(Char.IsWhiteSpace(m_current)))
+ {
goto Start;
}
}
// We have reached the end of string.
tokenType = TokenType.EndOfString;
- } else {
+ }
+ else
+ {
dtfi.Tokenize(TokenType.RegularTokenMask, out tokenType, out tokenValue, ref this);
}
}
- internal TokenType GetSeparatorToken(DateTimeFormatInfo dtfi, out int indexBeforeSeparator, out char charBeforeSeparator) {
+ internal TokenType GetSeparatorToken(DateTimeFormatInfo dtfi, out int indexBeforeSeparator, out char charBeforeSeparator)
+ {
indexBeforeSeparator = Index;
charBeforeSeparator = m_current;
TokenType tokenType;
- if (!SkipWhiteSpaceCurrent()) {
+ if (!SkipWhiteSpaceCurrent())
+ {
// Reach the end of the string.
return (TokenType.SEP_End);
}
- if (!DateTimeParse.IsDigit(m_current)) {
+ 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) {
+ if (!found)
+ {
tokenType = TokenType.SEP_Space;
}
- } else {
+ }
+ 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;
@@ -4458,53 +5041,67 @@ Start:
return (tokenType);
}
- internal bool MatchSpecifiedWord(String target) {
+ internal bool MatchSpecifiedWord(String target)
+ {
return MatchSpecifiedWord(target, target.Length + Index);
}
- internal bool MatchSpecifiedWord(String target, int endIndex) {
+ internal bool MatchSpecifiedWord(String target, int endIndex)
+ {
int count = endIndex - Index;
- if (count != target.Length) {
+ if (count != target.Length)
+ {
return false;
}
- if (Index + count > len) {
+ if (Index + count > len)
+ {
return false;
}
- return (m_info.Compare(Value, Index, count, target, 0, count, CompareOptions.IgnoreCase)==0);
+ 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) {
+ 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) {
+ 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) {
+ if (wsIndex == -1)
+ {
return false;
}
- do {
+ do
+ {
int segmentLength = wsIndex - targetPosition;
- if (thisPosition >= Value.Length - segmentLength) { // Subtraction to prevent overflow.
+ if (thisPosition >= Value.Length - segmentLength)
+ { // Subtraction to prevent overflow.
return false;
}
- if (segmentLength == 0) {
+ 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 {
+ }
+ else
+ {
// Make sure we also have whitespace in the input string
- if (!Char.IsWhiteSpace(Value[thisPosition + segmentLength])) {
+ if (!Char.IsWhiteSpace(Value[thisPosition + segmentLength]))
+ {
return false;
}
- if (m_info.Compare(Value, thisPosition, segmentLength, target, targetPosition, segmentLength, CompareOptions.IgnoreCase) !=0) {
+ if (m_info.Compare(Value, thisPosition, segmentLength, target, targetPosition, segmentLength, CompareOptions.IgnoreCase) != 0)
+ {
return false;
}
// Advance the input string
@@ -4515,27 +5112,34 @@ Start:
// Skip past multiple whitespace
- while (thisPosition < Value.Length && Char.IsWhiteSpace(Value[thisPosition])) {
+ 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) {
+ if (targetPosition < target.Length)
+ {
int segmentLength = target.Length - targetPosition;
- if (thisPosition > Value.Length - segmentLength) {
+ if (thisPosition > Value.Length - segmentLength)
+ {
return false;
}
- if (m_info.Compare(Value, thisPosition, segmentLength, target, targetPosition, segmentLength, CompareOptions.IgnoreCase) !=0) {
+ if (m_info.Compare(Value, thisPosition, segmentLength, target, targetPosition, segmentLength, CompareOptions.IgnoreCase) != 0)
+ {
return false;
}
}
}
- if (checkWordBoundary) {
+ if (checkWordBoundary)
+ {
int nextCharIndex = Index + matchLength;
- if (nextCharIndex < Value.Length) {
- if (Char.IsLetter(Value[nextCharIndex])) {
+ if (nextCharIndex < Value.Length)
+ {
+ if (Char.IsLetter(Value[nextCharIndex]))
+ {
return (false);
}
}
@@ -4549,16 +5153,20 @@ Start:
// 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) {
+ internal bool Match(String str)
+ {
+ if (++Index >= len)
+ {
return (false);
}
- if (str.Length > (Value.Length - Index)) {
+ if (str.Length > (Value.Length - Index))
+ {
return false;
}
- if (m_info.Compare(Value, Index, str.Length, str, 0, str.Length, CompareOptions.Ordinal)==0) {
+ 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.
@@ -4568,11 +5176,14 @@ Start:
return (false);
}
- internal bool Match(char ch) {
- if (++Index >= len) {
+ internal bool Match(char ch)
+ {
+ if (++Index >= len)
+ {
return (false);
}
- if (Value[Index] == ch) {
+ if (Value[Index] == ch)
+ {
m_current = ch;
return (true);
}
@@ -4591,13 +5202,17 @@ Start:
// 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) {
+ internal int MatchLongestWords(String[] words, ref int maxMatchStrLen)
+ {
int result = -1;
- for (int i = 0; i < words.Length; i++) {
+ 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) {
+ if (MatchSpecifiedWords(word, false, ref matchLength))
+ {
+ if (matchLength > maxMatchStrLen)
+ {
maxMatchStrLen = matchLength;
result = i;
}
@@ -4612,10 +5227,12 @@ Start:
// For a string "hh:mm:ss" at Index of 3. GetRepeatCount() = 2, and Index
// will point to the second ':'.
//
- internal int GetRepeatCount() {
+ internal int GetRepeatCount()
+ {
char repeatChar = Value[Index];
int pos = Index + 1;
- while ((pos < len) && (Value[pos] == repeatChar)) {
+ while ((pos < len) && (Value[pos] == repeatChar))
+ {
pos++;
}
int repeatCount = (pos - Index);
@@ -4627,8 +5244,10 @@ Start:
}
// Return false when end of string is encountered or a non-digit character is found.
- internal bool GetNextDigit() {
- if (++Index >= len) {
+ internal bool GetNextDigit()
+ {
+ if (++Index >= len)
+ {
return (false);
}
return (DateTimeParse.IsDigit(Value[Index]));
@@ -4637,7 +5256,8 @@ Start:
//
// Get the current character.
//
- internal char GetChar() {
+ internal char GetChar()
+ {
Debug.Assert(Index >= 0 && Index < len, "Index >= 0 && Index < len");
return (Value[Index]);
}
@@ -4645,7 +5265,8 @@ Start:
//
// Convert the current character to a digit, and return it.
//
- internal int GetDigit() {
+ 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');
@@ -4660,10 +5281,11 @@ Start:
{
// Look ahead to see if the next character
// is a whitespace.
- while (Index+1 < len)
+ while (Index + 1 < len)
{
- char ch = Value[Index+1];
- if (!Char.IsWhiteSpace(ch)) {
+ char ch = Value[Index + 1];
+ if (!Char.IsWhiteSpace(ch))
+ {
return;
}
Index++;
@@ -4678,7 +5300,8 @@ Start:
//
internal bool SkipWhiteSpaceCurrent()
{
- if (Index >= len) {
+ if (Index >= len)
+ {
return (false);
}
@@ -4699,9 +5322,11 @@ Start:
return (false);
}
- internal void TrimTail() {
+ internal void TrimTail()
+ {
int i = len - 1;
- while (i >= 0 && Char.IsWhiteSpace(Value[i])) {
+ while (i >= 0 && Char.IsWhiteSpace(Value[i]))
+ {
i--;
}
Value = Value.Substring(0, i + 1);
@@ -4710,17 +5335,22 @@ Start:
// Trim the trailing spaces within a quoted string.
// Call this after TrimTail() is done.
- internal void RemoveTrailingInQuoteSpaces() {
+ internal void RemoveTrailingInQuoteSpaces()
+ {
int i = len - 1;
- if (i <= 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])) {
+ if (ch == '\'' || ch == '\"')
+ {
+ if (Char.IsWhiteSpace(Value[i - 1]))
+ {
i--;
- while (i >= 1 && Char.IsWhiteSpace(Value[i-1])) {
+ while (i >= 1 && Char.IsWhiteSpace(Value[i - 1]))
+ {
i--;
}
Value = Value.Remove(i, Value.Length - 1 - i);
@@ -4731,51 +5361,65 @@ Start:
// 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) {
+ 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])) {
+ if (ch == '\'' || ch == '\"')
+ {
+ while ((i + 1) < len && Char.IsWhiteSpace(Value[i + 1]))
+ {
i++;
}
- if (i != 0) {
+ if (i != 0)
+ {
Value = Value.Remove(1, i);
len = Value.Length;
}
}
}
- internal DTSubString GetSubString() {
+ internal DTSubString GetSubString()
+ {
DTSubString sub = new DTSubString();
sub.index = Index;
sub.s = Value;
- while (Index + sub.length < len) {
+ while (Index + sub.length < len)
+ {
DTSubStringType currentType;
Char ch = Value[Index + sub.length];
- if (ch >= '0' && ch <= '9') {
+ if (ch >= '0' && ch <= '9')
+ {
currentType = DTSubStringType.Number;
}
- else {
+ else
+ {
currentType = DTSubStringType.Other;
}
- if (sub.length == 0) {
+ if (sub.length == 0)
+ {
sub.type = currentType;
}
- else {
- if (sub.type != currentType) {
+ else
+ {
+ if (sub.type != currentType)
+ {
break;
}
}
sub.length++;
- if (currentType == DTSubStringType.Number) {
+ if (currentType == DTSubStringType.Number)
+ {
// Incorporate the number into the value
// Limit the digits to prevent overflow
- if (sub.length > DateTimeParse.MaxDateTimeNumberDigits) {
+ if (sub.length > DateTimeParse.MaxDateTimeNumberDigits)
+ {
sub.type = DTSubStringType.Invalid;
return sub;
}
@@ -4783,14 +5427,16 @@ Start:
Debug.Assert(number >= 0 && number <= 9, "number >= 0 && number <= 9");
sub.value = sub.value * 10 + number;
}
- else {
+ 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) {
+ if (sub.length == 0)
+ {
sub.type = DTSubStringType.End;
return sub;
}
@@ -4798,17 +5444,20 @@ Start:
return sub;
}
- internal void ConsumeSubString(DTSubString 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) {
+ if (Index < len)
+ {
m_current = Value[Index];
}
}
}
- internal enum DTSubStringType {
+ internal enum DTSubStringType
+ {
Unknown = 0,
Invalid = 1,
Number = 2,
@@ -4816,15 +5465,18 @@ Start:
Other = 4,
}
- internal struct DTSubString {
+ internal struct DTSubString
+ {
internal String s;
internal Int32 index;
internal Int32 length;
internal DTSubStringType type;
internal Int32 value;
- internal Char this[Int32 relativeIndex] {
- get {
+ internal Char this[Int32 relativeIndex]
+ {
+ get
+ {
return s[index + relativeIndex];
}
}
@@ -4834,7 +5486,8 @@ Start:
// The buffer to store the parsing token.
//
internal
- struct DateTimeToken {
+ 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)
@@ -4844,8 +5497,9 @@ Start:
// The buffer to store temporary parsing information.
//
internal
- unsafe struct DateTimeRawInfo {
- private int* num;
+ unsafe struct DateTimeRawInfo
+ {
+ private int* num;
internal int numCount;
internal int month;
internal int year;
@@ -4858,24 +5512,28 @@ Start:
internal bool timeZone;
- internal void Init(int * numberBuffer) {
- month = -1;
- year = -1;
- dayOfWeek = -1;
- era = -1;
- timeMark = DateTimeParse.TM.NotSet;
+ 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) {
+ internal unsafe void AddNumber(int value)
+ {
num[numCount++] = value;
}
- internal unsafe int GetNumber(int index) {
+ internal unsafe int GetNumber(int index)
+ {
return num[index];
}
}
- internal enum ParseFailureKind {
+ internal enum ParseFailureKind
+ {
None = 0,
ArgumentNull = 1,
Format = 2,
@@ -4884,22 +5542,23 @@ Start:
};
[Flags]
- internal enum ParseFlags {
- HaveYear = 0x00000001,
- HaveMonth = 0x00000002,
- HaveDay = 0x00000004,
- HaveHour = 0x00000008,
- HaveMinute = 0x00000010,
- HaveSecond = 0x00000020,
- HaveTime = 0x00000040,
- HaveDate = 0x00000080,
- TimeZoneUsed = 0x00000100,
- TimeZoneUtc = 0x00000200,
+ 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,
+ CaptureOffset = 0x00000800,
+ YearDefault = 0x00001000,
+ Rfc1123Pattern = 0x00002000,
+ UtcSortPattern = 0x00004000,
}
//
@@ -4935,10 +5594,11 @@ Start:
internal object failureMessageFormatArgument;
internal string failureArgumentName;
- internal void Init() {
- Year = -1;
- Month = -1;
- Day = -1;
+ internal void Init()
+ {
+ Year = -1;
+ Month = -1;
+ Day = -1;
fraction = -1;
era = -1;
}
@@ -4949,27 +5609,25 @@ Start:
Month = month;
Day = day;
}
- internal void SetFailure(ParseFailureKind failure, string failureMessageID, object failureMessageFormatArgument) {
+ 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) {
+ 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 struct ParsingInfo
+ {
internal Calendar calendar;
internal int dayOfWeek;
internal DateTimeParse.TM timeMark;
@@ -4980,50 +5638,51 @@ Start:
internal bool fAllowTrailingWhite;
internal bool fCustomNumberParser;
internal DateTimeParse.MatchNumberDelegate parseNumberDelegate;
-
- internal void Init() {
+
+ internal void Init()
+ {
dayOfWeek = -1;
timeMark = DateTimeParse.TM.NotSet;
}
-
}
//
// The type of token that will be returned by DateTimeFormatInfo.Tokenize().
//
- internal enum TokenType {
+ 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"
+ 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
+ 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_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.
diff --git a/src/mscorlib/src/System/Globalization/DateTimeStyles.cs b/src/mscorlib/src/System/Globalization/DateTimeStyles.cs
index eadeda8e72..cd551cb08e 100644
--- a/src/mscorlib/src/System/Globalization/DateTimeStyles.cs
+++ b/src/mscorlib/src/System/Globalization/DateTimeStyles.cs
@@ -11,39 +11,40 @@
**
**
===========================================================*/
-namespace System.Globalization {
-
-[Serializable]
+namespace System.Globalization
+{
+ [Serializable]
[Flags]
- public enum DateTimeStyles {
+ 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,
+ None = 0x00000000,
- AllowLeadingWhite = 0x00000001,
+ AllowLeadingWhite = 0x00000001,
- AllowTrailingWhite = 0x00000002, //Bitflag indicating trailing whitespace is allowed.
+ AllowTrailingWhite = 0x00000002, //Bitflag indicating trailing whitespace is allowed.
- AllowInnerWhite = 0x00000004,
+ AllowInnerWhite = 0x00000004,
- AllowWhiteSpaces = AllowLeadingWhite | AllowInnerWhite | AllowTrailingWhite,
+ 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,
+ 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,
+ AdjustToUniversal = 0x00000010,
- AssumeLocal = 0x00000020,
+ AssumeLocal = 0x00000020,
- AssumeUniversal = 0x00000040,
+ AssumeUniversal = 0x00000040,
// Attempt to preserve whether the input is unspecified, local or UTC
- RoundtripKind = 0x00000080,
+ RoundtripKind = 0x00000080,
}
}
diff --git a/src/mscorlib/src/System/Globalization/DaylightTime.cs b/src/mscorlib/src/System/Globalization/DaylightTime.cs
index a21e092955..92c2437d26 100644
--- a/src/mscorlib/src/System/Globalization/DaylightTime.cs
+++ b/src/mscorlib/src/System/Globalization/DaylightTime.cs
@@ -14,36 +14,43 @@ namespace System.Globalization
internal DateTime m_end;
internal TimeSpan m_delta;
- private DaylightTime() {
+ private DaylightTime()
+ {
}
- public DaylightTime(DateTime start, DateTime end, TimeSpan delta) {
+ 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 {
+ public DateTime Start
+ {
+ get
+ {
return m_start;
}
}
// The end date of a daylight saving period.
- public DateTime End {
- get {
+ public DateTime End
+ {
+ get
+ {
return m_end;
}
}
// Delta to stardard offset in ticks.
- public TimeSpan Delta {
- get {
+ public TimeSpan Delta
+ {
+ get
+ {
return m_delta;
}
}
-
}
// Value type version of DaylightTime
diff --git a/src/mscorlib/src/System/Globalization/DigitShapes.cs b/src/mscorlib/src/System/Globalization/DigitShapes.cs
index 1513d56f5c..7a30dd2000 100644
--- a/src/mscorlib/src/System/Globalization/DigitShapes.cs
+++ b/src/mscorlib/src/System/Globalization/DigitShapes.cs
@@ -5,17 +5,17 @@
//
// The enumeration constants used in NumberFormatInfo.DigitSubstitution.
//
-namespace System.Globalization {
-
+namespace System.Globalization
+{
[Serializable]
- public enum DigitShapes : int {
-
- Context = 0x0000, // The shape depends on the previous text in the same output.
+ public enum DigitShapes : int
+ {
+ Context = 0x0000, // The shape depends on the previous text in the same output.
- None = 0x0001, // Gives full Unicode compatibility.
+ None = 0x0001, // Gives full Unicode compatibility.
- NativeNational = 0x0002, // National shapes determined by LOCALE_SNATIVEDIGITS
+ 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
index 3f6df52a96..0d026fd5fc 100644
--- a/src/mscorlib/src/System/Globalization/EastAsianLunisolarCalendar.cs
+++ b/src/mscorlib/src/System/Globalization/EastAsianLunisolarCalendar.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.Globalization {
- using System;
- using System.Diagnostics.Contracts;
+using System;
+using System.Diagnostics.Contracts;
+namespace System.Globalization
+{
////////////////////////////////////////////////////////////////////////////
//
// Notes about EastAsianLunisolarCalendar
@@ -14,7 +15,8 @@ namespace System.Globalization {
[Serializable]
- public abstract class EastAsianLunisolarCalendar : Calendar {
+ public abstract class EastAsianLunisolarCalendar : Calendar
+ {
internal const int LeapMonth = 0;
internal const int Jan1Month = 1;
internal const int Jan1Date = 2;
@@ -39,8 +41,10 @@ namespace System.Globalization {
// Return the type of the East Asian Lunisolar calendars.
//
- public override CalendarAlgorithmType AlgorithmType {
- get {
+ public override CalendarAlgorithmType AlgorithmType
+ {
+ get
+ {
return CalendarAlgorithmType.LunisolarCalendar;
}
}
@@ -48,7 +52,8 @@ namespace System.Globalization {
// Return the year number in the 60-year cycle.
//
- public virtual int GetSexagenaryYear (DateTime time) {
+ public virtual int GetSexagenaryYear(DateTime time)
+ {
CheckTicksRange(time.Ticks);
int year = 0, month = 0, day = 0;
@@ -61,23 +66,27 @@ namespace System.Globalization {
// The returned value is from 1 ~ 10.
//
- public int GetCelestialStem(int sexagenaryYear) {
- if ((sexagenaryYear < 1) || (sexagenaryYear > 60)) {
+ 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 ((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)) {
+ public int GetTerrestrialBranch(int sexagenaryYear)
+ {
+ if ((sexagenaryYear < 1) || (sexagenaryYear > 60))
+ {
throw new ArgumentOutOfRangeException(
nameof(sexagenaryYear),
Environment.GetResourceString("ArgumentOutOfRange_Range", 1, 60));
@@ -87,59 +96,71 @@ namespace System.Globalization {
return ((sexagenaryYear - 1) % 12) + 1;
}
- internal abstract int GetYearInfo(int LunarYear, int Index);
+ 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 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) {
+ internal int MinEraCalendarYear(int era)
+ {
EraInfo[] mEraInfo = CalEraInfo;
//ChineseLunisolarCalendar does not has m_EraInfo it is going to retuen null
- if (mEraInfo == null) {
+ if (mEraInfo == null)
+ {
return MinCalendarYear;
}
- if (era == Calendar.CurrentEra) {
+ 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)) {
+ if (era == GetEra(MinDate))
+ {
return (GetYear(MinCalendarYear, MinDate));
}
- for (int i = 0; i < mEraInfo.Length; i++) {
- if (era == mEraInfo[i].era) {
+ 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) {
+ internal int MaxEraCalendarYear(int era)
+ {
EraInfo[] mEraInfo = CalEraInfo;
//ChineseLunisolarCalendar does not has m_EraInfo it is going to retuen null
- if (mEraInfo == null) {
+ if (mEraInfo == null)
+ {
return MaxCalendarYear;
}
- if (era == Calendar.CurrentEra) {
+ 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)) {
+ if (era == GetEra(MaxDate))
+ {
return (GetYear(MaxCalendarYear, MaxDate));
}
- for (int i = 0; i < mEraInfo.Length; i++) {
- if (era == mEraInfo[i].era) {
+ for (int i = 0; i < mEraInfo.Length; i++)
+ {
+ if (era == mEraInfo[i].era)
+ {
return (mEraInfo[i].maxEraYear);
}
}
@@ -148,11 +169,14 @@ namespace System.Globalization {
// Construct an instance of EastAsianLunisolar calendar.
- internal EastAsianLunisolarCalendar() {
+ internal EastAsianLunisolarCalendar()
+ {
}
- internal void CheckTicksRange(long ticks) {
- if (ticks < MinSupportedDateTime.Ticks || ticks > MaxSupportedDateTime.Ticks) {
+ internal void CheckTicksRange(long ticks)
+ {
+ if (ticks < MinSupportedDateTime.Ticks || ticks > MaxSupportedDateTime.Ticks)
+ {
throw new ArgumentOutOfRangeException(
"time",
String.Format(CultureInfo.InvariantCulture, Environment.GetResourceString("ArgumentOutOfRange_CalendarRange"),
@@ -161,21 +185,26 @@ namespace System.Globalization {
Contract.EndContractBlock();
}
- internal void CheckEraRange (int era) {
- if (era == Calendar.CurrentEra) {
+ internal void CheckEraRange(int era)
+ {
+ if (era == Calendar.CurrentEra)
+ {
era = CurrentEraValue;
}
- if ((era <GetEra(MinDate)) || (era > GetEra(MaxDate))) {
+ 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);
+ internal int CheckYearRange(int year, int era)
+ {
+ CheckEraRange(era);
+ year = GetGregorianYear(year, era);
- if ((year < MinCalendarYear) || (year > MaxCalendarYear)) {
+ if ((year < MinCalendarYear) || (year > MaxCalendarYear))
+ {
throw new ArgumentOutOfRangeException(
nameof(year),
Environment.GetResourceString("ArgumentOutOfRange_Range", MinEraCalendarYear(era), MaxEraCalendarYear(era)));
@@ -183,30 +212,33 @@ namespace System.Globalization {
return year;
}
- internal int CheckYearMonthRange(int year, int month, int era) {
+ 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)
+ if (GetYearInfo(year, LeapMonth) == 0)
throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Month"));
}
- if (month < 1 || month > 13) {
+ if (month < 1 || month > 13)
+ {
throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Month"));
}
return year;
}
- internal int InternalGetDaysInMonth(int year, int month) {
+ 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)
+ mask >>= (month - 1);
+ if ((GetYearInfo(year, nDaysPerMonth) & mask) == 0)
nDays = 29;
else
nDays = 30;
@@ -217,33 +249,40 @@ namespace System.Globalization {
// month arguments.
//
- public override int GetDaysInMonth(int year, int month, int era) {
+ 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)));
+ private 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) {
+ 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) {
+ 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;
+ int gy = 0; int gm = 0; int gd = 0;
- if (LunarToGregorian(year, month, day, ref gy, ref gm, ref gd)) {
+ if (LunarToGregorian(year, month, day, ref gy, ref gm, ref gd))
+ {
return new DateTime(gy, gm, gd, hour, minute, second, millisecond);
- } else {
+ }
+ else
+ {
throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("ArgumentOutOfRange_BadYearMonthDay"));
}
}
@@ -253,7 +292,8 @@ namespace System.Globalization {
// 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) {
+ 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
@@ -265,26 +305,29 @@ namespace System.Globalization {
// calc the solar day of year
fLeap = GregorianIsLeapYear(nSYear);
- nSolarDay = (fLeap==1) ? DaysToMonth366[nSMonth-1]: DaysToMonth365[nSMonth-1] ;
+ nSolarDay = (fLeap == 1) ? DaysToMonth366[nSMonth - 1] : DaysToMonth365[nSMonth - 1];
nSolarDay += nSDate;
// init lunar year info
nLunarDay = nSolarDay;
nLYear = nSYear;
- if (nLYear == (MaxCalendarYear + 1)) {
+ if (nLYear == (MaxCalendarYear + 1))
+ {
nLYear--;
nLunarDay += ((GregorianIsLeapYear(nLYear) == 1) ? 366 : 365);
nJan1Month = GetYearInfo(nLYear, Jan1Month);
- nJan1Date = GetYearInfo(nLYear,Jan1Date);
- } else {
-
+ nJan1Date = GetYearInfo(nLYear, Jan1Date);
+ }
+ else
+ {
nJan1Month = GetYearInfo(nLYear, Jan1Month);
- nJan1Date = GetYearInfo(nLYear,Jan1Date);
+ nJan1Date = GetYearInfo(nLYear, Jan1Date);
// check if this solar date is actually part of the previous
// lunar year
if ((nSMonth < nJan1Month) ||
- (nSMonth == nJan1Month && nSDate < nJan1Date)) {
+ (nSMonth == nJan1Month && nSDate < nJan1Date))
+ {
// the corresponding lunar day is actually part of the previous
// lunar year
nLYear--;
@@ -303,7 +346,7 @@ namespace System.Globalization {
// 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 -= DaysToMonth365[nJan1Month - 1];
nLunarDay -= (nJan1Date - 1);
// convert the lunar day into a lunar month/date
@@ -311,7 +354,8 @@ namespace System.Globalization {
LDpM = GetYearInfo(nLYear, nDaysPerMonth);
nDays = ((LDpM & mask) != 0) ? 30 : 29;
nLMonth = 1;
- while (nLunarDay > nDays) {
+ while (nLunarDay > nDays)
+ {
nLunarDay -= nDays;
nLMonth++;
mask >>= 1;
@@ -324,16 +368,18 @@ namespace System.Globalization {
//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) {
+ 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;
+ 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++) {
+ for (int i = 1; i < nLMonth; i++)
+ {
numLunarDays += InternalGetDaysInMonth(nLYear, i);
}
@@ -343,40 +389,46 @@ namespace System.Globalization {
// calc the solar day of year of 1 Lunar day
int fLeap = GregorianIsLeapYear(nLYear);
- int[] days = (fLeap==1)? DaysToMonth366: DaysToMonth365;
+ int[] days = (fLeap == 1) ? DaysToMonth366 : DaysToMonth365;
- nSolarDay = nJan1Date;
+ nSolarDay = nJan1Date;
if (nJan1Month > 1)
- nSolarDay += days [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)) {
+ if (nSolarDay > (fLeap + 365))
+ {
nSolarYear = nLYear + 1;
nSolarDay -= (fLeap + 365);
- } else {
+ }
+ else
+ {
nSolarYear = nLYear;
}
- for (nSolarMonth = 1; nSolarMonth < 12; nSolarMonth++) {
+ for (nSolarMonth = 1; nSolarMonth < 12; nSolarMonth++)
+ {
if (days[nSolarMonth] >= nSolarDay)
break;
}
- nSolarDay -= days[nSolarMonth-1];
+ 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;
+ 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));
+ 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;
+ 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);
@@ -395,8 +447,10 @@ namespace System.Globalization {
// time-of-day part of the specified DateTime.
//
- public override DateTime AddMonths(DateTime time, int months) {
- if (months < -120000 || months > 120000) {
+ public override DateTime AddMonths(DateTime time, int months)
+ {
+ if (months < -120000 || months > 120000)
+ {
throw new ArgumentOutOfRangeException(
nameof(months),
Environment.GetResourceString("ArgumentOutOfRange_Range", -120000, 120000));
@@ -405,23 +459,28 @@ namespace System.Globalization {
CheckTicksRange(time.Ticks);
- int y=0; int m=0; int d=0;
+ 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;
+ if (i > 0)
+ {
+ int monthsInYear = InternalIsLeapYear(y) ? 13 : 12;
- while (i-monthsInYear > 0) {
+ while (i - monthsInYear > 0)
+ {
i -= monthsInYear;
y++;
- monthsInYear = InternalIsLeapYear(y)?13:12;
+ monthsInYear = InternalIsLeapYear(y) ? 13 : 12;
}
m = i;
- } else {
+ }
+ else
+ {
int monthsInYear;
- while (i <= 0) {
- monthsInYear = InternalIsLeapYear(y-1)?13:12;
+ while (i <= 0)
+ {
+ monthsInYear = InternalIsLeapYear(y - 1) ? 13 : 12;
i += monthsInYear;
y--;
}
@@ -429,7 +488,8 @@ namespace System.Globalization {
}
int days = InternalGetDaysInMonth(y, m);
- if (d > days) {
+ if (d > days)
+ {
d = days;
}
DateTime dt = LunarToTime(time, y, m, d);
@@ -439,20 +499,23 @@ namespace System.Globalization {
}
- public override DateTime AddYears(DateTime time, int years) {
+ public override DateTime AddYears(DateTime time, int years)
+ {
CheckTicksRange(time.Ticks);
- int y=0; int m=0; int d=0;
+ int y = 0; int m = 0; int d = 0;
TimeToLunar(time, ref y, ref m, ref d);
y += years;
- if (m==13 && !InternalIsLeapYear(y)) {
+ if (m == 13 && !InternalIsLeapYear(y))
+ {
m = 12;
d = InternalGetDaysInMonth(y, m);
}
int DaysInMonths = InternalGetDaysInMonth(y, m);
- if (d > DaysInMonths) {
+ if (d > DaysInMonths)
+ {
d = DaysInMonths;
}
@@ -465,13 +528,14 @@ namespace System.Globalization {
// is an integer between 1 and [354|355 |383|384].
//
- public override int GetDayOfYear(DateTime time) {
+ public override int GetDayOfYear(DateTime time)
+ {
CheckTicksRange(time.Ticks);
- int y=0; int m=0; int d=0;
+ int y = 0; int m = 0; int d = 0;
TimeToLunar(time, ref y, ref m, ref d);
- for (int i=1; i<m ;i++)
+ for (int i = 1; i < m; i++)
{
d = d + InternalGetDaysInMonth(y, i);
}
@@ -482,10 +546,11 @@ namespace System.Globalization {
// value is an integer between 1 and 29 or 30.
//
- public override int GetDayOfMonth(DateTime time) {
+ public override int GetDayOfMonth(DateTime time)
+ {
CheckTicksRange(time.Ticks);
- int y=0; int m=0; int d=0;
+ int y = 0; int m = 0; int d = 0;
TimeToLunar(time, ref y, ref m, ref d);
return d;
@@ -494,7 +559,8 @@ namespace System.Globalization {
// 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) {
+ public override int GetDaysInYear(int year, int era)
+ {
year = CheckYearRange(year, era);
int Days = 0;
@@ -510,10 +576,11 @@ namespace System.Globalization {
// integer between 1 and 13.
//
- public override int GetMonth(DateTime time) {
+ public override int GetMonth(DateTime time)
+ {
CheckTicksRange(time.Ticks);
- int y=0; int m=0; int d=0;
+ int y = 0; int m = 0; int d = 0;
TimeToLunar(time, ref y, ref m, ref d);
return m;
@@ -523,10 +590,11 @@ namespace System.Globalization {
// integer between 1 and MaxCalendarYear.
//
- public override int GetYear(DateTime time) {
+ public override int GetYear(DateTime time)
+ {
CheckTicksRange(time.Ticks);
- int y=0; int m=0; int d=0;
+ int y = 0; int m = 0; int d = 0;
TimeToLunar(time, ref y, ref m, ref d);
return GetYear(y, time);
@@ -538,67 +606,75 @@ namespace System.Globalization {
// Thursday, 5 indicates Friday, and 6 indicates Saturday.
//
- public override DayOfWeek GetDayOfWeek(DateTime time) {
+ 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) {
+ public override int GetMonthsInYear(int year, int era)
+ {
year = CheckYearRange(year, era);
- return (InternalIsLeapYear(year)?13:12);
+ 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) {
+ 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) {
+ 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)));
+ 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) {
+ 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)));
+ 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) {
+ public override int GetLeapMonth(int year, int era)
+ {
year = CheckYearRange(year, era);
int month = GetYearInfo(year, LeapMonth);
- if (month>0)
+ if (month > 0)
{
- return (month+1);
+ return (month + 1);
}
return 0;
}
- internal bool InternalIsLeapYear(int year) {
- return (GetYearInfo(year, LeapMonth)!=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) {
+ public override bool IsLeapYear(int year, int era)
+ {
year = CheckYearRange(year, era);
return InternalIsLeapYear(year);
}
@@ -606,15 +682,19 @@ namespace System.Globalization {
private const int DEFAULT_GREGORIAN_TWO_DIGIT_YEAR_MAX = 2029;
- public override int TwoDigitYearMax {
- get {
- if (twoDigitYearMax == -1) {
+ 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 {
+ set
+ {
VerifyWritable();
if (value < 99 || value > MaxCalendarYear)
{
@@ -627,8 +707,10 @@ namespace System.Globalization {
}
- 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"));
}
@@ -638,6 +720,5 @@ namespace System.Globalization {
CheckYearRange(year, CurrentEra);
return (year);
}
-
}
}
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.cs b/src/mscorlib/src/System/Globalization/EncodingTable.cs
index 127cbffe63..e54dfd19b2 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.
//
@@ -51,34 +51,43 @@ namespace System.Globalization
// 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);
}
}
@@ -110,10 +119,10 @@ namespace System.Globalization
arrayEncodingInfo[i] = new EncodingInfo(codePageDataPtr[i].codePage, CodePageDataItem.CreateString(codePageDataPtr[i].Names, 0),
Environment.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.
@@ -123,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();
@@ -139,7 +149,8 @@ namespace System.Globalization
//
codePageObj = hashByName[name];
- if (codePageObj!=null) {
+ if (codePageObj != null)
+ {
return ((int)codePageObj);
}
@@ -151,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
@@ -162,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;
}
@@ -175,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.
//
@@ -200,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==========================
@@ -220,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/GregorianCalendar.cs b/src/mscorlib/src/System/Globalization/GregorianCalendar.cs
index 9083e6de27..d8a4db3838 100644
--- a/src/mscorlib/src/System/Globalization/GregorianCalendar.cs
+++ b/src/mscorlib/src/System/Globalization/GregorianCalendar.cs
@@ -2,22 +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.
-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;
-
+//
+// 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;
+
+namespace System.Globalization
+{
// This calendar recognizes two era values:
// 0 CurrentEra (AD)
// 1 BeforeCurrentEra (BC)
@@ -58,23 +59,23 @@ namespace System.Globalization {
private static volatile Calendar s_defaultInstance;
-#region Serialization
+ #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,
+ CultureInfo.CurrentCulture,
Environment.GetResourceString(
"Serialization_MemberOutOfRange"),
- "type",
+ "type",
"GregorianCalendar"));
}
}
-#endregion Serialization
+ #endregion Serialization
public override DateTime MinSupportedDateTime
{
@@ -111,8 +112,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,12 +124,15 @@ 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",
@@ -136,15 +142,19 @@ namespace System.Globalization {
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:
@@ -160,8 +170,10 @@ namespace System.Globalization {
}
}
- internal override int ID {
- get {
+ internal override int 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
@@ -210,7 +222,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,11 +252,13 @@ 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);
@@ -255,8 +269,9 @@ namespace System.Globalization {
// 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,7 +294,8 @@ 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(
@@ -303,7 +319,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,16 +380,20 @@ 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) {
+ 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",
1, MaxYear));
}
- if (month < 1 || month > 12) {
+ if (month < 1 || month > 12)
+ {
throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("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"));
@@ -384,9 +404,11 @@ 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),
@@ -407,9 +429,11 @@ namespace System.Globalization {
}
- public override int[] Eras {
- get {
- return (new int[] {ADEra} );
+ public override int[] Eras
+ {
+ get
+ {
+ return (new int[] { ADEra });
}
}
@@ -427,7 +451,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);
@@ -458,7 +483,8 @@ namespace System.Globalization {
public override bool IsLeapDay(int year, int month, int day, int era)
{
- if (month < 1 || month > 12) {
+ if (month < 1 || month > 12)
+ {
throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Range",
1, 12));
}
@@ -468,20 +494,24 @@ namespace System.Globalization {
{
throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
}
- if (year < 1 || year > MaxYear) {
+ if (year < 1 || year > MaxYear)
+ {
throw new ArgumentOutOfRangeException(
nameof(year),
Environment.GetResourceString("ArgumentOutOfRange_Range", 1, MaxYear));
}
- if (day < 1 || day > GetDaysInMonth(year, month)) {
+ if (day < 1 || day > GetDaysInMonth(year, month))
+ {
throw new ArgumentOutOfRangeException(nameof(day), Environment.GetResourceString("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);
@@ -497,7 +527,8 @@ namespace System.Globalization {
{
throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
}
- if (year < 1 || year > MaxYear) {
+ if (year < 1 || year > MaxYear)
+ {
throw new ArgumentOutOfRangeException(
nameof(year),
String.Format(
@@ -514,11 +545,13 @@ namespace System.Globalization {
public override bool IsLeapMonth(int year, int month, int era)
{
- if (era != CurrentEra && era != ADEra) {
+ if (era != CurrentEra && era != ADEra)
+ {
throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
}
- if (year < 1 || year > MaxYear) {
+ if (year < 1 || year > MaxYear)
+ {
throw new ArgumentOutOfRangeException(
nameof(year),
String.Format(
@@ -526,22 +559,25 @@ namespace System.Globalization {
Environment.GetResourceString("ArgumentOutOfRange_Range"), 1, MaxYear));
}
- if (month < 1 || month > 12) {
+ if (month < 1 || month > 12)
+ {
throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("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));
}
@@ -559,14 +595,17 @@ 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"));
}
- 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) {
+ 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);
}
result = DateTime.MinValue;
@@ -578,16 +617,20 @@ 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(
@@ -595,21 +638,23 @@ namespace System.Globalization {
Environment.GetResourceString("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"));
}
Contract.EndContractBlock();
- if (year > MaxYear) {
+ if (year > MaxYear)
+ {
throw new ArgumentOutOfRangeException(
nameof(year),
String.Format(
diff --git a/src/mscorlib/src/System/Globalization/GregorianCalendarHelper.cs b/src/mscorlib/src/System/Globalization/GregorianCalendarHelper.cs
index 062ae4818a..3536733cfe 100644
--- a/src/mscorlib/src/System/Globalization/GregorianCalendarHelper.cs
+++ b/src/mscorlib/src/System/Globalization/GregorianCalendarHelper.cs
@@ -3,26 +3,27 @@
// 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;
+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,57 +58,60 @@ 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
};
@@ -121,7 +125,7 @@ namespace System.Globalization {
// 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;
@@ -129,18 +133,19 @@ namespace System.Globalization {
// 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_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_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,26 +156,32 @@ 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"));
- }
+ Environment.GetResourceString("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,
+ Environment.GetResourceString("ArgumentOutOfRange_Range"),
+ m_EraInfo[i].minEraYear,
m_EraInfo[i].maxEraYear));
}
return (m_EraInfo[i].yearOffset + year);
@@ -178,31 +189,37 @@ namespace System.Globalization {
}
throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("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 +231,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 +241,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 +287,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"));
- }
+ }
// 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 +315,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,
+ Environment.GetResourceString("ArgumentOutOfRange_Range"),
+ 0,
MillisPerSecond - 1));
- }
- return (TimeSpan.TimeToTicks(hour, minute, second) + millisecond * TicksPerMillisecond);;
+ }
+ return (TimeSpan.TimeToTicks(hour, minute, second) + millisecond * TicksPerMillisecond); ;
}
throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("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,
+ Environment.GetResourceString("ArgumentOutOfRange_CalendarRange"),
m_Cal.MinSupportedDateTime,
m_Cal.MaxSupportedDateTime));
}
@@ -342,15 +365,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,
+ Environment.GetResourceString("ArgumentOutOfRange_Range"),
+ -120000,
120000));
}
Contract.EndContractBlock();
@@ -360,20 +384,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 +405,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 +414,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 +426,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 +450,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) {
+ if (month < 1 || month > 12)
+ {
throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("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,16 +473,18 @@ 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);
}
}
@@ -464,66 +492,74 @@ namespace System.Globalization {
}
- 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"));
- }
-
+ }
+
// 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++) {
+ 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"));
- }
+ }
// 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 +567,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)));
+ Environment.GetResourceString("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 +607,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);
+ Environment.GetResourceString("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,19 +648,23 @@ 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"));
+ Environment.GetResourceString("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(
@@ -628,6 +675,6 @@ namespace System.Globalization {
// the TwoDigitYearMax comparison.
return (year);
}
- }
+ }
}
diff --git a/src/mscorlib/src/System/Globalization/GregorianCalendarTypes.cs b/src/mscorlib/src/System/Globalization/GregorianCalendarTypes.cs
index 1af5e9221c..70cd11b0fe 100644
--- a/src/mscorlib/src/System/Globalization/GregorianCalendarTypes.cs
+++ b/src/mscorlib/src/System/Globalization/GregorianCalendarTypes.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;
+using System;
+namespace System.Globalization
+{
[Serializable]
- public enum GregorianCalendarTypes {
+ public enum GregorianCalendarTypes
+ {
Localized = Calendar.CAL_GREGORIAN,
USEnglish = Calendar.CAL_GREGORIAN_US,
MiddleEastFrench = Calendar.CAL_GREGORIAN_ME_FRENCH,
diff --git a/src/mscorlib/src/System/Globalization/HebrewCalendar.cs b/src/mscorlib/src/System/Globalization/HebrewCalendar.cs
index 190c3f17d2..ba54a67a77 100644
--- a/src/mscorlib/src/System/Globalization/HebrewCalendar.cs
+++ b/src/mscorlib/src/System/Globalization/HebrewCalendar.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;
- using System.Text;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
+using System;
+using System.Text;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+namespace System.Globalization
+{
////////////////////////////////////////////////////////////////////////////
//
// Rules for the Hebrew calendar:
@@ -51,22 +52,21 @@ namespace System.Globalization {
// 13. Elul (29 days)
//
////////////////////////////////////////////////////////////////////////////
- /*
- ** Calendar support range:
- ** Calendar Minimum Maximum
- ** ========== ========== ==========
- ** Gregorian 1583/01/01 2239/09/29
- ** Hebrew 5343/04/07 5999/13/29
- */
+ /*
+ ** 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.
+ // 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 class HebrewCalendar : Calendar
+ {
public static readonly int HebrewEra = 1;
internal const int DatePartYear = 0;
@@ -135,7 +135,7 @@ namespace System.Globalization {
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 TABLESIZE = (LastGregorianTableYear - FirstGregorianTableYear);
private const int MinHebrewYear = HebrewYearOf1AD + FirstGregorianTableYear; // == 5343
private const int MaxHebrewYear = HebrewYearOf1AD + LastGregorianTableYear; // == 5999
@@ -350,11 +350,14 @@ namespace System.Globalization {
// Construct an instance of gregorian calendar.
- public HebrewCalendar() {
+ public HebrewCalendar()
+ {
}
- internal override int ID {
- get {
+ internal override int ID
+ {
+ get
+ {
return (CAL_HEBREW);
}
}
@@ -370,9 +373,11 @@ namespace System.Globalization {
** 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) {
+ static private void CheckHebrewYearValue(int y, int era, String varName)
+ {
CheckEraRange(era);
- if (y > MaxHebrewYear || y < MinHebrewYear) {
+ if (y > MaxHebrewYear || y < MinHebrewYear)
+ {
throw new ArgumentOutOfRangeException(
varName,
String.Format(
@@ -393,9 +398,11 @@ namespace System.Globalization {
** Call CheckHebrewYearValue() before calling this to verify the year value is supported.
============================================================================*/
- private void CheckHebrewMonthValue(int year, int month, int era) {
+ private void CheckHebrewMonthValue(int year, int month, int era)
+ {
int monthsInYear = GetMonthsInYear(year, era);
- if (month < 1 || month > monthsInYear) {
+ if (month < 1 || month > monthsInYear)
+ {
throw new ArgumentOutOfRangeException(
nameof(month),
String.Format(
@@ -417,9 +424,11 @@ namespace System.Globalization {
** 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) {
+ private void CheckHebrewDayValue(int year, int month, int day, int era)
+ {
int daysInMonth = GetDaysInMonth(year, month, era);
- if (day < 1 || day > daysInMonth) {
+ if (day < 1 || day > daysInMonth)
+ {
throw new ArgumentOutOfRangeException(
nameof(day),
String.Format(
@@ -430,14 +439,18 @@ namespace System.Globalization {
}
}
- static internal void CheckEraRange(int era) {
- if (era != CurrentEra && era != HebrewEra) {
+ 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) {
+ 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.
@@ -449,8 +462,10 @@ namespace System.Globalization {
}
}
- static internal int GetResult(__DateBuffer result, int part) {
- switch (part) {
+ static internal int GetResult(__DateBuffer result, int part)
+ {
+ switch (part)
+ {
case DatePartYear:
return (result.year);
case DatePartMonth:
@@ -479,18 +494,20 @@ namespace System.Globalization {
**Exceptions:
============================================================================*/
- static internal int GetLunarMonthDay(int gregorianYear, __DateBuffer lunarDate) {
+ 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) {
+ if (index < 0 || index > TABLESIZE)
+ {
throw new ArgumentOutOfRangeException(nameof(gregorianYear));
}
index *= 2;
- lunarDate.day = HebrewTable[index];
+ lunarDate.day = HebrewTable[index];
// Get the type of the year. The value is from 1 to 6
int LunarYearType = HebrewTable[index + 1];
@@ -498,27 +515,28 @@ namespace System.Globalization {
//
// Get the Lunar Month.
//
- switch (lunarDate.day) {
- case ( 0 ) : // 1/1 is on Shvat 1
+ 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
+ case (30): // 1/1 is on Kislev 30
lunarDate.month = 3;
break;
- case ( 31 ) : // 1/1 is on Shvat 2
+ case (31): // 1/1 is on Shvat 2
lunarDate.month = 5;
lunarDate.day = 2;
break;
- case ( 32 ) : // 1/1 is on Shvat 3
+ case (32): // 1/1 is on Shvat 3
lunarDate.month = 5;
lunarDate.day = 3;
break;
- case ( 33 ) : // 1/1 is on Kislev 29
+ 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)
+ default: // 1/1 is on Tevet (This is the general case)
lunarDate.month = 4;
break;
}
@@ -528,7 +546,8 @@ namespace System.Globalization {
// 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)
+ {
// The Gregorian year, month, day value for ticks.
int gregorianYear, gregorianMonth, gregorianDay;
int hebrewYearType; // lunar year type
@@ -562,9 +581,9 @@ namespace System.Globalization {
//
// Store the values for the start of the new year - 1/1.
//
- result.year = lunarDate.year;
+ result.year = lunarDate.year;
result.month = lunarDate.month;
- result.day = lunarDate.day;
+ result.day = lunarDate.day;
//
// Get the absolute date from 1/1/1600.
@@ -574,7 +593,8 @@ namespace System.Globalization {
//
// If the requested date was 1/1, then we're done.
//
- if ((gregorianMonth == 1) && (gregorianDay == 1)) {
+ if ((gregorianMonth == 1) && (gregorianDay == 1))
+ {
return (GetResult(result, part));
}
@@ -588,7 +608,8 @@ namespace System.Globalization {
// If the requested date is within the current lunar month, then
// we're done.
//
- if ((NumDays + (long)lunarDate.day) <= (long)(LunarMonthLen[hebrewYearType, lunarDate.month])) {
+ if ((NumDays + (long)lunarDate.day) <= (long)(LunarMonthLen[hebrewYearType, lunarDate.month]))
+ {
result.day += (int)NumDays;
return (GetResult(result, part));
}
@@ -611,11 +632,13 @@ namespace System.Globalization {
// If NumDays is 1, then we are done. Otherwise, find the correct Hebrew month
// and day.
- if (NumDays > 1) {
+ if (NumDays > 1)
+ {
//
// See if we're on the correct Lunar month.
//
- while (NumDays > (long)(LunarMonthLen[hebrewYearType, result.month])) {
+ while (NumDays > (long)(LunarMonthLen[hebrewYearType, result.month]))
+ {
//
// Adjust the number of days and move to the next month.
//
@@ -625,7 +648,8 @@ namespace System.Globalization {
// 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)) {
+ if ((result.month > 13) || (LunarMonthLen[hebrewYearType, result.month] == 0))
+ {
//
// Adjust the Year.
//
@@ -664,8 +688,10 @@ namespace System.Globalization {
// y1.
//
- public override DateTime AddMonths(DateTime time, int months) {
- try {
+ 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);
@@ -673,19 +699,25 @@ namespace System.Globalization {
int monthsInYear;
int i;
- if (months >= 0) {
+ if (months >= 0)
+ {
i = m + months;
- while (i > (monthsInYear = GetMonthsInYear(y, CurrentEra))) {
+ while (i > (monthsInYear = GetMonthsInYear(y, CurrentEra)))
+ {
y++;
i -= monthsInYear;
}
- } else {
- if ((i = m + months) <= 0) {
+ }
+ else
+ {
+ if ((i = m + months) <= 0)
+ {
months = -months;
months -= m;
y--;
- while (months > (monthsInYear = GetMonthsInYear(y, CurrentEra))) {
+ while (months > (monthsInYear = GetMonthsInYear(y, CurrentEra)))
+ {
y--;
months -= monthsInYear;
}
@@ -695,7 +727,8 @@ namespace System.Globalization {
}
int days = GetDaysInMonth(y, i);
- if (d > days) {
+ if (d > days)
+ {
d = days;
}
return (new DateTime(ToDateTime(y, i, d, 0, 0, 0, 0).Ticks + (time.Ticks % TicksPerDay)));
@@ -721,7 +754,8 @@ namespace System.Globalization {
// parts of the result are the same as those of the specified DateTime.
//
- public override DateTime AddYears(DateTime time, int years) {
+ 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);
@@ -730,12 +764,14 @@ namespace System.Globalization {
CheckHebrewYearValue(y, Calendar.CurrentEra, nameof(years));
int months = GetMonthsInYear(y, CurrentEra);
- if (m > months) {
+ if (m > months)
+ {
m = months;
}
int days = GetDaysInMonth(y, m);
- if (d > days) {
+ if (d > days)
+ {
d = days;
}
@@ -748,7 +784,8 @@ namespace System.Globalization {
// value is an integer between 1 and 31.
//
- public override int GetDayOfMonth(DateTime time) {
+ public override int GetDayOfMonth(DateTime time)
+ {
return (GetDatePart(time.Ticks, DatePartDay));
}
@@ -758,13 +795,15 @@ namespace System.Globalization {
// Thursday, 5 indicates Friday, and 6 indicates Saturday.
//
- public override DayOfWeek GetDayOfWeek(DateTime time) {
+ 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) {
+ 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.
@@ -775,7 +814,8 @@ namespace System.Globalization {
// is an integer between 1 and 366.
//
- public override int GetDayOfYear(DateTime time) {
+ public override int GetDayOfYear(DateTime time)
+ {
// Get Hebrew year value of the specified time.
int year = GetYear(time);
DateTime beginOfYearDate;
@@ -806,15 +846,17 @@ namespace System.Globalization {
// month arguments.
//
- public override int GetDaysInMonth(int year, int month, int era) {
+ 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,
+ 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) {
+ if (monthDays == 0)
+ {
throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Month"));
}
return (monthDays);
@@ -823,14 +865,16 @@ namespace System.Globalization {
// 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) {
+ 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) {
+ if (LunarYearType < 4)
+ {
// common year: LunarYearType = 1, 2, 3
return (352 + LunarYearType);
}
@@ -839,15 +883,17 @@ namespace System.Globalization {
// Returns the era for the specified DateTime value.
- public override int GetEra(DateTime time) {
-
+ public override int GetEra(DateTime time)
+ {
return (HebrewEra);
}
- public override int[] Eras {
- get {
- return (new int[] {HebrewEra});
+ public override int[] Eras
+ {
+ get
+ {
+ return (new int[] { HebrewEra });
}
}
@@ -855,13 +901,15 @@ namespace System.Globalization {
// integer between 1 and 12.
//
- public override int GetMonth(DateTime time) {
+ 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) {
+ public override int GetMonthsInYear(int year, int era)
+ {
return (IsLeapYear(year, era) ? 13 : 12);
}
@@ -869,7 +917,8 @@ namespace System.Globalization {
// integer between 1 and 9999.
//
- public override int GetYear(DateTime time) {
+ public override int GetYear(DateTime time)
+ {
return (GetDatePart(time.Ticks, DatePartYear));
}
@@ -877,15 +926,20 @@ namespace System.Globalization {
// 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)) {
+ 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)) {
+ }
+ 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) {
+ if (month == 6 && day == 30)
+ {
return (true);
}
}
@@ -913,13 +967,16 @@ namespace System.Globalization {
// month is a leap month, or false if not.
//
- public override bool IsLeapMonth(int year, int month, int era) {
+ 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) {
+ if (isLeapYear)
+ {
+ if (month == 7)
+ {
return (true);
}
}
@@ -930,20 +987,24 @@ namespace System.Globalization {
// 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);
+ 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) {
+ private 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) {
+ if (swap)
+ {
// (month1, day1) < (month2, day2). Swap the values.
// The result will be a negative number.
int tempMonth, tempDay;
@@ -959,7 +1020,8 @@ namespace System.Globalization {
month1++;
// Add up the days.
- while (month1 < month2) {
+ while (month1 < month2)
+ {
days += LunarMonthLen[lunarYearType, month1++];
}
days += day2;
@@ -992,7 +1054,8 @@ namespace System.Globalization {
============================================================================*/
- static DateTime HebrewToGregorian(int hebrewYear, int hebrewMonth, int hebrewDay, int hour, int minute, int second, int millisecond) {
+ private 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;
@@ -1000,7 +1063,8 @@ namespace System.Globalization {
__DateBuffer hebrewDateOfJan1 = new __DateBuffer(); // year value is unused.
int lunarYearType = GetLunarMonthDay(gregorianYear, hebrewDateOfJan1);
- if ((hebrewMonth == hebrewDateOfJan1.month) && (hebrewDay == hebrewDateOfJan1.day)) {
+ if ((hebrewMonth == hebrewDateOfJan1.month) && (hebrewDay == hebrewDateOfJan1.day))
+ {
return (new DateTime(gregorianYear, 1, 1, hour, minute, second, millisecond));
}
@@ -1014,7 +1078,8 @@ namespace System.Globalization {
// 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) {
+ 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);
@@ -1026,15 +1091,19 @@ namespace System.Globalization {
private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 5790;
- public override int TwoDigitYearMax {
- get {
- if (twoDigitYearMax == -1) {
+ public override int TwoDigitYearMax
+ {
+ get
+ {
+ if (twoDigitYearMax == -1)
+ {
twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX);
}
return (twoDigitYearMax);
}
- set {
+ set
+ {
VerifyWritable();
if (value == 99)
{
@@ -1049,18 +1118,22 @@ namespace System.Globalization {
}
- 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"));
}
Contract.EndContractBlock();
- if (year < 100) {
+ if (year < 100)
+ {
return (base.ToFourDigitYear(year));
}
- if (year > MaxHebrewYear || year < MinHebrewYear) {
+ if (year > MaxHebrewYear || year < MinHebrewYear)
+ {
throw new ArgumentOutOfRangeException(
nameof(year),
String.Format(
@@ -1072,13 +1145,12 @@ namespace System.Globalization {
return (year);
}
- internal class __DateBuffer {
+ 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
index 5517cb14ea..b868d3eed7 100644
--- a/src/mscorlib/src/System/Globalization/HebrewNumber.cs
+++ b/src/mscorlib/src/System/Globalization/HebrewNumber.cs
@@ -3,12 +3,13 @@
// 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;
+using System;
+using System.Text;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+namespace System.Globalization
+{
////////////////////////////////////////////////////////////////////////////
//
// Used in HebrewNumber.ParseByChar to maintain the context information (
@@ -16,15 +17,17 @@ namespace System.Globalization {
// when parsing Hebrew number character by character.
//
////////////////////////////////////////////////////////////////////////////
-
- internal struct HebrewNumberParsingContext {
+
+ 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) {
+ public HebrewNumberParsingContext(int result)
+ {
// Set the start state of the state machine for parsing Hebrew numbers.
state = HebrewNumber.HS.Start;
this.result = result;
@@ -36,8 +39,9 @@ namespace System.Globalization {
// Please see ParseByChar() for comments about different states defined here.
//
////////////////////////////////////////////////////////////////////////////
-
- internal enum HebrewNumberParsingState {
+
+ internal enum HebrewNumberParsingState
+ {
InvalidHebrewNumber,
NotHebrewDigit,
FoundEndOfHebrewNumber,
@@ -57,12 +61,13 @@ namespace System.Globalization {
// 5000 will be subtracted from the value.
//
////////////////////////////////////////////////////////////////////////////
-
- internal class HebrewNumber {
+ 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() {
+ private HebrewNumber()
+ {
}
////////////////////////////////////////////////////////////////////////////
@@ -85,7 +90,8 @@ namespace System.Globalization {
//
////////////////////////////////////////////////////////////////////////////
- internal static String ToString(int Number) {
+ internal static String ToString(int Number)
+ {
char cTens = '\x0';
char cUnits; // tens and units chars
int Hundreds, Tens; // hundreds and tens values
@@ -95,30 +101,34 @@ namespace System.Globalization {
//
// Adjust the number if greater than 5000.
//
- if (Number > 5000) {
+ if (Number > 5000)
+ {
Number -= 5000;
}
- Debug.Assert(Number > 0 && Number <= 999, "Number is out of range.");;
+ Debug.Assert(Number > 0 && Number <= 999, "Number is out of range."); ;
//
// Get the Hundreds.
//
Hundreds = Number / 100;
- if (Hundreds > 0) {
+ 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++) {
+ for (int i = 0; i < (Hundreds / 4); i++)
+ {
szHebrew.Append('\x05ea');
}
int remains = Hundreds % 4;
- if (remains > 0) {
+ if (remains > 0)
+ {
szHebrew.Append((char)((int)'\x05e6' + remains));
}
}
@@ -129,35 +139,36 @@ namespace System.Globalization {
Tens = Number / 10;
Number %= 10;
- switch (Tens) {
- case ( 0 ) :
+ switch (Tens)
+ {
+ case (0):
cTens = '\x0';
break;
- case ( 1 ) :
+ case (1):
cTens = '\x05d9'; // Hebrew Letter Yod
break;
- case ( 2 ) :
+ case (2):
cTens = '\x05db'; // Hebrew Letter Kaf
break;
- case ( 3 ) :
+ case (3):
cTens = '\x05dc'; // Hebrew Letter Lamed
break;
- case ( 4 ) :
+ case (4):
cTens = '\x05de'; // Hebrew Letter Mem
break;
- case ( 5 ) :
+ case (5):
cTens = '\x05e0'; // Hebrew Letter Nun
break;
- case ( 6 ) :
+ case (6):
cTens = '\x05e1'; // Hebrew Letter Samekh
break;
- case ( 7 ) :
+ case (7):
cTens = '\x05e2'; // Hebrew Letter Ayin
break;
- case ( 8 ) :
+ case (8):
cTens = '\x05e4'; // Hebrew Letter Pe
break;
- case ( 9 ) :
+ case (9):
cTens = '\x05e6'; // Hebrew Letter Tsadi
break;
}
@@ -168,32 +179,39 @@ namespace System.Globalization {
cUnits = (char)(Number > 0 ? ((int)'\x05d0' + Number - 1) : 0);
if ((cUnits == '\x05d4') && // Hebrew Letter He (5)
- (cTens == '\x05d9')) { // Hebrew Letter Yod (10)
+ (cTens == '\x05d9'))
+ { // Hebrew Letter Yod (10)
cUnits = '\x05d5'; // Hebrew Letter Vav (6)
- cTens = '\x05d8'; // Hebrew Letter Tet (9)
+ cTens = '\x05d8'; // Hebrew Letter Tet (9)
}
if ((cUnits == '\x05d5') && // Hebrew Letter Vav (6)
- (cTens == '\x05d9')) { // Hebrew Letter Yod (10)
+ (cTens == '\x05d9'))
+ { // Hebrew Letter Yod (10)
cUnits = '\x05d6'; // Hebrew Letter Zayin (7)
- cTens = '\x05d8'; // Hebrew Letter Tet (9)
+ cTens = '\x05d8'; // Hebrew Letter Tet (9)
}
//
// Copy the appropriate info to the given buffer.
//
- if (cTens != '\x0') {
+ if (cTens != '\x0')
+ {
szHebrew.Append(cTens);
}
- if (cUnits != '\x0') {
+ if (cUnits != '\x0')
+ {
szHebrew.Append(cUnits);
}
- if (szHebrew.Length > 1) {
+ if (szHebrew.Length > 1)
+ {
szHebrew.Insert(szHebrew.Length - 1, '"');
- } else {
+ }
+ else
+ {
szHebrew.Append('\'');
}
@@ -209,12 +227,13 @@ namespace System.Globalization {
// state machine.
//
////////////////////////////////////////////////////////////////////////////
-
- enum HebrewToken {
+
+ private enum HebrewToken
+ {
Invalid = -1,
Digit400 = 0,
Digit200_300 = 1,
- Digit100 = 2,
+ Digit100 = 2,
Digit10 = 3, // 10 ~ 90
Digit1 = 4, // 1, 2, 3, 4, 5, 8,
Digit6_7 = 5,
@@ -229,11 +248,13 @@ namespace System.Globalization {
// This class is used to map a token into its Hebrew digit value.
//
////////////////////////////////////////////////////////////////////////////
-
- class HebrewValue {
+
+ private class HebrewValue
+ {
internal HebrewToken token;
internal int value;
- internal HebrewValue(HebrewToken token, int value) {
+ internal HebrewValue(HebrewToken token, int value)
+ {
this.token = token;
this.value = value;
}
@@ -243,7 +264,7 @@ namespace System.Globalization {
// 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 = {
+ private static HebrewValue[] HebrewValues = {
new HebrewValue(HebrewToken.Digit1, 1) , // '\x05d0
new HebrewValue(HebrewToken.Digit1, 2) , // '\x05d1
new HebrewValue(HebrewToken.Digit1, 3) , // '\x05d2
@@ -273,8 +294,8 @@ namespace System.Globalization {
new HebrewValue(HebrewToken.Digit400, 400) , // '\x05ea;
};
- const int minHebrewNumberCh = 0x05d0;
- static char maxHebrewNumberCh = (char)(minHebrewNumberCh + HebrewValues.Length - 1);
+ private const int minHebrewNumberCh = 0x05d0;
+ private static char maxHebrewNumberCh = (char)(minHebrewNumberCh + HebrewValues.Length - 1);
////////////////////////////////////////////////////////////////////////////
//
@@ -283,19 +304,20 @@ namespace System.Globalization {
// DQ = Double Quote
//
////////////////////////////////////////////////////////////////////////////
-
- internal enum HS {
+
+ 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
+ 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
+ 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,
@@ -309,7 +331,7 @@ namespace System.Globalization {
//
// The state machine for Hebrew number pasing.
//
- readonly static HS[][] NumberPasingState = {
+ private 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},
@@ -330,7 +352,7 @@ namespace System.Globalization {
/* 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:
@@ -348,32 +370,44 @@ namespace System.Globalization {
// continue to parse incoming characters.
//
////////////////////////////////////////////////////////////////////////
-
- internal static HebrewNumberParsingState ParseByChar(char ch, ref HebrewNumberParsingContext context) {
+
+ internal static HebrewNumberParsingState ParseByChar(char ch, ref HebrewNumberParsingContext context)
+ {
HebrewToken token;
- if (ch == '\'') {
+ if (ch == '\'')
+ {
token = HebrewToken.SingleQuote;
- } else if (ch == '\"') {
+ }
+ else if (ch == '\"')
+ {
token = HebrewToken.DoubleQuote;
- } else {
- int index = (int)ch - minHebrewNumberCh;
- if (index >= 0 && index < HebrewValues.Length ) {
+ }
+ else
+ {
+ int index = (int)ch - minHebrewNumberCh;
+ if (index >= 0 && index < HebrewValues.Length)
+ {
token = HebrewValues[index].token;
- if (token == HebrewToken.Invalid) {
+ if (token == HebrewToken.Invalid)
+ {
return (HebrewNumberParsingState.NotHebrewDigit);
}
context.result += HebrewValues[index].value;
- } else {
+ }
+ else
+ {
// Not in valid Hebrew digit range.
return (HebrewNumberParsingState.NotHebrewDigit);
}
}
context.state = NumberPasingState[(int)context.state][(int)token];
- if (context.state == HS._err) {
+ if (context.state == HS._err)
+ {
// Invalid Hebrew state. This indicates an incorrect Hebrew number.
return (HebrewNumberParsingState.InvalidHebrewNumber);
- }
- if (context.state == HS.END) {
+ }
+ if (context.state == HS.END)
+ {
// Reach a terminal state.
return (HebrewNumberParsingState.FoundEndOfHebrewNumber);
}
@@ -391,13 +425,14 @@ namespace System.Globalization {
// true if the specified character is a valid Hebrew number character.
//
////////////////////////////////////////////////////////////////////////
-
- internal static bool IsDigit(char ch) {
- if (ch >= minHebrewNumberCh && ch <= maxHebrewNumberCh) {
+
+ 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/Globalization/HijriCalendar.cs b/src/mscorlib/src/System/Globalization/HijriCalendar.cs
index 061d380285..9eeab44a81 100644
--- a/src/mscorlib/src/System/Globalization/HijriCalendar.cs
+++ b/src/mscorlib/src/System/Globalization/HijriCalendar.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.Globalization {
-
+namespace System.Globalization
+{
using System;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
@@ -40,18 +40,17 @@ namespace System.Globalization {
// 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
- */
+ /*
+ ** 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 class HijriCalendar : Calendar
+ {
public static readonly int HijriEra = 1;
internal const int DatePartYear = 0;
@@ -62,7 +61,7 @@ namespace System.Globalization {
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 readonly int[] HijriMonthDays = { 0, 30, 59, 89, 118, 148, 177, 207, 236, 266, 295, 325, 355 };
//internal static Calendar m_defaultInstance;
@@ -129,11 +128,14 @@ namespace System.Globalization {
// Construct an instance of Hijri calendar.
- public HijriCalendar() {
+ public HijriCalendar()
+ {
}
- internal override int ID {
- get {
+ internal override int ID
+ {
+ get
+ {
return (CAL_HIJRI);
}
}
@@ -158,8 +160,9 @@ namespace System.Globalization {
**Exceptions:
============================================================================*/
- long GetAbsoluteDateHijri(int y, int m, int d) {
- return (long)(DaysUpToHijriYear(y) + HijriMonthDays[m-1] + d - 1 - HijriAdjustment);
+ private long GetAbsoluteDateHijri(int y, int m, int d)
+ {
+ return (long)(DaysUpToHijriYear(y) + HijriMonthDays[m - 1] + d - 1 - HijriAdjustment);
}
/*=================================DaysUpToHijriYear==========================
@@ -171,7 +174,8 @@ namespace System.Globalization {
**Notes:
============================================================================*/
- long DaysUpToHijriYear(int HijriYear) {
+ private 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
@@ -191,9 +195,10 @@ namespace System.Globalization {
// Compute the number of absolute days up to the given year.
//
NumDays = ((NumYear30 * 10631L) / 30L) + 227013L;
- while (NumYearsLeft > 0) {
+ while (NumYearsLeft > 0)
+ {
// Common year is 354 days, and leap year is 355 days.
- NumDays += 354 + (IsLeapYear(NumYearsLeft, CurrentEra) ? 1: 0);
+ NumDays += 354 + (IsLeapYear(NumYearsLeft, CurrentEra) ? 1 : 0);
NumYearsLeft--;
}
@@ -204,18 +209,23 @@ namespace System.Globalization {
}
- public int HijriAdjustment {
- get {
- if (m_HijriAdvance == Int32.MinValue) {
+ 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 {
+ set
+ {
// NOTE: Check the value of Min/MaxAdavncedHijri with Arabic speakers to see if the assumption is good.
- if (value < MinAdvancedHijri || value > MaxAdvancedHijri) {
+ if (value < MinAdvancedHijri || value > MaxAdvancedHijri)
+ {
throw new ArgumentOutOfRangeException(
nameof(HijriAdjustment),
String.Format(
@@ -247,13 +257,15 @@ namespace System.Globalization {
** "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() {
+ private static int GetAdvanceHijriDate()
+ {
#if FEATURE_WIN32_REGISTRY
int hijriAdvance = 0;
Microsoft.Win32.RegistryKey key = null;
- try {
+ try
+ {
// Open in read-only mode.
// Use InternalOpenSubKey so that we avoid the security check.
key = Microsoft.Win32.Registry.CurrentUser.InternalOpenSubKey(InternationalRegKey, false);
@@ -262,21 +274,28 @@ namespace System.Globalization {
catch (ObjectDisposedException) { return 0; }
catch (ArgumentException) { return 0; }
- if (key != null) {
- try {
+ if (key != null)
+ {
+ try
+ {
Object value = key.InternalGetValue(HijriAdvanceRegKeyEntry, null, false, false);
- if (value == null) {
+ if (value == null)
+ {
return (0);
}
String str = value.ToString();
- if (String.Compare(str, 0, HijriAdvanceRegKeyEntry, 0, HijriAdvanceRegKeyEntry.Length, StringComparison.OrdinalIgnoreCase) == 0) {
+ if (String.Compare(str, 0, HijriAdvanceRegKeyEntry, 0, HijriAdvanceRegKeyEntry.Length, StringComparison.OrdinalIgnoreCase) == 0)
+ {
if (str.Length == HijriAdvanceRegKeyEntry.Length)
hijriAdvance = -1;
- else {
+ else
+ {
str = str.Substring(HijriAdvanceRegKeyEntry.Length);
- try {
+ try
+ {
int advance = Int32.Parse(str.ToString(), CultureInfo.InvariantCulture);
- if ((advance >= MinAdvancedHijri) && (advance <= MaxAdvancedHijri)) {
+ if ((advance >= MinAdvancedHijri) && (advance <= MaxAdvancedHijri))
+ {
hijriAdvance = advance;
}
}
@@ -288,10 +307,10 @@ namespace System.Globalization {
}
}
}
- finally {
+ finally
+ {
key.Close();
}
-
}
return (hijriAdvance);
@@ -300,8 +319,10 @@ namespace System.Globalization {
#endif // FEATURE_WIN32_REGISTRY
}
- static internal void CheckTicksRange(long ticks) {
- if (ticks < calendarMinValue.Ticks || ticks > calendarMaxValue.Ticks) {
+ static internal void CheckTicksRange(long ticks)
+ {
+ if (ticks < calendarMinValue.Ticks || ticks > calendarMaxValue.Ticks)
+ {
throw new ArgumentOutOfRangeException(
"time",
String.Format(
@@ -312,15 +333,19 @@ namespace System.Globalization {
}
}
- static internal void CheckEraRange(int era) {
- if (era != CurrentEra && era != HijriEra) {
+ 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) {
+ static internal void CheckYearRange(int year, int era)
+ {
CheckEraRange(era);
- if (year < 1 || year > MaxCalendarYear) {
+ if (year < 1 || year > MaxCalendarYear)
+ {
throw new ArgumentOutOfRangeException(
nameof(year),
String.Format(
@@ -331,10 +356,13 @@ namespace System.Globalization {
}
}
- static internal void CheckYearMonthRange(int year, int month, int era) {
+ static internal void CheckYearMonthRange(int year, int month, int era)
+ {
CheckYearRange(year, era);
- if (year == MaxCalendarYear) {
- if (month > MaxCalendarMonth) {
+ if (year == MaxCalendarYear)
+ {
+ if (month > MaxCalendarMonth)
+ {
throw new ArgumentOutOfRangeException(
nameof(month),
String.Format(
@@ -345,7 +373,8 @@ namespace System.Globalization {
}
}
- if (month < 1 || month > 12) {
+ if (month < 1 || month > 12)
+ {
throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Month"));
}
}
@@ -363,7 +392,8 @@ namespace System.Globalization {
** From here, we can get the correct Hijri year.
============================================================================*/
- internal virtual int GetDatePart(long ticks, int part) {
+ internal virtual int GetDatePart(long ticks, int part)
+ {
int HijriYear; // Hijri year
int HijriMonth; // Hijri month
int HijriDay; // Hijri day
@@ -390,19 +420,26 @@ namespace System.Globalization {
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) {
+ if (NumDays < daysToHijriYear)
+ {
daysToHijriYear -= daysOfHijriYear;
HijriYear--;
- } else if (NumDays == daysToHijriYear) {
+ }
+ else if (NumDays == daysToHijriYear)
+ {
HijriYear--;
daysToHijriYear -= GetDaysInYear(HijriYear, CurrentEra);
- } else {
- if (NumDays > daysToHijriYear + daysOfHijriYear) {
+ }
+ else
+ {
+ if (NumDays > daysToHijriYear + daysOfHijriYear)
+ {
daysToHijriYear += daysOfHijriYear;
HijriYear++;
}
}
- if (part == DatePartYear) {
+ if (part == DatePartYear)
+ {
return (HijriYear);
}
@@ -413,16 +450,19 @@ namespace System.Globalization {
HijriMonth = 1;
NumDays -= daysToHijriYear;
- if (part == DatePartDayOfYear) {
+ if (part == DatePartDayOfYear)
+ {
return ((int)NumDays);
}
- while ((HijriMonth <= 12) && (NumDays > HijriMonthDays[HijriMonth - 1])) {
+ while ((HijriMonth <= 12) && (NumDays > HijriMonthDays[HijriMonth - 1]))
+ {
HijriMonth++;
}
HijriMonth--;
- if (part == DatePartMonth) {
+ if (part == DatePartMonth)
+ {
return (HijriMonth);
}
@@ -431,7 +471,8 @@ namespace System.Globalization {
//
HijriDay = (int)(NumDays - HijriMonthDays[HijriMonth - 1]);
- if (part == DatePartDay) {
+ if (part == DatePartDay)
+ {
return (HijriDay);
}
// Incorrect part value.
@@ -456,8 +497,10 @@ namespace System.Globalization {
// y1.
//
- public override DateTime AddMonths(DateTime time, int months) {
- if (months < -120000 || months > 120000) {
+ public override DateTime AddMonths(DateTime time, int months)
+ {
+ if (months < -120000 || months > 120000)
+ {
throw new ArgumentOutOfRangeException(
nameof(months),
String.Format(
@@ -472,18 +515,22 @@ 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 days = GetDaysInMonth(y, m);
- if (d > days) {
+ if (d > days)
+ {
d = days;
}
- long ticks = GetAbsoluteDateHijri(y, m, d)* TicksPerDay + (time.Ticks % TicksPerDay);
+ long ticks = GetAbsoluteDateHijri(y, m, d) * TicksPerDay + (time.Ticks % TicksPerDay);
Calendar.CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime);
return (new DateTime(ticks));
}
@@ -497,7 +544,8 @@ namespace System.Globalization {
// parts of the result are the same as those of the specified DateTime.
//
- public override DateTime AddYears(DateTime time, int years) {
+ public override DateTime AddYears(DateTime time, int years)
+ {
return (AddMonths(time, years * 12));
}
@@ -505,7 +553,8 @@ namespace System.Globalization {
// value is an integer between 1 and 31.
//
- public override int GetDayOfMonth(DateTime time) {
+ public override int GetDayOfMonth(DateTime time)
+ {
return (GetDatePart(time.Ticks, DatePartDay));
}
@@ -515,7 +564,8 @@ namespace System.Globalization {
// Thursday, 5 indicates Friday, and 6 indicates Saturday.
//
- public override DayOfWeek GetDayOfWeek(DateTime time) {
+ public override DayOfWeek GetDayOfWeek(DateTime time)
+ {
return ((DayOfWeek)((int)(time.Ticks / TicksPerDay + 1) % 7));
}
@@ -523,7 +573,8 @@ namespace System.Globalization {
// is an integer between 1 and 366.
//
- public override int GetDayOfYear(DateTime time) {
+ public override int GetDayOfYear(DateTime time)
+ {
return (GetDatePart(time.Ticks, DatePartDayOfYear));
}
@@ -531,9 +582,11 @@ namespace System.Globalization {
// month arguments.
//
[Pure]
- public override int GetDaysInMonth(int year, int month, int era) {
+ public override int GetDaysInMonth(int year, int month, int era)
+ {
CheckYearMonthRange(year, month, era);
- if (month == 12) {
+ if (month == 12)
+ {
// For the 12th month, leap year has 30 days, and common year has 29 days.
return (IsLeapYear(year, CurrentEra) ? 30 : 29);
}
@@ -544,23 +597,27 @@ namespace System.Globalization {
// 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) {
+ 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);
+ return (IsLeapYear(year, CurrentEra) ? 355 : 354);
}
// Returns the era for the specified DateTime value.
- public override int GetEra(DateTime time) {
+ public override int GetEra(DateTime time)
+ {
CheckTicksRange(time.Ticks);
return (HijriEra);
}
- public override int[] Eras {
- get {
- return (new int[] {HijriEra});
+ public override int[] Eras
+ {
+ get
+ {
+ return (new int[] { HijriEra });
}
}
@@ -568,13 +625,15 @@ namespace System.Globalization {
// integer between 1 and 12.
//
- public override int GetMonth(DateTime time) {
+ 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) {
+ public override int GetMonthsInYear(int year, int era)
+ {
CheckYearRange(year, era);
return (12);
}
@@ -583,7 +642,8 @@ namespace System.Globalization {
// integer between 1 and MaxCalendarYear.
//
- public override int GetYear(DateTime time) {
+ public override int GetYear(DateTime time)
+ {
return (GetDatePart(time.Ticks, DatePartYear));
}
@@ -591,10 +651,12 @@ namespace System.Globalization {
// the date is a leap day, or false if not.
//
- public override bool IsLeapDay(int year, int month, int day, int era) {
+ 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) {
+ if (day < 1 || day > daysInMonth)
+ {
throw new ArgumentOutOfRangeException(
nameof(day),
String.Format(
@@ -620,7 +682,8 @@ namespace System.Globalization {
// month is a leap month, or false if not.
//
- public override bool IsLeapMonth(int year, int month, int era) {
+ public override bool IsLeapMonth(int year, int month, int era)
+ {
CheckYearMonthRange(year, month, era);
return (false);
}
@@ -629,7 +692,8 @@ namespace System.Globalization {
// year is a leap year, or false if not.
//
- public override bool IsLeapYear(int year, int era) {
+ public override bool IsLeapYear(int year, int era)
+ {
CheckYearRange(year, era);
return ((((year * 11) + 14) % 30) < 11);
}
@@ -637,10 +701,12 @@ namespace System.Globalization {
// 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) {
+ 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) {
+ if (day < 1 || day > daysInMonth)
+ {
BCLDebug.Log("year = " + year + ", month = " + month + ", day = " + day);
throw new ArgumentOutOfRangeException(
nameof(day),
@@ -653,9 +719,12 @@ namespace System.Globalization {
long lDate = GetAbsoluteDateHijri(year, month, day);
- if (lDate >= 0) {
+ if (lDate >= 0)
+ {
return (new DateTime(lDate * GregorianCalendar.TicksPerDay + TimeToTicks(hour, minute, second, millisecond)));
- } else {
+ }
+ else
+ {
throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("ArgumentOutOfRange_BadYearMonthDay"));
}
}
@@ -663,15 +732,19 @@ namespace System.Globalization {
private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 1451;
- public override int TwoDigitYearMax {
- get {
- if (twoDigitYearMax == -1) {
+ public override int TwoDigitYearMax
+ {
+ get
+ {
+ if (twoDigitYearMax == -1)
+ {
twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX);
}
return (twoDigitYearMax);
}
- set {
+ set
+ {
VerifyWritable();
if (value < 99 || value > MaxCalendarYear)
{
@@ -682,25 +755,28 @@ namespace System.Globalization {
Environment.GetResourceString("ArgumentOutOfRange_Range"),
99,
MaxCalendarYear));
-
}
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"));
}
Contract.EndContractBlock();
- if (year < 100) {
+ if (year < 100)
+ {
return (base.ToFourDigitYear(year));
}
- if (year > MaxCalendarYear) {
+ if (year > MaxCalendarYear)
+ {
throw new ArgumentOutOfRangeException(
nameof(year),
String.Format(
@@ -711,6 +787,5 @@ namespace System.Globalization {
}
return (year);
}
-
}
}
diff --git a/src/mscorlib/src/System/Globalization/IdnMapping.cs b/src/mscorlib/src/System/Globalization/IdnMapping.cs
index bf75f5be3c..f3a70d6321 100644
--- a/src/mscorlib/src/System/Globalization/IdnMapping.cs
+++ b/src/mscorlib/src/System/Globalization/IdnMapping.cs
@@ -57,36 +57,36 @@ HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
*/
+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;
+
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
{
// Legal name lengths for domain names
- const int M_labelLimit = 63; // Not including dots
- const int M_defaultNameLimit = 255; // Including dots
+ private const int M_labelLimit = 63; // Not including dots
+ private const int M_defaultNameLimit = 255; // Including dots
// IDNA prefix
- const String M_strAcePrefix = "xn--";
+ private const String M_strAcePrefix = "xn--";
// Legal "dot" seperators (i.e: . in www.microsoft.com)
- static char[] M_Dots =
+ private static char[] M_Dots =
{
'.', '\u3002', '\uFF0E', '\uFF61'
};
- bool m_bAllowUnassigned;
- bool m_bUseStd3AsciiRules;
+ private bool m_bAllowUnassigned;
+ private bool m_bUseStd3AsciiRules;
public IdnMapping()
{
@@ -96,12 +96,12 @@ namespace System.Globalization
{
get
{
- return this.m_bAllowUnassigned;
+ return m_bAllowUnassigned;
}
set
{
- this.m_bAllowUnassigned = value;
+ m_bAllowUnassigned = value;
}
}
@@ -109,12 +109,12 @@ namespace System.Globalization
{
get
{
- return this.m_bUseStd3AsciiRules;
+ return m_bUseStd3AsciiRules;
}
set
{
- this.m_bUseStd3AsciiRules = value;
+ m_bUseStd3AsciiRules = value;
}
}
@@ -126,7 +126,7 @@ namespace System.Globalization
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);
}
@@ -165,7 +165,7 @@ namespace System.Globalization
if (unicode[unicode.Length - 1] <= 0x1f)
{
throw new ArgumentException(
- Environment.GetResourceString("Argument_InvalidCharSequence", unicode.Length-1 ),
+ Environment.GetResourceString("Argument_InvalidCharSequence", unicode.Length - 1),
nameof(unicode));
}
@@ -206,12 +206,12 @@ namespace System.Globalization
Environment.GetResourceString("Argument_InvalidCharSequence", unicode.Length - 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;
-
+ 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)
{
lastError = Marshal.GetLastWin32Error();
@@ -219,12 +219,12 @@ namespace System.Globalization
{
throw new ArgumentException(Environment.GetResourceString("Argument_IdnIllegalName"), nameof(unicode));
}
-
+
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex"), nameof(unicode));
}
- char [] output = new char[length];
-
+ char[] output = new char[length];
+
length = IdnToAscii(flags, unicode, unicode.Length, output, length);
if (length == 0)
{
@@ -233,10 +233,10 @@ namespace System.Globalization
{
throw new ArgumentException(Environment.GetResourceString("Argument_IdnIllegalName"), nameof(unicode));
}
-
+
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex"), nameof(unicode));
}
-
+
return new String(output, 0, length);
}
@@ -248,14 +248,14 @@ namespace System.Globalization
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)
{
- 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"));
@@ -270,7 +270,7 @@ namespace System.Globalization
// 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"),
+ throw new ArgumentException(Environment.GetResourceString("Argument_IdnBadPunycode"),
nameof(ascii));
Contract.EndContractBlock();
@@ -293,38 +293,38 @@ namespace System.Globalization
return strUnicode;
}
-
+
private string GetUnicodeUsingOS(string ascii)
{
- 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;
-
+ 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)
{
lastError = Marshal.GetLastWin32Error();
if (lastError == ERROR_INVALID_NAME)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_IdnIllegalName"), nameof(ascii));
+ throw new ArgumentException(Environment.GetResourceString("Argument_IdnIllegalName"), nameof(ascii));
}
-
+
throw new ArgumentException(Environment.GetResourceString("Argument_IdnBadPunycode"), nameof(ascii));
}
- char [] output = new char[length];
-
+ char[] output = new char[length];
+
length = IdnToUnicode(flags, ascii, ascii.Length, output, length);
if (length == 0)
{
lastError = Marshal.GetLastWin32Error();
if (lastError == ERROR_INVALID_NAME)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_IdnIllegalName"), nameof(ascii));
+ throw new ArgumentException(Environment.GetResourceString("Argument_IdnIllegalName"), nameof(ascii));
}
-
+
throw new ArgumentException(Environment.GetResourceString("Argument_IdnBadPunycode"), nameof(ascii));
}
-
+
return new String(output, 0, length);
}
@@ -334,8 +334,8 @@ namespace System.Globalization
if (that != null)
{
- return this.m_bAllowUnassigned == that.m_bAllowUnassigned &&
- this.m_bUseStd3AsciiRules == that.m_bUseStd3AsciiRules;
+ return m_bAllowUnassigned == that.m_bAllowUnassigned &&
+ m_bUseStd3AsciiRules == that.m_bUseStd3AsciiRules;
}
return (false);
@@ -343,11 +343,11 @@ namespace System.Globalization
public override int GetHashCode()
{
- return (this.m_bAllowUnassigned ? 100 : 200) + (this.m_bUseStd3AsciiRules ? 1000 : 2000);
+ return (m_bAllowUnassigned ? 100 : 200) + (m_bUseStd3AsciiRules ? 1000 : 2000);
}
// Helpers
- static bool IsSupplementary(int cTest)
+ private static bool IsSupplementary(int cTest)
{
return cTest >= 0x10000;
}
@@ -356,14 +356,14 @@ namespace System.Globalization
// 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)
+ private static bool IsDot(char c)
{
return c == '.' || c == '\u3002' || c == '\uFF0E' || c == '\uFF61';
}
// See if we're only ASCII
- static bool ValidateStd3AndAscii(string unicode, bool bUseStd3, bool bCheckAscii)
+ private static bool ValidateStd3AndAscii(string unicode, bool bUseStd3, bool bCheckAscii)
{
// If its empty, then its too small
if (unicode.Length == 0)
@@ -380,7 +380,7 @@ namespace System.Globalization
if (unicode[i] <= 0x1f)
{
throw new ArgumentException(
- Environment.GetResourceString("Argument_InvalidCharSequence", i ),
+ Environment.GetResourceString("Argument_InvalidCharSequence", i),
nameof(unicode));
}
@@ -403,7 +403,7 @@ namespace System.Globalization
// 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;
@@ -423,38 +423,38 @@ namespace System.Globalization
"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))
+ 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)),
+ M_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)
+ 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(Environment.GetResourceString(
- "Argument_IdnBadStd3", c), "Unicode");
+ 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)
+ private static bool HasUpperCaseFlag(char punychar)
{
return (punychar >= 'A' && punychar <= 'Z');
}
@@ -464,17 +464,17 @@ namespace System.Globalization
/* 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 = '-';
+ private const int punycodeBase = 36;
+ private const int tmin = 1;
+ private const int tmax = 26;
+ private const int skew = 38;
+ private const int damp = 700;
+ private const int initial_bias = 72;
+ private const int initial_n = 0x80;
+ private const char delimiter = '-';
/* basic(cp) tests whether cp is a basic code point: */
- static bool basic(uint cp)
+ private static bool basic(uint cp)
{
// Is it in ASCII range?
return cp < 0x80;
@@ -484,7 +484,7 @@ namespace System.Globalization
// 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)
+ private static int decode_digit(char cp)
{
if (cp >= '0' && cp <= '9')
return cp - '0' + 26;
@@ -506,7 +506,7 @@ namespace System.Globalization
/* 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)
+ private 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
@@ -524,7 +524,7 @@ namespace System.Globalization
/* is caseless. The behavior is undefined if bcp is not a basic */
/* code point. */
- static char encode_basic(char bcp)
+ private static char encode_basic(char bcp)
{
if (HasUpperCaseFlag(bcp))
bcp += (char)('a' - 'A');
@@ -535,12 +535,12 @@ namespace System.Globalization
/*** Platform-specific constants ***/
/* maxint is the maximum value of a uint variable: */
- const int maxint = 0x7ffffff;
+ private const int maxint = 0x7ffffff;
/*** Bias adaptation function ***/
- static int adapt(
- int delta, int numpoints, bool firsttime )
+ private static int adapt(
+ int delta, int numpoints, bool firsttime)
{
uint k;
@@ -548,9 +548,9 @@ namespace System.Globalization
Debug.Assert(numpoints != 0, "[IdnMapping.adapt]Expected non-zero numpoints.");
delta += delta / numpoints;
- for (k = 0; delta > ((punycodeBase - tmin) * tmax) / 2; k += punycodeBase)
+ for (k = 0; delta > ((punycodeBase - tmin) * tmax) / 2; k += punycodeBase)
{
- delta /= punycodeBase - tmin;
+ delta /= punycodeBase - tmin;
}
Debug.Assert(delta + skew != 0, "[IdnMapping.adapt]Expected non-zero delta+skew.");
@@ -585,7 +585,7 @@ namespace System.Globalization
/* except punycode_bad_input; if not punycode_success, then */
/* output_size and output might contain garbage. */
- static String punycode_encode(String unicode)
+ private static String punycode_encode(String unicode)
{
// 0 length strings aren't allowed
if (unicode.Length == 0)
@@ -740,7 +740,7 @@ namespace System.Globalization
Debug.Assert(delta > 0, "[IdnMapping.cs]1 punycode_encode - delta overflowed int");
n = m;
- for (j = iAfterLastDot; j < iNextDot; j+= IsSupplementary(test) ? 2 : 1)
+ for (j = iAfterLastDot; j < iNextDot; j += IsSupplementary(test) ? 2 : 1)
{
// Make sure we're aware of surrogates
test = Char.ConvertToUtf32(unicode, j);
@@ -758,7 +758,7 @@ namespace System.Globalization
{
// Represent delta as a generalized variable-length integer:
int q, k;
- for (q = delta, k = punycodeBase; ; k += punycodeBase)
+ for (q = delta, k = punycodeBase; ; k += punycodeBase)
{
int t = k <= bias ? tmin :
k >= bias + tmax ? tmax : k - bias;
@@ -802,10 +802,10 @@ namespace System.Globalization
}
// Throw if we're too long
- if (output.Length > M_defaultNameLimit - (IsDot(unicode[unicode.Length-1]) ? 0 : 1))
+ 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)),
+ M_defaultNameLimit - (IsDot(unicode[unicode.Length - 1]) ? 0 : 1)),
nameof(unicode));
// Return our output string
@@ -835,7 +835,7 @@ 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 punycode_decode(String ascii)
{
// 0 length strings aren't allowed
if (ascii.Length == 0)
@@ -844,10 +844,10 @@ namespace System.Globalization
Contract.EndContractBlock();
// Throw if we're too long
- if (ascii.Length > M_defaultNameLimit - (IsDot(ascii[ascii.Length-1]) ? 0 : 1))
+ 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));
+ M_defaultNameLimit - (IsDot(ascii[ascii.Length - 1]) ? 0 : 1)), nameof(ascii));
// output stringbuilder
StringBuilder output = new StringBuilder(ascii.Length);
@@ -888,13 +888,13 @@ namespace System.Globalization
{
// 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));
-// }
+ // 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));
@@ -934,7 +934,7 @@ namespace System.Globalization
"Argument_IdnBadPunycode"), nameof(ascii));
// When appending make sure they get lower cased
- output.Append((char)(ascii[copyAscii] >= 'A' && ascii[copyAscii] <='Z' ?
+ output.Append((char)(ascii[copyAscii] >= 'A' && ascii[copyAscii] <= 'Z' ?
ascii[copyAscii] - 'A' + 'a' :
ascii[copyAscii]));
}
@@ -944,7 +944,7 @@ namespace System.Globalization
// basic code points, otherwise start after the -.
// asciiIndex will be next character to read from ascii
int asciiIndex = iAfterLastDot +
- ( numBasicCodePoints > 0 ? numBasicCodePoints + 1 : 0);
+ (numBasicCodePoints > 0 ? numBasicCodePoints + 1 : 0);
// initialize our state
int n = initial_n;
@@ -965,7 +965,7 @@ namespace System.Globalization
/* value at the end to obtain delta. */
int oldi = i;
- for (w = 1, k = punycodeBase; ; k += punycodeBase)
+ for (w = 1, k = punycodeBase; ; k += punycodeBase)
{
// Check to make sure we aren't overrunning our ascii string
if (asciiIndex >= iNextDot)
@@ -1005,13 +1005,13 @@ namespace System.Globalization
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)
- // }
+ // 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))
@@ -1082,8 +1082,8 @@ namespace System.Globalization
"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'));
+ // if (output[iTest] >= 'A' && output[iTest] <= 'Z')
+ // output[iTest] = (char)(output[iTest] + (char)('a' - 'A'));
}
// Its also a requirement that the last one be RTL if 1st is RTL
@@ -1109,10 +1109,10 @@ namespace System.Globalization
}
// Throw if we're too long
- if (output.Length > M_defaultNameLimit - (IsDot(output[output.Length-1]) ? 0 : 1))
+ 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));
+ M_defaultNameLimit - (IsDot(output[output.Length - 1]) ? 0 : 1)), nameof(ascii));
// Return our output string
return output.ToString();
@@ -1151,37 +1151,37 @@ namespace System.Globalization
*/
- private const int IDN_ALLOW_UNASSIGNED = 0x1;
- private const int IDN_USE_STD3_ASCII_RULES = 0x2;
-
+ private const int IDN_ALLOW_UNASSIGNED = 0x1;
+ private const int IDN_USE_STD3_ASCII_RULES = 0x2;
+
private const int ERROR_INVALID_NAME = 123;
[SuppressUnmanagedCodeSecurityAttribute()]
- [DllImport("normaliz.dll", CharSet=CharSet.Unicode, SetLastError=true)]
+ [DllImport("normaliz.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern int IdnToAscii(
- uint dwFlags,
+ uint dwFlags,
[InAttribute()]
[MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPWStr)]
- String lpUnicodeCharStr,
- int cchUnicodeChar,
+ String lpUnicodeCharStr,
+ int cchUnicodeChar,
[System.Runtime.InteropServices.OutAttribute()]
- char [] lpASCIICharStr,
- int cchASCIIChar);
+ char [] lpASCIICharStr,
+ int cchASCIIChar);
[SuppressUnmanagedCodeSecurityAttribute()]
- [DllImport("normaliz.dll", CharSet=CharSet.Unicode, SetLastError=true)]
+ [DllImport("normaliz.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern int IdnToUnicode(
- uint dwFlags,
+ uint dwFlags,
[InAttribute()]
[MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPWStr)]
- string lpASCIICharStr,
- int cchASCIIChar,
+ string lpASCIICharStr,
+ int cchASCIIChar,
[System.Runtime.InteropServices.OutAttribute()]
char [] lpUnicodeCharStr,
- int cchUnicodeChar);
+ int cchUnicodeChar);
}
}
diff --git a/src/mscorlib/src/System/Globalization/JapaneseCalendar.cs b/src/mscorlib/src/System/Globalization/JapaneseCalendar.cs
index 72331f8346..82be6a5772 100644
--- a/src/mscorlib/src/System/Globalization/JapaneseCalendar.cs
+++ b/src/mscorlib/src/System/Globalization/JapaneseCalendar.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.Globalization {
-
+namespace System.Globalization
+{
using System;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
@@ -112,13 +112,13 @@ namespace System.Globalization {
{
// 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,
+ 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,
+ 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,
+ 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,
+ 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
@@ -158,7 +158,7 @@ namespace System.Globalization {
// 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);
@@ -183,7 +183,7 @@ namespace System.Globalization {
// Remember we found one.
registryEraRanges[iFoundEras] = era;
- iFoundEras++;
+ iFoundEras++;
}
}
}
@@ -233,7 +233,7 @@ namespace System.Globalization {
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;
+ registryEraRanges[i].maxEraYear = registryEraRanges[i - 1].yearOffset + 1 - registryEraRanges[i].yearOffset;
}
}
@@ -277,7 +277,7 @@ namespace System.Globalization {
{
// Need inputs
if (value == null || data == null) return null;
-
+
//
// Get Date
//
@@ -289,9 +289,9 @@ namespace System.Globalization {
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))
+ 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;
@@ -322,7 +322,7 @@ namespace System.Globalization {
// 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,
+ return new EraInfo(0, year, month, day, year - 1, 1, 0,
names[0], names[1], names[3]);
}
@@ -337,36 +337,46 @@ namespace System.Globalization {
**Exceptions:
============================================================================*/
- internal static Calendar GetDefaultInstance() {
- if (s_defaultInstance == null) {
+ internal static Calendar GetDefaultInstance()
+ {
+ if (s_defaultInstance == null)
+ {
s_defaultInstance = new JapaneseCalendar();
}
return (s_defaultInstance);
}
- public JapaneseCalendar() {
- try {
+ public JapaneseCalendar()
+ {
+ try
+ {
new CultureInfo("ja-JP");
- } catch (ArgumentException e) {
+ }
+ catch (ArgumentException e)
+ {
throw new TypeInitializationException(this.GetType().FullName, e);
}
helper = new GregorianCalendarHelper(this, GetEraInfo());
}
- internal override int ID {
- get {
+ internal override int ID
+ {
+ get
+ {
return (CAL_JAPAN);
}
}
- public override DateTime AddMonths(DateTime time, int months) {
+ public override DateTime AddMonths(DateTime time, int months)
+ {
return (helper.AddMonths(time, months));
}
- public override DateTime AddYears(DateTime time, int years) {
+ public override DateTime AddYears(DateTime time, int years)
+ {
return (helper.AddYears(time, years));
}
@@ -382,22 +392,26 @@ namespace System.Globalization {
============================================================================*/
- public override int GetDaysInMonth(int year, int month, int era) {
+ public override int GetDaysInMonth(int year, int month, int era)
+ {
return (helper.GetDaysInMonth(year, month, era));
}
- public override int GetDaysInYear(int year, int era) {
+ public override int GetDaysInYear(int year, int era)
+ {
return (helper.GetDaysInYear(year, era));
}
- public override int GetDayOfMonth(DateTime time) {
+ public override int GetDayOfMonth(DateTime time)
+ {
return (helper.GetDayOfMonth(time));
}
- public override DayOfWeek GetDayOfWeek(DateTime time) {
+ public override DayOfWeek GetDayOfWeek(DateTime time)
+ {
return (helper.GetDayOfWeek(time));
}
@@ -429,17 +443,20 @@ namespace System.Globalization {
============================================================================*/
- public override int GetEra(DateTime time) {
+ public override int GetEra(DateTime time)
+ {
return (helper.GetEra(time));
}
- public override int GetMonth(DateTime time) {
+ public override int GetMonth(DateTime time)
+ {
return (helper.GetMonth(time));
- }
+ }
- public override int GetYear(DateTime time) {
+ public override int GetYear(DateTime time)
+ {
return (helper.GetYear(time));
}
@@ -450,7 +467,8 @@ namespace System.Globalization {
}
- public override bool IsLeapYear(int year, int era) {
+ public override bool IsLeapYear(int year, int era)
+ {
return (helper.IsLeapYear(year, era));
}
@@ -464,26 +482,31 @@ namespace System.Globalization {
}
- public override bool IsLeapMonth(int year, int month, int 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) {
+ 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) {
+ public override int ToFourDigitYear(int year)
+ {
+ if (year <= 0)
+ {
throw new ArgumentOutOfRangeException(nameof(year),
Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
}
Contract.EndContractBlock();
- if (year > helper.MaxYear) {
+ if (year > helper.MaxYear)
+ {
throw new ArgumentOutOfRangeException(
nameof(year),
String.Format(
@@ -496,8 +519,10 @@ namespace System.Globalization {
}
- public override int[] Eras {
- get {
+ public override int[] Eras
+ {
+ get
+ {
return (helper.Eras);
}
}
@@ -549,20 +574,25 @@ namespace System.Globalization {
}
private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 99;
-
- internal override bool IsValidYear(int year, int era) {
+
+ internal override bool IsValidYear(int year, int era)
+ {
return helper.IsValidYear(year, era);
- }
+ }
- public override int TwoDigitYearMax {
- get {
- if (twoDigitYearMax == -1) {
+ public override int TwoDigitYearMax
+ {
+ get
+ {
+ if (twoDigitYearMax == -1)
+ {
twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX);
}
return (twoDigitYearMax);
}
- set {
+ set
+ {
VerifyWritable();
if (value < 99 || value > helper.MaxYear)
{
diff --git a/src/mscorlib/src/System/Globalization/JapaneseLunisolarCalendar.cs b/src/mscorlib/src/System/Globalization/JapaneseLunisolarCalendar.cs
index 67cfb23833..7fff27c4bf 100644
--- a/src/mscorlib/src/System/Globalization/JapaneseLunisolarCalendar.cs
+++ b/src/mscorlib/src/System/Globalization/JapaneseLunisolarCalendar.cs
@@ -2,26 +2,27 @@
// 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;
+using System;
+using System.Diagnostics.Contracts;
+namespace System.Globalization
+{
////////////////////////////////////////////////////////////////////////////
//
// Notes about JapaneseLunisolarCalendar
//
////////////////////////////////////////////////////////////////////////////
- /*
- ** Calendar support range:
- ** Calendar Minimum Maximum
- ** ========== ========== ==========
- ** Gregorian 1960/01/28 2050/01/22
- ** JapaneseLunisolar 1960/01/01 2049/12/29
- */
+ /*
+ ** 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 {
-
+ public class JapaneseLunisolarCalendar : EastAsianLunisolarCalendar
+ {
//
// The era value for the current era.
//
@@ -69,7 +70,7 @@ namespace System.Globalization {
}
}
- static readonly int [,] yinfo =
+ private 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
@@ -164,61 +165,70 @@ namespace System.Globalization {
2049 */{ 0 , 2 , 2 , 44448 },/* 30 29 30 29 30 30 29 30 30 29 30 29 0 355
*/ };
- internal override int MinCalendarYear {
+ internal override int MinCalendarYear
+ {
get
{
return (MIN_LUNISOLAR_YEAR);
}
}
- internal override int MaxCalendarYear {
+ internal override int MaxCalendarYear
+ {
get
{
return (MAX_LUNISOLAR_YEAR);
}
}
- internal override DateTime MinDate {
+ internal override DateTime MinDate
+ {
get
{
return (minDate);
}
}
- internal override DateTime MaxDate {
+ internal override DateTime MaxDate
+ {
get
{
return (maxDate);
}
}
- internal override EraInfo[] CalEraInfo {
+ 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)) {
+ 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 ));
+ MAX_LUNISOLAR_YEAR));
}
Contract.EndContractBlock();
return yinfo[LunarYear - MIN_LUNISOLAR_YEAR, Index];
}
- internal override int GetYear(int year, DateTime time) {
+ internal override int GetYear(int year, DateTime time)
+ {
return helper.GetYear(year, time);
}
- internal override int GetGregorianYear(int year, int era) {
+ internal override int GetGregorianYear(int year, int era)
+ {
return helper.GetGregorianYear(year, era);
}
@@ -258,34 +268,41 @@ namespace System.Globalization {
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) {
+ public override int GetEra(DateTime time)
+ {
return (helper.GetEra(time));
}
- internal override int BaseCalendarID {
- get {
+ internal override int BaseCalendarID
+ {
+ get
+ {
return (CAL_JAPAN);
}
}
- internal override int ID {
- get {
+ internal override int ID
+ {
+ get
+ {
return (CAL_JAPANESELUNISOLAR);
}
}
- public override int[] Eras {
- get {
+ 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
index ff8801433c..f0555d0c89 100644
--- a/src/mscorlib/src/System/Globalization/JulianCalendar.cs
+++ b/src/mscorlib/src/System/Globalization/JulianCalendar.cs
@@ -2,10 +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.Diagnostics.Contracts;
+using System;
+using System.Diagnostics.Contracts;
+
+namespace System.Globalization
+{
//
// 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
@@ -18,9 +20,8 @@ namespace System.Globalization {
//* Julia 0001/01/03 9999/10/19
[Serializable]
- public class JulianCalendar : Calendar {
-
-
+ public class JulianCalendar : Calendar
+ {
public static readonly int JulianEra = 1;
private const int DatePartYear = 0;
@@ -29,9 +30,9 @@ namespace System.Globalization {
private const int DatePartDay = 3;
// Number of days in a non-leap year
- private const int JulianDaysPerYear = 365;
+ private const int JulianDaysPerYear = 365;
// Number of days in 4 years
- private const int JulianDaysPer4Years = JulianDaysPerYear * 4 + 1;
+ private const int JulianDaysPer4Years = JulianDaysPerYear * 4 + 1;
//internal static Calendar m_defaultInstance;
@@ -95,26 +96,33 @@ namespace System.Globalization {
// Construct an instance of gregorian calendar.
- public JulianCalendar() {
+ public JulianCalendar()
+ {
// There is no system setting of TwoDigitYear max, so set the value here.
twoDigitYearMax = 2029;
}
- internal override int ID {
- get {
+ internal override int ID
+ {
+ get
+ {
return (CAL_JULIAN);
}
}
- static internal void CheckEraRange(int era) {
- if (era != CurrentEra && era != JulianEra) {
+ 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) {
+ internal void CheckYearEraRange(int year, int era)
+ {
CheckEraRange(era);
- if (year <= 0 || year > MaxYear) {
+ if (year <= 0 || year > MaxYear)
+ {
throw new ArgumentOutOfRangeException(
nameof(year),
String.Format(
@@ -125,8 +133,10 @@ namespace System.Globalization {
}
}
- static internal void CheckMonthRange(int month) {
- if (month < 1 || month > 12) {
+ static internal void CheckMonthRange(int month)
+ {
+ if (month < 1 || month > 12)
+ {
throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Month"));
}
}
@@ -141,11 +151,13 @@ namespace System.Globalization {
** sure year/month values are correct.
============================================================================*/
- static internal void CheckDayRange(int year, int month, int day) {
+ 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) {
+ if (day < 3)
+ {
throw new ArgumentOutOfRangeException(null,
Environment.GetResourceString("ArgumentOutOfRange_BadYearMonthDay"));
}
@@ -153,7 +165,8 @@ namespace System.Globalization {
bool isLeapYear = (year % 4) == 0;
int[] days = isLeapYear ? DaysToMonth366 : DaysToMonth365;
int monthDays = days[month] - days[month - 1];
- if (day < 1 || day > monthDays) {
+ if (day < 1 || day > monthDays)
+ {
throw new ArgumentOutOfRangeException(
nameof(day),
String.Format(
@@ -197,7 +210,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);
- 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;
@@ -212,7 +225,7 @@ namespace System.Globalization {
// 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[] 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.
@@ -224,7 +237,8 @@ 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(
@@ -238,18 +252,21 @@ 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[] daysArray = (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)) ? DaysToMonth366 : DaysToMonth365;
int days = (daysArray[m] - daysArray[m - 1]);
- if (d > days) {
+ if (d > days)
+ {
d = days;
}
long ticks = DateToTicks(y, m, d) + time.Ticks % TicksPerDay;
@@ -258,37 +275,43 @@ namespace System.Globalization {
}
- public override DateTime AddYears(DateTime time, int years) {
+ public override DateTime AddYears(DateTime time, int years)
+ {
return (AddMonths(time, years * 12));
}
- public override int GetDayOfMonth(DateTime time) {
+ public override int GetDayOfMonth(DateTime time)
+ {
return (GetDatePart(time.Ticks, DatePartDay));
}
- public override DayOfWeek GetDayOfWeek(DateTime time) {
+ public override DayOfWeek GetDayOfWeek(DateTime time)
+ {
return ((DayOfWeek)((int)(time.Ticks / TicksPerDay + 1) % 7));
}
- public override int GetDayOfYear(DateTime time) {
+ public override int GetDayOfYear(DateTime time)
+ {
return (GetDatePart(time.Ticks, DatePartDayOfYear));
}
- public override int GetDaysInMonth(int year, int month, int era) {
+ public override int GetDaysInMonth(int year, int month, int era)
+ {
CheckYearEraRange(year, era);
CheckMonthRange(month);
- int[] days = (year % 4 == 0) ? DaysToMonth366: DaysToMonth365;
+ int[] days = (year % 4 == 0) ? DaysToMonth366 : DaysToMonth365;
return (days[month] - days[month - 1]);
}
- public override int GetDaysInYear(int year, int era) {
+ public override int GetDaysInYear(int year, int era)
+ {
// Year/Era range is done in IsLeapYear().
- return (IsLeapYear(year, era) ? 366:365);
+ return (IsLeapYear(year, era) ? 366 : 365);
}
@@ -304,9 +327,11 @@ namespace System.Globalization {
}
- public override int[] Eras {
- get {
- return (new int[] {JulianEra});
+ public override int[] Eras
+ {
+ get
+ {
+ return (new int[] { JulianEra });
}
}
@@ -328,7 +353,8 @@ namespace System.Globalization {
{
CheckMonthRange(month);
// Year/Era range check is done in IsLeapYear().
- if (IsLeapYear(year, era)) {
+ if (IsLeapYear(year, era))
+ {
CheckDayRange(year, month, day);
return (month == 2 && day == 29);
}
@@ -370,7 +396,8 @@ namespace System.Globalization {
CheckYearEraRange(year, era);
CheckMonthRange(month);
CheckDayRange(year, month, day);
- if (millisecond < 0 || millisecond >= MillisPerSecond) {
+ if (millisecond < 0 || millisecond >= MillisPerSecond)
+ {
throw new ArgumentOutOfRangeException(
nameof(millisecond),
String.Format(
@@ -380,22 +407,26 @@ namespace System.Globalization {
MillisPerSecond - 1));
}
- 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)
{
return new DateTime(DateToTicks(year, month, day) + (new TimeSpan(0, hour, minute, second, millisecond)).Ticks);
- } else
+ }
+ else
{
throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("ArgumentOutOfRange_BadHourMinuteSecond"));
}
}
- public override int TwoDigitYearMax {
- get {
+ public override int TwoDigitYearMax
+ {
+ get
+ {
return (twoDigitYearMax);
}
- set {
+ set
+ {
VerifyWritable();
if (value < 99 || value > MaxYear)
{
@@ -406,21 +437,23 @@ namespace System.Globalization {
Environment.GetResourceString("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"));
}
Contract.EndContractBlock();
- if (year > MaxYear) {
+ if (year > MaxYear)
+ {
throw new ArgumentOutOfRangeException(
nameof(year),
String.Format(
@@ -432,5 +465,4 @@ namespace System.Globalization {
return (base.ToFourDigitYear(year));
}
}
-
}
diff --git a/src/mscorlib/src/System/Globalization/KoreanCalendar.cs b/src/mscorlib/src/System/Globalization/KoreanCalendar.cs
index 6c5a03b7e8..6ee425b3c0 100644
--- a/src/mscorlib/src/System/Globalization/KoreanCalendar.cs
+++ b/src/mscorlib/src/System/Globalization/KoreanCalendar.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;
- using System.Diagnostics.CodeAnalysis;
- using System.Diagnostics.Contracts;
+using System;
+using System.Diagnostics.CodeAnalysis;
+using System.Diagnostics.Contracts;
+namespace System.Globalization
+{
/*=================================KoreanCalendar==========================
**
** Korean calendar is based on the Gregorian calendar. And the year is an offset to Gregorian calendar.
@@ -24,7 +25,9 @@ namespace System.Globalization {
============================================================================*/
- [Serializable] public class KoreanCalendar: Calendar {
+ [Serializable]
+ public class KoreanCalendar : Calendar
+ {
//
// The era value for the current era.
//
@@ -92,28 +95,36 @@ namespace System.Globalization {
*/
- public KoreanCalendar() {
- try {
+ public KoreanCalendar()
+ {
+ try
+ {
new CultureInfo("ko-KR");
- } catch (ArgumentException e) {
+ }
+ catch (ArgumentException e)
+ {
throw new TypeInitializationException(this.GetType().FullName, e);
}
helper = new GregorianCalendarHelper(this, koreanEraInfo);
}
- internal override int ID {
- get {
+ internal override int ID
+ {
+ get
+ {
return (CAL_KOREA);
}
}
- public override DateTime AddMonths(DateTime time, int months) {
+ public override DateTime AddMonths(DateTime time, int months)
+ {
return (helper.AddMonths(time, months));
}
- public override DateTime AddYears(DateTime time, int years) {
+ public override DateTime AddYears(DateTime time, int years)
+ {
return (helper.AddYears(time, years));
}
@@ -129,22 +140,26 @@ namespace System.Globalization {
============================================================================*/
- public override int GetDaysInMonth(int year, int month, int era) {
+ public override int GetDaysInMonth(int year, int month, int era)
+ {
return (helper.GetDaysInMonth(year, month, era));
}
- public override int GetDaysInYear(int year, int era) {
+ public override int GetDaysInYear(int year, int era)
+ {
return (helper.GetDaysInYear(year, era));
}
- public override int GetDayOfMonth(DateTime time) {
+ public override int GetDayOfMonth(DateTime time)
+ {
return (helper.GetDayOfMonth(time));
}
- public override DayOfWeek GetDayOfWeek(DateTime time) {
+ public override DayOfWeek GetDayOfWeek(DateTime time)
+ {
return (helper.GetDayOfWeek(time));
}
@@ -155,7 +170,8 @@ namespace System.Globalization {
}
- public override int GetMonthsInYear(int year, int era) {
+ public override int GetMonthsInYear(int year, int era)
+ {
return (helper.GetMonthsInYear(year, era));
}
@@ -167,16 +183,19 @@ namespace System.Globalization {
}
- public override int GetEra(DateTime time) {
+ public override int GetEra(DateTime time)
+ {
return (helper.GetEra(time));
}
- public override int GetMonth(DateTime time) {
+ public override int GetMonth(DateTime time)
+ {
return (helper.GetMonth(time));
}
- public override int GetYear(DateTime time) {
+ public override int GetYear(DateTime time)
+ {
return (helper.GetYear(time));
}
@@ -187,7 +206,8 @@ namespace System.Globalization {
}
- public override bool IsLeapYear(int year, int era) {
+ public override bool IsLeapYear(int year, int era)
+ {
return (helper.IsLeapYear(year, era));
}
@@ -201,18 +221,22 @@ namespace System.Globalization {
}
- public override bool IsLeapMonth(int year, int month, int 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) {
+ 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 {
+ public override int[] Eras
+ {
+ get
+ {
return (helper.Eras);
}
}
@@ -220,15 +244,19 @@ namespace System.Globalization {
private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 4362;
- public override int TwoDigitYearMax {
- get {
- if (twoDigitYearMax == -1) {
+ public override int TwoDigitYearMax
+ {
+ get
+ {
+ if (twoDigitYearMax == -1)
+ {
twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX);
}
return (twoDigitYearMax);
}
- set {
+ set
+ {
VerifyWritable();
if (value < 99 || value > helper.MaxYear)
{
@@ -239,15 +267,16 @@ namespace System.Globalization {
Environment.GetResourceString("ArgumentOutOfRange_Range"),
99,
helper.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"));
}
diff --git a/src/mscorlib/src/System/Globalization/KoreanLunisolarCalendar.cs b/src/mscorlib/src/System/Globalization/KoreanLunisolarCalendar.cs
index 9e36b435e7..b6f02d701e 100644
--- a/src/mscorlib/src/System/Globalization/KoreanLunisolarCalendar.cs
+++ b/src/mscorlib/src/System/Globalization/KoreanLunisolarCalendar.cs
@@ -2,27 +2,27 @@
// 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;
+using System;
+using System.Diagnostics.Contracts;
+namespace System.Globalization
+{
////////////////////////////////////////////////////////////////////////////
//
// Notes about KoreanLunisolarCalendar
//
////////////////////////////////////////////////////////////////////////////
- /*
- ** Calendar support range:
- ** Calendar Minimum Maximum
- ** ========== ========== ==========
- ** Gregorian 918/02/14 2051/02/10
- ** KoreanLunisolar 918/01/01 2050/13/29
- */
+ /*
+ ** 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 {
-
-
+ public class KoreanLunisolarCalendar : EastAsianLunisolarCalendar
+ {
//
// The era value for the current era.
//
@@ -34,9 +34,9 @@ namespace System.Globalization {
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_YEAR = 918;
internal const int MIN_GREGORIAN_MONTH = 2;
- internal const int MIN_GREGORIAN_DAY = 14;
+ internal const int MIN_GREGORIAN_DAY = 14;
internal const int MAX_GREGORIAN_YEAR = 2051;
internal const int MAX_GREGORIAN_MONTH = 2;
@@ -45,7 +45,8 @@ namespace System.Globalization {
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 {
+ public override DateTime MinSupportedDateTime
+ {
get
{
return (minDate);
@@ -54,7 +55,8 @@ namespace System.Globalization {
- public override DateTime MaxSupportedDateTime {
+ public override DateTime MaxSupportedDateTime
+ {
get
{
return (maxDate);
@@ -71,7 +73,7 @@ namespace System.Globalization {
}
}
- static readonly int [,] yinfo =
+ private 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
@@ -1210,66 +1212,73 @@ namespace System.Globalization {
*/};
- internal override int MinCalendarYear {
+ internal override int MinCalendarYear
+ {
get
{
return (MIN_LUNISOLAR_YEAR);
}
}
- internal override int MaxCalendarYear {
+ internal override int MaxCalendarYear
+ {
get
{
return (MAX_LUNISOLAR_YEAR);
}
}
- internal override DateTime MinDate {
+ internal override DateTime MinDate
+ {
get
{
return (minDate);
}
}
- internal override DateTime MaxDate {
+ internal override DateTime MaxDate
+ {
get
{
return (maxDate);
}
}
- internal override EraInfo[] CalEraInfo {
+ internal override EraInfo[] CalEraInfo
+ {
get
{
return null;
}
}
- internal override int GetYearInfo(int LunarYear, int Index) {
- if ((LunarYear < MIN_LUNISOLAR_YEAR) || (LunarYear > MAX_LUNISOLAR_YEAR)) {
+ 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 ));
+ MAX_LUNISOLAR_YEAR));
}
Contract.EndContractBlock();
- return yinfo[LunarYear - MIN_LUNISOLAR_YEAR, Index];
- }
+ return yinfo[LunarYear - MIN_LUNISOLAR_YEAR, Index];
+ }
- internal override int GetYear(int year, DateTime time)
- {
+ internal override int GetYear(int year, DateTime time)
+ {
return year;
- }
+ }
- internal override int GetGregorianYear(int year, int era)
- {
- if (era != CurrentEra && era != GregorianEra)
+ 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)
+ if (year < MIN_LUNISOLAR_YEAR || year > MAX_LUNISOLAR_YEAR)
{
throw new ArgumentOutOfRangeException(
nameof(year),
@@ -1280,7 +1289,7 @@ namespace System.Globalization {
Contract.EndContractBlock();
return year;
- }
+ }
/*=================================GetDefaultInstance==========================
**Action: Internal method to provide a default intance of KoreanLunisolarCalendar. Used by NLS+ implementation
@@ -1301,33 +1310,41 @@ namespace System.Globalization {
// Construct an instance of KoreanLunisolar calendar.
- public KoreanLunisolarCalendar() {
+ public KoreanLunisolarCalendar()
+ {
}
- public override int GetEra(DateTime time) {
+ public override int GetEra(DateTime time)
+ {
CheckTicksRange(time.Ticks);
return (GregorianEra);
}
- internal override int BaseCalendarID {
- get {
+ internal override int BaseCalendarID
+ {
+ get
+ {
return (CAL_KOREA);
}
}
- internal override int ID {
- get {
+ internal override int ID
+ {
+ get
+ {
return (CAL_KOREANLUNISOLAR);
}
}
- public override int[] Eras {
- get {
- return (new int[] {GregorianEra});
+ 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..5d36dab3d5 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.Runtime.Serialization;
+using System.Text;
+using System;
+using System.Diagnostics.Contracts;
+
+namespace System.Globalization
+{
//
// Property Default Description
// PositiveSign '+' Character used to indicate positive values.
@@ -50,9 +52,9 @@ namespace System.Globalization {
// 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 = ".";
@@ -73,7 +75,7 @@ namespace System.Globalization {
internal String perMilleSymbol = "\u2030";
[OptionalField(VersionAdded = 2)]
- internal String[] nativeDigits = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
+ 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),
@@ -93,20 +95,21 @@ namespace System.Globalization {
[OptionalField(VersionAdded = 2)]
internal int digitSubstitution = 1; // DigitShapes.None
- internal bool isReadOnly=false;
+ 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 m_useUserOverride = false; // NEVER USED, DO NOT USE THIS! (Serialized in Everett)
// 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
+ #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
@@ -129,31 +132,37 @@ namespace System.Globalization {
private void OnDeserialized(StreamingContext ctx)
{
}
-#endregion Serialization
+ #endregion Serialization
- static private void VerifyDecimalSeparator(String decSep, String propertyName) {
- if (decSep==null) {
+ static private void VerifyDecimalSeparator(String decSep, String propertyName)
+ {
+ if (decSep == null)
+ {
throw new ArgumentNullException(propertyName,
Environment.GetResourceString("ArgumentNull_String"));
}
- if (decSep.Length==0) {
+ if (decSep.Length == 0)
+ {
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyDecString"));
}
Contract.EndContractBlock();
-
}
- static private void VerifyGroupSeparator(String groupSep, String propertyName) {
- if (groupSep==null) {
+ static private void VerifyGroupSeparator(String groupSep, String propertyName)
+ {
+ if (groupSep == null)
+ {
throw new ArgumentNullException(propertyName,
Environment.GetResourceString("ArgumentNull_String"));
}
Contract.EndContractBlock();
}
- static private void VerifyNativeDigits(String [] nativeDig, String propertyName) {
- if (nativeDig==null) {
+ static private void VerifyNativeDigits(String[] nativeDig, String propertyName)
+ {
+ if (nativeDig == null)
+ {
throw new ArgumentNullException(propertyName,
Environment.GetResourceString("ArgumentNull_Array"));
}
@@ -164,7 +173,7 @@ namespace System.Globalization {
}
Contract.EndContractBlock();
- for(int i = 0; i < nativeDig.Length; i++)
+ for (int i = 0; i < nativeDig.Length; i++)
{
if (nativeDig[i] == null)
{
@@ -172,19 +181,24 @@ namespace System.Globalization {
Environment.GetResourceString("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])) {
+ }
+ 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);
}
}
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);
@@ -192,8 +206,9 @@ namespace System.Globalization {
}
}
- static private void VerifyDigitSubstitution(DigitShapes digitSub, String propertyName) {
- switch(digitSub)
+ static private void VerifyDigitSubstitution(DigitShapes digitSub, String propertyName)
+ {
+ switch (digitSub)
{
case DigitShapes.Context:
case DigitShapes.None:
@@ -225,8 +240,10 @@ namespace System.Globalization {
}
[Pure]
- private void VerifyWritable() {
- if (isReadOnly) {
+ private void VerifyWritable()
+ {
+ if (isReadOnly)
+ {
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
}
Contract.EndContractBlock();
@@ -237,9 +254,12 @@ namespace System.Globalization {
// Used by FromString methods.
//
- public static NumberFormatInfo InvariantInfo {
- get {
- if (invariantInfo == null) {
+ public static NumberFormatInfo InvariantInfo
+ {
+ get
+ {
+ if (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();
@@ -251,27 +271,34 @@ namespace System.Globalization {
}
- 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.m_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,17 +307,21 @@ 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(
@@ -306,9 +337,11 @@ namespace System.Globalization {
}
- public String CurrencyDecimalSeparator {
+ public String CurrencyDecimalSeparator
+ {
get { return currencyDecimalSeparator; }
- set {
+ set
+ {
VerifyWritable();
VerifyDecimalSeparator(value, nameof(CurrencyDecimalSeparator));
currencyDecimalSeparator = value;
@@ -316,8 +349,10 @@ namespace System.Globalization {
}
- public bool IsReadOnly {
- get {
+ public bool IsReadOnly
+ {
+ get
+ {
return isReadOnly;
}
}
@@ -346,39 +381,46 @@ namespace System.Globalization {
}
- 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"));
}
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"));
}
Contract.EndContractBlock();
VerifyWritable();
-
+
Int32[] inputSizes = (Int32[])value.Clone();
CheckGroupSize(nameof(NumberGroupSizes), inputSizes);
numberGroupSizes = inputSizes;
@@ -386,12 +428,16 @@ namespace System.Globalization {
}
- public int[] PercentGroupSizes {
- get {
+ public int[] PercentGroupSizes
+ {
+ get
+ {
return ((int[])percentGroupSizes.Clone());
}
- set {
- if (value == null) {
+ set
+ {
+ if (value == null)
+ {
throw new ArgumentNullException(nameof(PercentGroupSizes),
Environment.GetResourceString("ArgumentNull_Obj"));
}
@@ -401,13 +447,14 @@ namespace System.Globalization {
CheckGroupSize(nameof(PercentGroupSizes), inputSizes);
percentGroupSizes = inputSizes;
}
-
}
- public String CurrencyGroupSeparator {
+ public String CurrencyGroupSeparator
+ {
get { return currencyGroupSeparator; }
- set {
+ set
+ {
VerifyWritable();
VerifyGroupSeparator(value, nameof(CurrencyGroupSeparator));
currencyGroupSeparator = value;
@@ -415,10 +462,13 @@ 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"));
}
@@ -431,12 +481,16 @@ namespace System.Globalization {
// Returns the current culture's NumberFormatInfo. Used by Parse methods.
//
- public static NumberFormatInfo CurrentInfo {
- get {
+ public static NumberFormatInfo CurrentInfo
+ {
+ get
+ {
System.Globalization.CultureInfo culture = System.Threading.Thread.CurrentThread.CurrentCulture;
- if (!culture.m_isInherited) {
+ if (!culture.m_isInherited)
+ {
NumberFormatInfo info = culture.numInfo;
- if (info != null) {
+ if (info != null)
+ {
return info;
}
}
@@ -445,12 +499,16 @@ 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"));
}
@@ -462,10 +520,13 @@ 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(
@@ -481,13 +542,16 @@ 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(
@@ -503,13 +567,16 @@ 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(
@@ -525,13 +592,16 @@ 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(
@@ -547,12 +617,16 @@ 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"));
}
@@ -563,10 +637,13 @@ 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"));
}
@@ -577,10 +654,13 @@ 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(
@@ -596,9 +676,11 @@ namespace System.Globalization {
}
- public String NumberDecimalSeparator {
+ public String NumberDecimalSeparator
+ {
get { return numberDecimalSeparator; }
- set {
+ set
+ {
VerifyWritable();
VerifyDecimalSeparator(value, nameof(NumberDecimalSeparator));
numberDecimalSeparator = value;
@@ -606,9 +688,11 @@ namespace System.Globalization {
}
- public String NumberGroupSeparator {
+ public String NumberGroupSeparator
+ {
get { return numberGroupSeparator; }
- set {
+ set
+ {
VerifyWritable();
VerifyGroupSeparator(value, nameof(NumberGroupSeparator));
numberGroupSeparator = value;
@@ -616,10 +700,13 @@ 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(
@@ -635,12 +722,16 @@ 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"));
}
@@ -651,10 +742,13 @@ 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"));
}
@@ -665,10 +759,13 @@ 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(
@@ -684,9 +781,11 @@ namespace System.Globalization {
}
- public String PercentDecimalSeparator {
+ public String PercentDecimalSeparator
+ {
get { return percentDecimalSeparator; }
- set {
+ set
+ {
VerifyWritable();
VerifyDecimalSeparator(value, nameof(PercentDecimalSeparator));
percentDecimalSeparator = value;
@@ -694,9 +793,11 @@ namespace System.Globalization {
}
- public String PercentGroupSeparator {
+ public String PercentGroupSeparator
+ {
get { return percentGroupSeparator; }
- set {
+ set
+ {
VerifyWritable();
VerifyGroupSeparator(value, nameof(PercentGroupSeparator));
percentGroupSeparator = value;
@@ -704,12 +805,16 @@ 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"));
}
@@ -720,10 +825,13 @@ 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"));
}
@@ -756,16 +864,20 @@ namespace System.Globalization {
}
}
- 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,26 +892,33 @@ 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) {
+ if ((style & InvalidNumberStyles) != 0)
+ {
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidNumberStyles"), nameof(style));
}
Contract.EndContractBlock();
- if ((style & NumberStyles.AllowHexSpecifier) != 0) { // Check for hex number
- if ((style & ~NumberStyles.HexNumber) != 0) {
+ if ((style & NumberStyles.AllowHexSpecifier) != 0)
+ { // Check for hex number
+ if ((style & ~NumberStyles.HexNumber) != 0)
+ {
throw new ArgumentException(Environment.GetResourceString("Arg_InvalidHexStyle"));
}
}
}
- internal static void ValidateParseStyleFloatingPoint(NumberStyles style) {
+ internal static void ValidateParseStyleFloatingPoint(NumberStyles style)
+ {
// Check for undefined flags
- if ((style & InvalidNumberStyles) != 0) {
+ if ((style & InvalidNumberStyles) != 0)
+ {
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidNumberStyles"), nameof(style));
}
Contract.EndContractBlock();
- if ((style & NumberStyles.AllowHexSpecifier) != 0) { // Check for hex number
+ if ((style & NumberStyles.AllowHexSpecifier) != 0)
+ { // Check for hex number
throw new ArgumentException(Environment.GetResourceString("Arg_HexStyleNotSupported"));
}
}
diff --git a/src/mscorlib/src/System/Globalization/NumberStyles.cs b/src/mscorlib/src/System/Globalization/NumberStyles.cs
index 969c07fc2a..31eafc9299 100644
--- a/src/mscorlib/src/System/Globalization/NumberStyles.cs
+++ b/src/mscorlib/src/System/Globalization/NumberStyles.cs
@@ -11,56 +11,58 @@
**
**
===========================================================*/
-namespace System.Globalization {
-
- using System;
+
+using System;
+
+namespace System.Globalization
+{
[Serializable]
[Flags]
- public enum NumberStyles {
+ 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,
+ None = 0x00000000,
+
+ AllowLeadingWhite = 0x00000001,
+
+ AllowTrailingWhite = 0x00000002, //Bitflag indicating trailing whitespace is allowed.
- 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
- 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
- AllowTrailingSign = 0x00000008, //Allow the number to end with a sign char
+ AllowParentheses = 0x00000010, //Allow the number to be enclosed in parens
- AllowParentheses = 0x00000010, //Allow the number to be enclosed in parens
+ AllowDecimalPoint = 0x00000020, //Allow a decimal point
- AllowDecimalPoint = 0x00000020, //Allow a decimal point
+ AllowThousands = 0x00000040, //Allow thousands separators (more properly, allow group separators)
- AllowThousands = 0x00000040, //Allow thousands separators (more properly, allow group separators)
+ AllowExponent = 0x00000080, //Allow an exponent
- AllowExponent = 0x00000080, //Allow an exponent
+ AllowCurrencySymbol = 0x00000100, //Allow a currency symbol.
- AllowCurrencySymbol = 0x00000100, //Allow a currency symbol.
+ AllowHexSpecifier = 0x00000200, //Allow specifiying hexadecimal.
+ //Common uses. These represent some of the most common combinations of these flags.
- AllowHexSpecifier = 0x00000200, //Allow specifiying hexadecimal.
- //Common uses. These represent some of the most common combinations of these flags.
-
- Integer = AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign,
+ Integer = AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign,
HexNumber = AllowLeadingWhite | AllowTrailingWhite | AllowHexSpecifier,
- Number = AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign | AllowTrailingSign |
+ Number = AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign | AllowTrailingSign |
AllowDecimalPoint | AllowThousands,
- Float = AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign |
+ Float = AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign |
AllowDecimalPoint | AllowExponent,
Currency = AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign | AllowTrailingSign |
- AllowParentheses | AllowDecimalPoint | AllowThousands | AllowCurrencySymbol,
+ AllowParentheses | AllowDecimalPoint | AllowThousands | AllowCurrencySymbol,
- Any = AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign | AllowTrailingSign |
- AllowParentheses | AllowDecimalPoint | AllowThousands | AllowCurrencySymbol | AllowExponent,
-
+ 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
index e61a007a02..dca34e812c 100644
--- a/src/mscorlib/src/System/Globalization/PersianCalendar.cs
+++ b/src/mscorlib/src/System/Globalization/PersianCalendar.cs
@@ -2,11 +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.Diagnostics;
- using System.Diagnostics.Contracts;
+using System;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+namespace System.Globalization
+{
////////////////////////////////////////////////////////////////////////////
//
// Notes about PersianCalendar
@@ -25,13 +26,12 @@ namespace System.Globalization {
*/
[Serializable]
- public class PersianCalendar : Calendar {
-
-
+ 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;
+ private const int ApproximateHalfYear = 180;
internal const int DatePartYear = 0;
internal const int DatePartDayOfYear = 1;
@@ -89,26 +89,33 @@ namespace System.Globalization {
//
- public override CalendarAlgorithmType AlgorithmType {
- get {
+ public override CalendarAlgorithmType AlgorithmType
+ {
+ get
+ {
return CalendarAlgorithmType.SolarCalendar;
}
}
// Construct an instance of Persian calendar.
- public PersianCalendar() {
+ public PersianCalendar()
+ {
}
- internal override int BaseCalendarID {
- get {
+ internal override int BaseCalendarID
+ {
+ get
+ {
return (CAL_GREGORIAN);
}
}
- internal override int ID {
- get {
+ internal override int ID
+ {
+ get
+ {
return (CAL_PERSIAN);
}
}
@@ -122,7 +129,8 @@ namespace System.Globalization {
**Exceptions:
============================================================================*/
- long GetAbsoluteDatePersian(int year, int month, int day) {
+ private 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
@@ -134,8 +142,10 @@ namespace System.Globalization {
throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("ArgumentOutOfRange_BadYearMonthDay"));
}
- static internal void CheckTicksRange(long ticks) {
- if (ticks < minDate.Ticks || ticks > maxDate.Ticks) {
+ static internal void CheckTicksRange(long ticks)
+ {
+ if (ticks < minDate.Ticks || ticks > maxDate.Ticks)
+ {
throw new ArgumentOutOfRangeException(
"time",
String.Format(
@@ -146,15 +156,19 @@ namespace System.Globalization {
}
}
- static internal void CheckEraRange(int era) {
- if (era != CurrentEra && era != PersianEra) {
+ 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) {
+ static internal void CheckYearRange(int year, int era)
+ {
CheckEraRange(era);
- if (year < 1 || year > MaxCalendarYear) {
+ if (year < 1 || year > MaxCalendarYear)
+ {
throw new ArgumentOutOfRangeException(
nameof(year),
String.Format(
@@ -165,10 +179,13 @@ namespace System.Globalization {
}
}
- static internal void CheckYearMonthRange(int year, int month, int era) {
+ static internal void CheckYearMonthRange(int year, int month, int era)
+ {
CheckYearRange(year, era);
- if (year == MaxCalendarYear) {
- if (month > MaxCalendarMonth) {
+ if (year == MaxCalendarYear)
+ {
+ if (month > MaxCalendarMonth)
+ {
throw new ArgumentOutOfRangeException(
nameof(month),
String.Format(
@@ -179,12 +196,13 @@ namespace System.Globalization {
}
}
- if (month < 1 || month > 12) {
+ if (month < 1 || month > 12)
+ {
throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Month"));
}
}
- static int MonthFromOrdinalDay(int ordinalDay)
+ private static int MonthFromOrdinalDay(int ordinalDay)
{
Debug.Assert(ordinalDay <= 366);
int index = 0;
@@ -194,7 +212,7 @@ namespace System.Globalization {
return index;
}
- static int DaysInPreviousMonths(int month)
+ private static int DaysInPreviousMonths(int month)
{
Debug.Assert(1 <= month && month <= 12);
--month; // months are one based but for calculations use 0 based
@@ -209,7 +227,8 @@ namespace System.Globalization {
**Exceptions: ArgumentException if part is incorrect.
============================================================================*/
- internal int GetDatePart(long ticks, int part) {
+ internal int GetDatePart(long ticks, int part)
+ {
long NumDays; // The calculation buffer in number of days.
CheckTicksRange(ticks);
@@ -288,8 +307,10 @@ namespace System.Globalization {
//
- public override DateTime AddMonths(DateTime time, int months) {
- if (months < -120000 || months > 120000) {
+ public override DateTime AddMonths(DateTime time, int months)
+ {
+ if (months < -120000 || months > 120000)
+ {
throw new ArgumentOutOfRangeException(
nameof(months),
String.Format(
@@ -304,15 +325,19 @@ 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 days = GetDaysInMonth(y, m);
- if (d > days) {
+ if (d > days)
+ {
d = days;
}
long ticks = GetAbsoluteDatePersian(y, m, d) * TicksPerDay + time.Ticks % TicksPerDay;
@@ -330,7 +355,8 @@ namespace System.Globalization {
//
- public override DateTime AddYears(DateTime time, int years) {
+ public override DateTime AddYears(DateTime time, int years)
+ {
return (AddMonths(time, years * 12));
}
@@ -339,7 +365,8 @@ namespace System.Globalization {
//
- public override int GetDayOfMonth(DateTime time) {
+ public override int GetDayOfMonth(DateTime time)
+ {
return (GetDatePart(time.Ticks, DatePartDay));
}
@@ -350,7 +377,8 @@ namespace System.Globalization {
//
- public override DayOfWeek GetDayOfWeek(DateTime time) {
+ public override DayOfWeek GetDayOfWeek(DateTime time)
+ {
return ((DayOfWeek)((int)(time.Ticks / TicksPerDay + 1) % 7));
}
@@ -359,7 +387,8 @@ namespace System.Globalization {
//
- public override int GetDayOfYear(DateTime time) {
+ public override int GetDayOfYear(DateTime time)
+ {
return (GetDatePart(time.Ticks, DatePartDayOfYear));
}
@@ -368,10 +397,12 @@ namespace System.Globalization {
//
- public override int GetDaysInMonth(int year, int month, int era) {
+ public override int GetDaysInMonth(int year, int month, int era)
+ {
CheckYearMonthRange(year, month, era);
- if ((month==MaxCalendarMonth) && (year==MaxCalendarYear)) {
+ if ((month == MaxCalendarMonth) && (year == MaxCalendarYear))
+ {
return MaxCalendarDay;
}
@@ -387,28 +418,33 @@ namespace System.Globalization {
// 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) {
+ public override int GetDaysInYear(int year, int era)
+ {
CheckYearRange(year, era);
- if (year==MaxCalendarYear) {
- return DaysToMonth[MaxCalendarMonth-1] + MaxCalendarDay;
+ if (year == MaxCalendarYear)
+ {
+ return DaysToMonth[MaxCalendarMonth - 1] + MaxCalendarDay;
}
// Common years have 365 days. Leap years have 366 days.
- return (IsLeapYear(year, CurrentEra) ? 366: 365);
+ return (IsLeapYear(year, CurrentEra) ? 366 : 365);
}
// Returns the era for the specified DateTime value.
- public override int GetEra(DateTime time) {
+ public override int GetEra(DateTime time)
+ {
CheckTicksRange(time.Ticks);
return (PersianEra);
}
- public override int[] Eras {
- get {
- return (new int[] {PersianEra});
+ public override int[] Eras
+ {
+ get
+ {
+ return (new int[] { PersianEra });
}
}
@@ -417,16 +453,19 @@ namespace System.Globalization {
//
- public override int GetMonth(DateTime time) {
+ 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) {
+ public override int GetMonthsInYear(int year, int era)
+ {
CheckYearRange(year, era);
- if (year==MaxCalendarYear) {
+ if (year == MaxCalendarYear)
+ {
return MaxCalendarMonth;
}
return (12);
@@ -437,7 +476,8 @@ namespace System.Globalization {
//
- public override int GetYear(DateTime time) {
+ public override int GetYear(DateTime time)
+ {
return (GetDatePart(time.Ticks, DatePartYear));
}
@@ -446,10 +486,12 @@ namespace System.Globalization {
//
- public override bool IsLeapDay(int year, int month, int day, int era) {
+ 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) {
+ if (day < 1 || day > daysInMonth)
+ {
throw new ArgumentOutOfRangeException(
nameof(day),
String.Format(
@@ -477,7 +519,8 @@ namespace System.Globalization {
//
- public override bool IsLeapMonth(int year, int month, int era) {
+ public override bool IsLeapMonth(int year, int month, int era)
+ {
CheckYearMonthRange(year, month, era);
return (false);
}
@@ -486,7 +529,8 @@ namespace System.Globalization {
// year is a leap year, or false if not.
//
- public override bool IsLeapYear(int year, int era) {
+ public override bool IsLeapYear(int year, int era)
+ {
CheckYearRange(year, era);
if (year == MaxCalendarYear)
@@ -501,10 +545,12 @@ namespace System.Globalization {
//
- public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) {
+ 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) {
+ if (day < 1 || day > daysInMonth)
+ {
BCLDebug.Log("year = " + year + ", month = " + month + ", day = " + day);
throw new ArgumentOutOfRangeException(
nameof(day),
@@ -517,24 +563,31 @@ namespace System.Globalization {
long lDate = GetAbsoluteDatePersian(year, month, day);
- if (lDate >= 0) {
+ if (lDate >= 0)
+ {
return (new DateTime(lDate * GregorianCalendar.TicksPerDay + TimeToTicks(hour, minute, second, millisecond)));
- } else {
+ }
+ 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) {
+ public override int TwoDigitYearMax
+ {
+ get
+ {
+ if (twoDigitYearMax == -1)
+ {
twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX);
}
return (twoDigitYearMax);
}
- set {
+ set
+ {
VerifyWritable();
if (value < 99 || value > MaxCalendarYear)
{
@@ -552,18 +605,22 @@ namespace System.Globalization {
- 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"));
}
Contract.EndContractBlock();
- if (year < 100) {
+ if (year < 100)
+ {
return (base.ToFourDigitYear(year));
}
- if (year > MaxCalendarYear) {
+ if (year > MaxCalendarYear)
+ {
throw new ArgumentOutOfRangeException(
nameof(year),
String.Format(
diff --git a/src/mscorlib/src/System/Globalization/RegionInfo.cs b/src/mscorlib/src/System/Globalization/RegionInfo.cs
index b719af7128..e791c78b87 100644
--- a/src/mscorlib/src/System/Globalization/RegionInfo.cs
+++ b/src/mscorlib/src/System/Globalization/RegionInfo.cs
@@ -15,14 +15,14 @@
//
////////////////////////////////////////////////////////////////////////////
-namespace System.Globalization {
-
+namespace System.Globalization
+{
using System;
using System.Runtime.Serialization;
using System.Diagnostics;
using System.Diagnostics.Contracts;
- [Serializable]
+ [Serializable]
public partial class RegionInfo
{
//--------------------------------------------------------------------//
@@ -41,7 +41,7 @@ namespace System.Globalization {
//
// The CultureData instance that we are going to read data from.
//
- [NonSerialized]internal CultureData m_cultureData;
+ [NonSerialized] internal CultureData m_cultureData;
//
// The RegionInfo for our current region
@@ -59,15 +59,16 @@ 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));
}
-
+
Contract.EndContractBlock();
//
@@ -75,7 +76,7 @@ namespace System.Globalization {
// 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").
//
- this.m_cultureData = CultureData.GetCultureDataForRegion(name,true);
+ this.m_cultureData = CultureData.GetCultureDataForRegion(name, true);
// this.m_name = name.ToUpper(CultureInfo.InvariantCulture);
if (this.m_cultureData == null)
@@ -97,10 +98,10 @@ namespace System.Globalization {
public RegionInfo(int culture)
{
if (culture == CultureInfo.LOCALE_INVARIANT) //The InvariantCulture has no matching region
- {
+ {
throw new ArgumentException(Environment.GetResourceString("Argument_NoRegionInvariantCulture"));
}
-
+
if (culture == CultureInfo.LOCALE_NEUTRAL)
{
// Not supposed to be neutral
@@ -112,8 +113,8 @@ namespace System.Globalization {
// Not supposed to be neutral
throw new ArgumentException(Environment.GetResourceString("Argument_CustomCultureCannotBePassedByNumber", culture), nameof(culture));
}
-
- this.m_cultureData = CultureData.GetCultureData(culture,true);
+
+ this.m_cultureData = CultureData.GetCultureData(culture, true);
this.m_name = this.m_cultureData.SREGIONNAME;
if (this.m_cultureData.IsNeutralCulture)
@@ -124,7 +125,7 @@ namespace System.Globalization {
m_cultureId = culture;
}
#endif
-
+
internal RegionInfo(CultureData cultureData)
{
this.m_cultureData = cultureData;
@@ -137,14 +138,14 @@ namespace System.Globalization {
this.m_name = this.m_cultureData.SREGIONNAME;
}
-#region Serialization
+ #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;
+ private 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)]
@@ -172,12 +173,12 @@ namespace System.Globalization {
}
}
- [OnSerializing]
- private void OnSerializing(StreamingContext ctx)
- {
+ [OnSerializing]
+ private void OnSerializing(StreamingContext ctx)
+ {
// Used to fill in everett data item, unnecessary now
- }
-#endregion Serialization
+ }
+ #endregion Serialization
////////////////////////////////////////////////////////////////////////
//
@@ -188,15 +189,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);
// Need full name for custom cultures
- temp.m_name=temp.m_cultureData.SREGIONNAME;
+ temp.m_name = temp.m_cultureData.SREGIONNAME;
s_currentRegionInfo = temp;
}
return temp;
@@ -210,8 +213,10 @@ namespace System.Globalization {
// Returns the name of the region (ie: en-US)
//
////////////////////////////////////////////////////////////////////////
- public virtual String Name {
- get {
+ public virtual String Name
+ {
+ get
+ {
Debug.Assert(m_name != null, "Expected RegionInfo.m_name to be populated already");
return (m_name);
}
@@ -241,9 +246,9 @@ 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);
}
@@ -319,17 +324,19 @@ namespace System.Globalization {
// Returns true if this region uses the metric measurement system
//
////////////////////////////////////////////////////////////////////////
- public virtual bool IsMetric {
- get {
+ public virtual bool IsMetric
+ {
+ get
+ {
int value = this.m_cultureData.IMEASURE;
- return (value==0);
+ return (value == 0);
}
}
- public virtual int GeoId
+ public virtual int GeoId
{
- get
+ get
{
return (this.m_cultureData.IGEOID);
}
@@ -373,8 +380,10 @@ namespace System.Globalization {
// Currency Symbol for this locale, ie: Fr. or $
//
////////////////////////////////////////////////////////////////////////
- public virtual String CurrencySymbol {
- get {
+ public virtual String CurrencySymbol
+ {
+ get
+ {
return (this.m_cultureData.SCURRENCY);
}
}
@@ -386,8 +395,10 @@ namespace System.Globalization {
// ISO Currency Symbol for this locale, ie: CHF
//
////////////////////////////////////////////////////////////////////////
- public virtual String ISOCurrencySymbol {
- get {
+ public virtual String ISOCurrencySymbol
+ {
+ get
+ {
return (this.m_cultureData.SINTLSYMBOL);
}
}
@@ -439,6 +450,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..700699bf87 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,7 +25,7 @@ namespace System.Globalization {
//--------------------------------------------------------------------//
// Internal Information //
//--------------------------------------------------------------------//
-
+
//
// Variables.
//
@@ -34,8 +34,8 @@ namespace System.Globalization {
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;
- // Whidbey serialization
+ internal int win32LCID;
+ // Whidbey serialization
internal CompareOptions options; // options
internal String m_String; // original string
@@ -49,8 +49,8 @@ namespace System.Globalization {
{
this.m_KeyData = keyData;
this.localeName = localeName;
- this.options = options;
- this.m_String = str;
+ this.options = options;
+ this.m_String = str;
}
#if FEATURE_USE_LCID
@@ -74,7 +74,7 @@ namespace System.Globalization {
}
}
#endif //FEATURE_USE_LCID
-
+
////////////////////////////////////////////////////////////////////////
//
// GetOriginalString
@@ -85,12 +85,13 @@ namespace System.Globalization {
////////////////////////////////////////////////////////////////////////
public virtual String OriginalString
{
- get {
+ get
+ {
return (m_String);
}
}
-
-
+
+
////////////////////////////////////////////////////////////////////////
//
// GetKeyData
@@ -101,12 +102,13 @@ namespace System.Globalization {
////////////////////////////////////////////////////////////////////////
public virtual byte[] KeyData
{
- get {
+ get
+ {
return (byte[])(m_KeyData.Clone());
}
}
-
-
+
+
////////////////////////////////////////////////////////////////////////
//
// Compare
@@ -116,45 +118,51 @@ 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.m_KeyData;
byte[] key2Data = sortkey2.m_KeyData;
-
- Debug.Assert(key1Data!=null, "key1Data!=null");
- Debug.Assert(key2Data!=null, "key2Data!=null");
- if (key1Data.Length == 0) {
- if (key2Data.Length == 0) {
+ Debug.Assert(key1Data != null, "key1Data!=null");
+ Debug.Assert(key2Data != null, "key2Data!=null");
+
+ 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 +174,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 +182,8 @@ namespace System.Globalization {
return (false);
}
-
-
+
+
////////////////////////////////////////////////////////////////////////
//
// GetHashCode
@@ -190,8 +198,8 @@ namespace System.Globalization {
return (CompareInfo.GetCompareInfo(
this.localeName).GetHashCodeOfString(this.m_String, this.options));
}
-
-
+
+
////////////////////////////////////////////////////////////////////////
//
// ToString
diff --git a/src/mscorlib/src/System/Globalization/SortVersion.cs b/src/mscorlib/src/System/Globalization/SortVersion.cs
index 24fe8546fc..ab4ce01327 100644
--- a/src/mscorlib/src/System/Globalization/SortVersion.cs
+++ b/src/mscorlib/src/System/Globalization/SortVersion.cs
@@ -2,60 +2,60 @@
// 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;
+using System;
+using System.Diagnostics.Contracts;
+namespace System.Globalization
+{
[Serializable]
- public sealed class SortVersion : IEquatable<SortVersion>
+ public sealed class SortVersion : IEquatable<SortVersion>
{
private int m_NlsVersion;
private Guid m_SortId;
- public int FullVersion
+ public int FullVersion
{
- get
+ get
{
return m_NlsVersion;
}
}
- public Guid SortId
+ public Guid SortId
{
- get
+ get
{
return m_SortId;
}
}
- public SortVersion(int fullVersion, Guid sortId)
- {
+ public SortVersion(int fullVersion, Guid sortId)
+ {
m_SortId = sortId;
m_NlsVersion = fullVersion;
}
- internal SortVersion(int nlsVersion, int effectiveId, Guid customVersion)
+ internal SortVersion(int nlsVersion, int effectiveId, Guid customVersion)
{
m_NlsVersion = nlsVersion;
- if (customVersion == Guid.Empty)
+ 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);
+ 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)
+ public override bool Equals(object obj)
{
SortVersion n = obj as SortVersion;
- if(n != null)
+ if (n != null)
{
return this.Equals(n);
}
@@ -63,9 +63,9 @@ namespace System.Globalization
return false;
}
- public bool Equals(SortVersion other)
+ public bool Equals(SortVersion other)
{
- if (other == null)
+ if (other == null)
{
return false;
}
@@ -73,19 +73,19 @@ namespace System.Globalization
return m_NlsVersion == other.m_NlsVersion && m_SortId == other.m_SortId;
}
- public override int GetHashCode()
- {
- return m_NlsVersion * 7 | m_SortId.GetHashCode();
+ public override int GetHashCode()
+ {
+ return m_NlsVersion * 7 | m_SortId.GetHashCode();
}
- public static bool operator ==(SortVersion left, SortVersion right)
+ public static bool operator ==(SortVersion left, SortVersion right)
{
- if (((object) left) != null)
+ if (((object)left) != null)
{
return left.Equals(right);
}
- if (((object) right) != null)
+ if (((object)right) != null)
{
return right.Equals(left);
}
@@ -94,7 +94,7 @@ namespace System.Globalization
return true;
}
- public static bool operator !=(SortVersion left, SortVersion right)
+ public static bool operator !=(SortVersion left, SortVersion right)
{
return !(left == right);
}
diff --git a/src/mscorlib/src/System/Globalization/StringInfo.cs b/src/mscorlib/src/System/Globalization/StringInfo.cs
index dc32fe9493..1cc2df3775 100644
--- a/src/mscorlib/src/System/Globalization/StringInfo.cs
+++ b/src/mscorlib/src/System/Globalization/StringInfo.cs
@@ -12,38 +12,39 @@
//
////////////////////////////////////////////////////////////////////////////
-namespace System.Globalization {
-
- using System;
- using System.Runtime.Serialization;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
+using System;
+using System.Runtime.Serialization;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+
+namespace System.Globalization
+{
[Serializable]
- public class StringInfo
+ public class StringInfo
{
+ [OptionalField(VersionAdded = 2)]
+ private String m_str;
- [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;
// 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)
- {
+
+ #region Serialization
+ [OnDeserializing]
+ private void OnDeserializing(StreamingContext ctx)
+ {
m_str = String.Empty;
- }
+ }
[OnDeserialized]
private void OnDeserialized(StreamingContext ctx)
@@ -52,73 +53,87 @@ namespace System.Globalization {
{
m_indexes = null;
}
- }
-#endregion Serialization
+ }
+ #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 (m_str.Equals(that.m_str));
}
return (false);
}
public override int GetHashCode()
{
- return this.m_str.GetHashCode();
+ return m_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 == m_indexes) && (0 < this.String.Length))
+ {
+ m_indexes = StringInfo.ParseCombiningCharacters(this.String);
}
- return(this.m_indexes);
+ return (m_indexes);
}
}
- public String String {
- get {
- return(this.m_str);
+ public String String
+ {
+ get
+ {
+ return (m_str);
}
- set {
- if (null == value) {
+ set
+ {
+ if (null == value)
+ {
throw new ArgumentNullException(nameof(String),
Environment.GetResourceString("ArgumentNull_String"));
}
Contract.EndContractBlock();
- this.m_str = value;
- this.m_indexes = null;
+ m_str = value;
+ m_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) {
+ if (startingTextElement < 0)
+ {
throw new ArgumentOutOfRangeException(nameof(startingTextElement),
Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
}
- else {
+ else
+ {
throw new ArgumentOutOfRangeException(nameof(startingTextElement),
Environment.GetResourceString("Arg_ArgumentOutOfRangeException"));
}
@@ -126,43 +141,49 @@ namespace System.Globalization {
return (this.SubstringByTextElements(startingTextElement, this.Indexes.Length - startingTextElement));
}
- public String SubstringByTextElements(int startingTextElement, int lengthInTextElements) {
-
+ public String SubstringByTextElements(int startingTextElement, int lengthInTextElements)
+ {
//
// Parameter checking
//
- if(startingTextElement < 0) {
+ if (startingTextElement < 0)
+ {
throw new ArgumentOutOfRangeException(nameof(startingTextElement),
Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
}
- if(this.String.Length == 0 || startingTextElement >= this.Indexes.Length) {
+ if (this.String.Length == 0 || startingTextElement >= this.Indexes.Length)
+ {
throw new ArgumentOutOfRangeException(nameof(startingTextElement),
Environment.GetResourceString("Arg_ArgumentOutOfRangeException"));
}
- if(lengthInTextElements < 0) {
+ if (lengthInTextElements < 0)
+ {
throw new ArgumentOutOfRangeException(nameof(lengthInTextElements),
Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
}
- if(startingTextElement > this.Indexes.Length - lengthInTextElements) {
+ if (startingTextElement > this.Indexes.Length - lengthInTextElements)
+ {
throw new ArgumentOutOfRangeException(nameof(lengthInTextElements),
Environment.GetResourceString("Arg_ArgumentOutOfRangeException"));
}
int start = this.Indexes[startingTextElement];
- if(startingTextElement + lengthInTextElements == this.Indexes.Length) {
+ if (startingTextElement + lengthInTextElements == this.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, (this.Indexes[lengthInTextElements + startingTextElement] - start)));
}
}
-
+
public static String GetNextTextElement(String str)
{
return (GetNextTextElement(str, 0));
@@ -200,7 +221,7 @@ 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)
{
Debug.Assert(index >= 0 && len >= 0, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
@@ -214,30 +235,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,26 +279,30 @@ 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"));
}
@@ -286,18 +315,18 @@ namespace System.Globalization {
{
return (GetTextElementEnumerator(str, 0));
}
-
+
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))
{
@@ -326,7 +355,7 @@ namespace System.Globalization {
throw new ArgumentNullException(nameof(str));
}
Contract.EndContractBlock();
-
+
int len = str.Length;
int[] result = new int[len];
if (len == 0)
@@ -338,11 +367,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 +382,6 @@ namespace System.Globalization {
return (returnArray);
}
return (result);
-
}
}
}
diff --git a/src/mscorlib/src/System/Globalization/TaiwanCalendar.cs b/src/mscorlib/src/System/Globalization/TaiwanCalendar.cs
index ec84a06b76..060776fc28 100644
--- a/src/mscorlib/src/System/Globalization/TaiwanCalendar.cs
+++ b/src/mscorlib/src/System/Globalization/TaiwanCalendar.cs
@@ -2,27 +2,31 @@
// 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 System;
+using System.Diagnostics.CodeAnalysis;
+using System.Diagnostics.Contracts;
+
+namespace System.Globalization
+{
/* 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 {
+ /*=================================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.
//
@@ -51,8 +55,10 @@ namespace System.Globalization {
**Exceptions:
============================================================================*/
- internal static Calendar GetDefaultInstance() {
- if (s_defaultInstance == null) {
+ internal static Calendar GetDefaultInstance()
+ {
+ if (s_defaultInstance == null)
+ {
s_defaultInstance = new TaiwanCalendar();
}
return (s_defaultInstance);
@@ -89,48 +95,60 @@ namespace System.Globalization {
}
- public TaiwanCalendar() {
- try {
+ public TaiwanCalendar()
+ {
+ try
+ {
new CultureInfo("zh-TW");
- } catch (ArgumentException e) {
+ }
+ catch (ArgumentException e)
+ {
throw new TypeInitializationException(this.GetType().FullName, e);
}
helper = new GregorianCalendarHelper(this, taiwanEraInfo);
}
- internal override int ID {
- get {
+ internal override int ID
+ {
+ get
+ {
return (CAL_TAIWAN);
}
}
- public override DateTime AddMonths(DateTime time, int months) {
+ public override DateTime AddMonths(DateTime time, int months)
+ {
return (helper.AddMonths(time, months));
}
- public override DateTime AddYears(DateTime time, int years) {
+ public override DateTime AddYears(DateTime time, int years)
+ {
return (helper.AddYears(time, years));
}
- public override int GetDaysInMonth(int year, int month, int era) {
+ public override int GetDaysInMonth(int year, int month, int era)
+ {
return (helper.GetDaysInMonth(year, month, era));
}
- public override int GetDaysInYear(int year, int era) {
+ public override int GetDaysInYear(int year, int era)
+ {
return (helper.GetDaysInYear(year, era));
}
- public override int GetDayOfMonth(DateTime time) {
+ public override int GetDayOfMonth(DateTime time)
+ {
return (helper.GetDayOfMonth(time));
}
- public override DayOfWeek GetDayOfWeek(DateTime time) {
+ public override DayOfWeek GetDayOfWeek(DateTime time)
+ {
return (helper.GetDayOfWeek(time));
}
@@ -141,7 +159,8 @@ namespace System.Globalization {
}
- public override int GetMonthsInYear(int year, int era) {
+ public override int GetMonthsInYear(int year, int era)
+ {
return (helper.GetMonthsInYear(year, era));
}
@@ -153,16 +172,19 @@ namespace System.Globalization {
}
- public override int GetEra(DateTime time) {
+ public override int GetEra(DateTime time)
+ {
return (helper.GetEra(time));
}
- public override int GetMonth(DateTime time) {
+ public override int GetMonth(DateTime time)
+ {
return (helper.GetMonth(time));
}
- public override int GetYear(DateTime time) {
+ public override int GetYear(DateTime time)
+ {
return (helper.GetYear(time));
}
@@ -173,7 +195,8 @@ namespace System.Globalization {
}
- public override bool IsLeapYear(int year, int era) {
+ public override bool IsLeapYear(int year, int era)
+ {
return (helper.IsLeapYear(year, era));
}
@@ -187,33 +210,41 @@ namespace System.Globalization {
}
- public override bool IsLeapMonth(int year, int month, int 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) {
+ 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 {
+ 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) {
+ public override int TwoDigitYearMax
+ {
+ get
+ {
+ if (twoDigitYearMax == -1)
+ {
twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX);
}
return (twoDigitYearMax);
}
- set {
+ set
+ {
VerifyWritable();
if (value < 99 || value > helper.MaxYear)
{
@@ -224,7 +255,6 @@ namespace System.Globalization {
Environment.GetResourceString("ArgumentOutOfRange_Range"),
99,
helper.MaxYear));
-
}
twoDigitYearMax = value;
}
@@ -233,14 +263,17 @@ namespace System.Globalization {
// 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) {
+ public override int ToFourDigitYear(int year)
+ {
+ if (year <= 0)
+ {
throw new ArgumentOutOfRangeException(nameof(year),
Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
}
Contract.EndContractBlock();
- if (year > helper.MaxYear) {
+ if (year > helper.MaxYear)
+ {
throw new ArgumentOutOfRangeException(
nameof(year),
String.Format(
diff --git a/src/mscorlib/src/System/Globalization/TaiwanLunisolarCalendar.cs b/src/mscorlib/src/System/Globalization/TaiwanLunisolarCalendar.cs
index d96c450f49..4331cb4acb 100644
--- a/src/mscorlib/src/System/Globalization/TaiwanLunisolarCalendar.cs
+++ b/src/mscorlib/src/System/Globalization/TaiwanLunisolarCalendar.cs
@@ -2,26 +2,27 @@
// 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;
+using System;
+using System.Diagnostics.Contracts;
+namespace System.Globalization
+{
////////////////////////////////////////////////////////////////////////////
//
// Notes about TaiwanLunisolarCalendar
//
////////////////////////////////////////////////////////////////////////////
- /*
- ** Calendar support range:
- ** Calendar Minimum Maximum
- ** ========== ========== ==========
- ** Gregorian 1912/02/18 2051/02/10
- ** TaiwanLunisolar 1912/01/01 2050/13/29
- */
+ /*
+ ** 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 {
-
+ public class TaiwanLunisolarCalendar : EastAsianLunisolarCalendar
+ {
// Since
// Gregorian Year = Era Year + yearOffset
// When Gregorian Year 1912 is year 1, so that
@@ -50,7 +51,8 @@ namespace System.Globalization {
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 {
+ public override DateTime MinSupportedDateTime
+ {
get
{
return (minDate);
@@ -59,7 +61,8 @@ namespace System.Globalization {
- public override DateTime MaxSupportedDateTime {
+ public override DateTime MaxSupportedDateTime
+ {
get
{
return (maxDate);
@@ -75,7 +78,7 @@ namespace System.Globalization {
}
}
- static readonly int [,] yinfo =
+ private 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
@@ -220,61 +223,70 @@ namespace System.Globalization {
*/};
- internal override int MinCalendarYear {
+ internal override int MinCalendarYear
+ {
get
{
return (MIN_LUNISOLAR_YEAR);
}
}
- internal override int MaxCalendarYear {
+ internal override int MaxCalendarYear
+ {
get
{
return (MAX_LUNISOLAR_YEAR);
}
}
- internal override DateTime MinDate {
+ internal override DateTime MinDate
+ {
get
{
return (minDate);
}
}
- internal override DateTime MaxDate {
+ internal override DateTime MaxDate
+ {
get
{
return (maxDate);
}
}
- internal override EraInfo[] CalEraInfo {
+ internal override EraInfo[] CalEraInfo
+ {
get
{
return (taiwanLunisolarEraInfo);
}
}
- internal override int GetYearInfo(int LunarYear, int Index) {
- if ((LunarYear < MIN_LUNISOLAR_YEAR) || (LunarYear > MAX_LUNISOLAR_YEAR)) {
+ 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 ));
+ MAX_LUNISOLAR_YEAR));
}
Contract.EndContractBlock();
return yinfo[LunarYear - MIN_LUNISOLAR_YEAR, Index];
}
- internal override int GetYear(int year, DateTime time) {
+ internal override int GetYear(int year, DateTime time)
+ {
return helper.GetYear(year, time);
}
- internal override int GetGregorianYear(int year, int era) {
+ internal override int GetGregorianYear(int year, int era)
+ {
return helper.GetGregorianYear(year, era);
}
@@ -297,32 +309,40 @@ namespace System.Globalization {
// Construct an instance of TaiwanLunisolar calendar.
- public TaiwanLunisolarCalendar() {
+ public TaiwanLunisolarCalendar()
+ {
helper = new GregorianCalendarHelper(this, taiwanLunisolarEraInfo);
}
- public override int GetEra(DateTime time) {
+ public override int GetEra(DateTime time)
+ {
return (helper.GetEra(time));
}
- internal override int BaseCalendarID {
- get {
+ internal override int BaseCalendarID
+ {
+ get
+ {
return (CAL_TAIWAN);
}
}
- internal override int ID {
- get {
+ internal override int ID
+ {
+ get
+ {
return (CAL_TAIWANLUNISOLAR);
}
}
- public override int[] Eras {
- get {
+ 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..45b7009e34 100644
--- a/src/mscorlib/src/System/Globalization/TextElementEnumerator.cs
+++ b/src/mscorlib/src/System/Globalization/TextElementEnumerator.cs
@@ -13,32 +13,33 @@
using System.Runtime.Serialization;
-namespace System.Globalization {
- using System.Collections;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
+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;
-
- [NonSerialized]
+
+ [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.
-
- [OptionalField(VersionAdded = 2)]
+
+ [OptionalField(VersionAdded = 2)]
private UnicodeCategory uc;
-
- [OptionalField(VersionAdded = 2)]
+
+ [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.
internal TextElementEnumerator(String str, int startIndex, int strLen)
@@ -52,38 +53,38 @@ namespace System.Globalization {
Reset();
}
-#region Serialization
+ #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;
- }
-
+ [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)
{
uc = CharUnicodeInfo.InternalGetUnicodeCategory(str, index, out charLen);
}
- }
-
- [OnSerializing]
- private void OnSerializing(StreamingContext ctx)
- {
- endIndex = strLen - 1;
- nextTextElementLen = currTextElementLen;
- }
+ }
+
+ [OnSerializing]
+ private void OnSerializing(StreamingContext ctx)
+ {
+ endIndex = strLen - 1;
+ nextTextElementLen = currTextElementLen;
+ }
-#endregion Serialization
+ #endregion Serialization
@@ -104,8 +105,10 @@ namespace System.Globalization {
// Get the current text element.
//
- public Object Current {
- get {
+ public Object Current
+ {
+ get
+ {
return (GetTextElement());
}
}
@@ -116,16 +119,18 @@ namespace System.Globalization {
public String GetTextElement()
{
- if (index == startIndex) {
+ if (index == startIndex)
+ {
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumNotStarted"));
}
- if (index > strLen) {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumEnded"));
- }
-
+ if (index > strLen)
+ {
+ throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumEnded"));
+ }
+
return (str.Substring(index - currTextElementLen, currTextElementLen));
}
-
+
//
// Get the starting index of the current text element.
//
@@ -134,7 +139,7 @@ namespace System.Globalization {
{
get
{
- if (index == startIndex)
+ if (index == startIndex)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumNotStarted"));
}
@@ -146,10 +151,11 @@ namespace System.Globalization {
public void Reset()
{
index = startIndex;
- if (index < strLen) {
+ if (index < strLen)
+ {
// If we have more than 1 character, get the category of the current char.
uc = CharUnicodeInfo.InternalGetUnicodeCategory(str, index, out charLen);
- }
+ }
}
}
}
diff --git a/src/mscorlib/src/System/Globalization/TextInfo.cs b/src/mscorlib/src/System/Globalization/TextInfo.cs
index 9ece275dd3..d698e64930 100644
--- a/src/mscorlib/src/System/Globalization/TextInfo.cs
+++ b/src/mscorlib/src/System/Globalization/TextInfo.cs
@@ -14,7 +14,8 @@
using System.Security;
-namespace System.Globalization {
+namespace System.Globalization
+{
using System;
using System.Text;
using System.Threading;
@@ -72,18 +73,18 @@ namespace System.Globalization {
//
[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 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;
// Invariant text info
- internal static TextInfo Invariant
+ internal static TextInfo Invariant
{
- get
+ get
{
if (s_Invariant == null)
s_Invariant = new TextInfo(CultureData.Invariant);
@@ -99,12 +100,12 @@ namespace System.Globalization {
// Implements CultureInfo.TextInfo.
//
////////////////////////////////////////////////////////////////////////
- internal TextInfo(CultureData cultureData)
+ internal 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;
+ m_cultureData = cultureData;
+ m_cultureName = m_cultureData.CultureName;
+ m_textInfoName = m_cultureData.STEXTINFO;
}
////////////////////////////////////////////////////////////////////////
@@ -115,7 +116,7 @@ namespace System.Globalization {
//
////////////////////////////////////////////////////////////////////////
-#region Serialization
+ #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)]
@@ -124,33 +125,33 @@ namespace System.Globalization {
// 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;
+ internal int m_nDataItem;
[OptionalField(VersionAdded = 1)]
- internal bool m_useUserOverride;
+ internal bool m_useUserOverride;
[OptionalField(VersionAdded = 1)]
- internal int m_win32LangID;
+ internal int m_win32LangID;
- [OnDeserializing]
- private void OnDeserializing(StreamingContext ctx)
- {
+ [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;
- }
+ m_cultureData = null;
+ m_cultureName = null;
+ }
private void OnDeserialized()
{
// this method will be called twice because of the support of IDeserializationCallback
- if (this.m_cultureData == null)
+ if (m_cultureData == null)
{
- if (this.m_cultureName == null)
+ if (m_cultureName == null)
{
// This is whidbey data, get it from customCultureName/win32langid
- if (this.customCultureName != null)
+ if (customCultureName != null)
{
// They gave a custom cultuer name, so use that
- this.m_cultureName = this.customCultureName;
+ m_cultureName = customCultureName;
}
#if FEATURE_USE_LCID
else
@@ -169,10 +170,10 @@ namespace System.Globalization {
}
#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;
+ m_cultureData = CultureInfo.GetCultureInfo(m_cultureName).m_cultureData;
+ m_textInfoName = m_cultureData.STEXTINFO;
}
}
@@ -183,18 +184,18 @@ namespace System.Globalization {
}
[OnSerializing]
- private void OnSerializing(StreamingContext ctx)
+ private void OnSerializing(StreamingContext ctx)
{
// Relabel our name since Whidbey expects it to be called customCultureName
- this.customCultureName = this.m_cultureName;
+ customCultureName = m_cultureName;
#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;
+ this.m_win32LangID = (CultureInfo.GetCultureInfo(m_cultureName)).LCID;
#endif
- }
-
-#endregion Serialization
+ }
+
+ #endregion Serialization
//
// Internal ordinal comparison functions
@@ -226,9 +227,9 @@ namespace System.Globalization {
// 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 )
+ 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(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);
}
@@ -255,7 +256,7 @@ namespace System.Globalization {
// [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.
@@ -271,7 +272,7 @@ namespace System.Globalization {
return startIndex;
}
}
-
+
// Not found
return -1;
}
@@ -280,7 +281,7 @@ namespace System.Globalization {
{
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 - 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
@@ -298,7 +299,7 @@ namespace System.Globalization {
// 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)
{
@@ -312,7 +313,7 @@ namespace System.Globalization {
return startIndex;
}
}
-
+
// Not found
return -1;
}
@@ -331,38 +332,38 @@ namespace System.Globalization {
////////////////////////////////////////////////////////////////////////
- public virtual int ANSICodePage
+ public virtual int ANSICodePage
{
- get
+ get
{
- return (this.m_cultureData.IDEFAULTANSICODEPAGE);
+ return (m_cultureData.IDEFAULTANSICODEPAGE);
}
}
-
- public virtual int OEMCodePage
+
+ public virtual int OEMCodePage
{
- get
+ get
{
- return (this.m_cultureData.IDEFAULTOEMCODEPAGE);
+ return (m_cultureData.IDEFAULTOEMCODEPAGE);
}
}
- public virtual int MacCodePage
+ public virtual int MacCodePage
{
- get
+ get
{
- return (this.m_cultureData.IDEFAULTMACCODEPAGE);
+ return (m_cultureData.IDEFAULTMACCODEPAGE);
}
}
- public virtual int EBCDICCodePage
+ public virtual int EBCDICCodePage
{
- get
+ get
{
- return (this.m_cultureData.IDEFAULTEBCDICCODEPAGE);
+ return (m_cultureData.IDEFAULTEBCDICCODEPAGE);
}
}
@@ -376,12 +377,12 @@ namespace System.Globalization {
////////////////////////////////////////////////////////////////////////
#if FEATURE_USE_LCID
- public int 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(m_textInfoName).LCID;
}
}
#endif
@@ -392,11 +393,11 @@ namespace System.Globalization {
// The name of the culture associated with the current TextInfo.
//
////////////////////////////////////////////////////////////////////////
- public string CultureName
+ public string CultureName
{
- get
+ get
{
- return(this.m_textInfoName);
+ return (m_textInfoName);
}
}
@@ -407,7 +408,7 @@ namespace System.Globalization {
// Detect if the object is readonly.
//
////////////////////////////////////////////////////////////////////////
- public bool IsReadOnly
+ public bool IsReadOnly
{
get { return (m_isReadOnly); }
}
@@ -422,10 +423,10 @@ namespace System.Globalization {
public virtual Object Clone()
{
object o = MemberwiseClone();
- ((TextInfo) o).SetReadOnlyState(false);
+ ((TextInfo)o).SetReadOnlyState(false);
return (o);
}
-
+
////////////////////////////////////////////////////////////////////////
//
// ReadOnly
@@ -434,21 +435,21 @@ 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 (m_isReadOnly)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
}
@@ -470,19 +471,20 @@ namespace System.Globalization {
////////////////////////////////////////////////////////////////////////
- public virtual String ListSeparator
+ public virtual String ListSeparator
{
- get
+ get
{
- if (m_listSeparator == null) {
- m_listSeparator = this.m_cultureData.SLIST;
+ if (m_listSeparator == null)
+ {
+ m_listSeparator = m_cultureData.SLIST;
}
return (m_listSeparator);
}
- set
+ set
{
- if (value == null)
+ if (value == null)
{
throw new ArgumentNullException(nameof(value), Environment.GetResourceString("ArgumentNull_String"));
}
@@ -501,22 +503,21 @@ namespace System.Globalization {
//
////////////////////////////////////////////////////////////////////////
- public unsafe virtual char ToLower(char c)
+ public unsafe virtual char ToLower(char c)
{
- if(IsAscii(c) && IsAsciiCasingSameAsInvariant)
+ if (IsAscii(c) && IsAsciiCasingSameAsInvariant)
{
return ToLowerAsciiInvariant(c);
}
- return (InternalChangeCaseChar(this.m_dataHandle, this.m_handleOrigin, this.m_textInfoName, c, false));
+ return (InternalChangeCaseChar(m_dataHandle, m_handleOrigin, m_textInfoName, c, 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);
-
+ return InternalChangeCaseString(m_dataHandle, m_handleOrigin, m_textInfoName, str, false);
}
static private Char ToLowerAsciiInvariant(Char c)
@@ -537,21 +538,21 @@ namespace System.Globalization {
//
////////////////////////////////////////////////////////////////////////
- public unsafe virtual char ToUpper(char c)
+ public unsafe virtual char ToUpper(char c)
{
if (IsAscii(c) && IsAsciiCasingSameAsInvariant)
{
return ToUpperAsciiInvariant(c);
}
- return (InternalChangeCaseChar(this.m_dataHandle, this.m_handleOrigin, this.m_textInfoName, c, true));
+ return (InternalChangeCaseChar(m_dataHandle, m_handleOrigin, m_textInfoName, c, 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);
+ return InternalChangeCaseString(m_dataHandle, m_handleOrigin, m_textInfoName, str, true);
}
static private Char ToUpperAsciiInvariant(Char c)
@@ -596,12 +597,12 @@ namespace System.Globalization {
public override bool Equals(Object obj)
{
TextInfo that = obj as TextInfo;
-
+
if (that != null)
{
return this.CultureName.Equals(that.CultureName);
}
-
+
return (false);
}
@@ -635,7 +636,7 @@ namespace System.Globalization {
public override String ToString()
{
- return ("TextInfo - " + this.m_cultureData.CultureName);
+ return ("TextInfo - " + m_cultureData.CultureName);
}
@@ -662,14 +663,14 @@ namespace System.Globalization {
// 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);
}
@@ -677,17 +678,17 @@ namespace System.Globalization {
StringBuilder result = new StringBuilder();
String lowercaseData = null;
- 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;
-
+
//
// Convert the characters until the end of the this word
// to lowercase.
@@ -700,42 +701,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
+ i += charLen;
+ }
+ else
{
// A word separator. Break out of the loop.
break;
@@ -744,29 +745,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,65 +776,65 @@ 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(this.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 );
+ result.Append((char)0x01C5);
break;
case (char)0x01C7: // LJ -> Lj
case (char)0x01C8: // Lj -> Lj
case (char)0x01C9: // lj -> Lj
- result.Append( (char)0x01C8 );
+ result.Append((char)0x01C8);
break;
case (char)0x01CA: // NJ -> Nj
case (char)0x01CB: // Nj -> Nj
case (char)0x01CC: // nj -> Nj
- result.Append( (char)0x01CB );
+ result.Append((char)0x01CB);
break;
case (char)0x01F1: // DZ -> Dz
case (char)0x01F2: // Dz -> Dz
case (char)0x01F3: // dz -> Dz
- result.Append( (char)0x01F2 );
+ result.Append((char)0x01F2);
break;
default:
- result.Append( this.ToUpper(input[inputIndex]) );
+ result.Append(this.ToUpper(input[inputIndex]));
break;
}
- }
+ }
return inputIndex;
}
@@ -843,44 +844,44 @@ namespace System.Globalization {
// 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 =
- /* false */ (0 << 0) | // UppercaseLetter = 0,
- /* false */ (0 << 1) | // LowercaseLetter = 1,
- /* false */ (0 << 2) | // TitlecaseLetter = 2,
- /* false */ (0 << 3) | // ModifierLetter = 3,
- /* false */ (0 << 4) | // OtherLetter = 4,
- /* false */ (0 << 5) | // NonSpacingMark = 5,
- /* false */ (0 << 6) | // SpacingCombiningMark = 6,
- /* false */ (0 << 7) | // EnclosingMark = 7,
- /* false */ (0 << 8) | // DecimalDigitNumber = 8,
- /* false */ (0 << 9) | // LetterNumber = 9,
- /* false */ (0 << 10) | // OtherNumber = 10,
- /* true */ (1 << 11) | // SpaceSeparator = 11,
- /* true */ (1 << 12) | // LineSeparator = 12,
- /* true */ (1 << 13) | // ParagraphSeparator = 13,
- /* true */ (1 << 14) | // Control = 14,
- /* true */ (1 << 15) | // Format = 15,
- /* false */ (0 << 16) | // Surrogate = 16,
- /* false */ (0 << 17) | // PrivateUse = 17,
- /* true */ (1 << 18) | // ConnectorPunctuation = 18,
- /* true */ (1 << 19) | // DashPunctuation = 19,
- /* true */ (1 << 20) | // OpenPunctuation = 20,
- /* true */ (1 << 21) | // ClosePunctuation = 21,
- /* true */ (1 << 22) | // InitialQuotePunctuation = 22,
- /* true */ (1 << 23) | // FinalQuotePunctuation = 23,
- /* true */ (1 << 24) | // OtherPunctuation = 24,
- /* true */ (1 << 25) | // MathSymbol = 25,
- /* true */ (1 << 26) | // CurrencySymbol = 26,
- /* true */ (1 << 27) | // ModifierSymbol = 27,
- /* true */ (1 << 28) | // OtherSymbol = 28,
- /* false */ (0 << 29); // OtherNotAssigned = 29;
-
- private static bool IsWordSeparator(UnicodeCategory category)
+ private const int wordSeparatorMask =
+ /* false */ (0 << 0) | // UppercaseLetter = 0,
+ /* false */ (0 << 1) | // LowercaseLetter = 1,
+ /* false */ (0 << 2) | // TitlecaseLetter = 2,
+ /* false */ (0 << 3) | // ModifierLetter = 3,
+ /* false */ (0 << 4) | // OtherLetter = 4,
+ /* false */ (0 << 5) | // NonSpacingMark = 5,
+ /* false */ (0 << 6) | // SpacingCombiningMark = 6,
+ /* false */ (0 << 7) | // EnclosingMark = 7,
+ /* false */ (0 << 8) | // DecimalDigitNumber = 8,
+ /* false */ (0 << 9) | // LetterNumber = 9,
+ /* false */ (0 << 10) | // OtherNumber = 10,
+ /* true */ (1 << 11) | // SpaceSeparator = 11,
+ /* true */ (1 << 12) | // LineSeparator = 12,
+ /* true */ (1 << 13) | // ParagraphSeparator = 13,
+ /* true */ (1 << 14) | // Control = 14,
+ /* true */ (1 << 15) | // Format = 15,
+ /* false */ (0 << 16) | // Surrogate = 16,
+ /* false */ (0 << 17) | // PrivateUse = 17,
+ /* true */ (1 << 18) | // ConnectorPunctuation = 18,
+ /* true */ (1 << 19) | // DashPunctuation = 19,
+ /* true */ (1 << 20) | // OpenPunctuation = 20,
+ /* true */ (1 << 21) | // ClosePunctuation = 21,
+ /* true */ (1 << 22) | // InitialQuotePunctuation = 22,
+ /* true */ (1 << 23) | // FinalQuotePunctuation = 23,
+ /* true */ (1 << 24) | // OtherPunctuation = 24,
+ /* true */ (1 << 25) | // MathSymbol = 25,
+ /* true */ (1 << 26) | // CurrencySymbol = 26,
+ /* 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;
}
- private static bool IsLetterCategory(UnicodeCategory uc)
+ private static bool IsLetterCategory(UnicodeCategory uc)
{
return (uc == UnicodeCategory.UppercaseLetter
|| uc == UnicodeCategory.LowercaseLetter
@@ -897,7 +898,7 @@ namespace System.Globalization {
{
get
{
- return this.m_cultureData.IsRightToLeft;
+ return m_cultureData.IsRightToLeft;
}
}
@@ -922,20 +923,20 @@ namespace System.Globalization {
internal unsafe int GetCaseInsensitiveHashCode(String str, bool forceRandomizedHashing, long additionalEntropy)
{
// Validate inputs
- if (str==null)
+ if (str == null)
{
- throw new ArgumentNullException(nameof(str));
+ throw new ArgumentNullException(nameof(str));
}
Contract.EndContractBlock();
// Return our result
- return (InternalGetCaseInsHash(this.m_dataHandle, this.m_handleOrigin, this.m_textInfoName, str, forceRandomizedHashing, additionalEntropy));
+ return (InternalGetCaseInsHash(m_dataHandle, m_handleOrigin, m_textInfoName, str, forceRandomizedHashing, additionalEntropy));
}
// 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);
@@ -958,7 +959,6 @@ namespace System.Globalization {
[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);
}
-
}
diff --git a/src/mscorlib/src/System/Globalization/ThaiBuddhistCalendar.cs b/src/mscorlib/src/System/Globalization/ThaiBuddhistCalendar.cs
index 762c3ca7cb..65489ce4cc 100644
--- a/src/mscorlib/src/System/Globalization/ThaiBuddhistCalendar.cs
+++ b/src/mscorlib/src/System/Globalization/ThaiBuddhistCalendar.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;
- using System.Diagnostics.CodeAnalysis;
- using System.Diagnostics.Contracts;
+using System;
+using System.Diagnostics.CodeAnalysis;
+using System.Diagnostics.Contracts;
+namespace System.Globalization
+{
/*=================================ThaiBuddhistCalendar==========================
**
** ThaiBuddhistCalendar is based on Gregorian calendar. Its year value has
@@ -21,8 +22,9 @@ namespace System.Globalization {
============================================================================*/
- [Serializable] public class ThaiBuddhistCalendar: Calendar {
-
+ [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
@@ -66,43 +68,52 @@ namespace System.Globalization {
}
}
- public ThaiBuddhistCalendar() {
+ public ThaiBuddhistCalendar()
+ {
helper = new GregorianCalendarHelper(this, thaiBuddhistEraInfo);
}
- internal override int ID {
- get {
+ internal override int ID
+ {
+ get
+ {
return (CAL_THAI);
}
}
- public override DateTime AddMonths(DateTime time, int months) {
+ public override DateTime AddMonths(DateTime time, int months)
+ {
return (helper.AddMonths(time, months));
}
- public override DateTime AddYears(DateTime time, int years) {
+ public override DateTime AddYears(DateTime time, int years)
+ {
return (helper.AddYears(time, years));
}
- public override int GetDaysInMonth(int year, int month, int era) {
+ public override int GetDaysInMonth(int year, int month, int era)
+ {
return (helper.GetDaysInMonth(year, month, era));
}
- public override int GetDaysInYear(int year, int era) {
+ public override int GetDaysInYear(int year, int era)
+ {
return (helper.GetDaysInYear(year, era));
}
- public override int GetDayOfMonth(DateTime time) {
+ public override int GetDayOfMonth(DateTime time)
+ {
return (helper.GetDayOfMonth(time));
}
- public override DayOfWeek GetDayOfWeek(DateTime time) {
+ public override DayOfWeek GetDayOfWeek(DateTime time)
+ {
return (helper.GetDayOfWeek(time));
}
@@ -113,7 +124,8 @@ namespace System.Globalization {
}
- public override int GetMonthsInYear(int year, int era) {
+ public override int GetMonthsInYear(int year, int era)
+ {
return (helper.GetMonthsInYear(year, era));
}
@@ -125,16 +137,19 @@ namespace System.Globalization {
}
- public override int GetEra(DateTime time) {
+ public override int GetEra(DateTime time)
+ {
return (helper.GetEra(time));
}
- public override int GetMonth(DateTime time) {
+ public override int GetMonth(DateTime time)
+ {
return (helper.GetMonth(time));
}
- public override int GetYear(DateTime time) {
+ public override int GetYear(DateTime time)
+ {
return (helper.GetYear(time));
}
@@ -145,7 +160,8 @@ namespace System.Globalization {
}
- public override bool IsLeapYear(int year, int era) {
+ public override bool IsLeapYear(int year, int era)
+ {
return (helper.IsLeapYear(year, era));
}
@@ -159,18 +175,22 @@ namespace System.Globalization {
}
- public override bool IsLeapMonth(int year, int month, int 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) {
+ 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 {
+ public override int[] Eras
+ {
+ get
+ {
return (helper.Eras);
}
}
@@ -182,15 +202,18 @@ namespace System.Globalization {
{
get
{
- if (twoDigitYearMax == -1) {
+ if (twoDigitYearMax == -1)
+ {
twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX);
}
return (twoDigitYearMax);
}
- set {
+ set
+ {
VerifyWritable();
- if (value < 99 || value > helper.MaxYear) {
+ if (value < 99 || value > helper.MaxYear)
+ {
throw new ArgumentOutOfRangeException(
"year",
String.Format(
@@ -198,15 +221,16 @@ namespace System.Globalization {
Environment.GetResourceString("ArgumentOutOfRange_Range"),
99,
helper.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"));
}
diff --git a/src/mscorlib/src/System/Globalization/TimeSpanFormat.cs b/src/mscorlib/src/System/Globalization/TimeSpanFormat.cs
index e5e615f1b3..8011c0b577 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,7 +59,7 @@ namespace System.Globalization {
pattern = Pattern.Minimum;
else
pattern = Pattern.Full;
-
+
return FormatStandard(value, false, format, pattern);
}
throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
@@ -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,31 +160,34 @@ 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)
@@ -207,16 +229,20 @@ namespace System.Globalization {
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;
@@ -232,7 +258,7 @@ namespace System.Globalization {
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;
}
@@ -263,7 +290,7 @@ namespace System.Globalization {
{
result.Append(((char)nextChar));
tokenLen = 2;
- }
+ }
else
{
//
@@ -278,40 +305,52 @@ namespace System.Globalization {
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..0be4f2f28d 100644
--- a/src/mscorlib/src/System/Globalization/TimeSpanParse.cs
+++ b/src/mscorlib/src/System/Globalization/TimeSpanParse.cs
@@ -50,16 +50,20 @@
// 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);
}
@@ -67,66 +71,74 @@ namespace System.Globalization {
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, Environment.GetResourceString(m_failureMessageID));
- case ParseFailureKind.FormatWithParameter:
- return new FormatException(Environment.GetResourceString(m_failureMessageID, m_failureMessageFormatArgument));
+ case ParseFailureKind.FormatWithParameter:
+ return new FormatException(Environment.GetResourceString(m_failureMessageID, m_failureMessageFormatArgument));
- case ParseFailureKind.Format:
- return new FormatException(Environment.GetResourceString(m_failureMessageID));
+ case ParseFailureKind.Format:
+ return new FormatException(Environment.GetResourceString(m_failureMessageID));
- case ParseFailureKind.Overflow:
- return new OverflowException(Environment.GetResourceString(m_failureMessageID));
+ case ParseFailureKind.Overflow:
+ return new OverflowException(Environment.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(Environment.GetResourceString("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
index 7ba5327324..68a47bcbe6 100644
--- a/src/mscorlib/src/System/Globalization/TimeSpanStyles.cs
+++ b/src/mscorlib/src/System/Globalization/TimeSpanStyles.cs
@@ -2,11 +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 {
-
+namespace System.Globalization
+{
[Flags]
- public enum TimeSpanStyles {
- None = 0x00000000,
- AssumeNegative = 0x00000001,
+ 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
index 06e7c7d75a..f53f629b20 100644
--- a/src/mscorlib/src/System/Globalization/UmAlQuraCalendar.cs
+++ b/src/mscorlib/src/System/Globalization/UmAlQuraCalendar.cs
@@ -2,34 +2,34 @@
// 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;
-
+using System;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+namespace System.Globalization
+{
////////////////////////////////////////////////////////////////////////////
//
// Notes about UmAlQuraCalendar
//
////////////////////////////////////////////////////////////////////////////
- /*
- ** Calendar support range:
- ** Calendar Minimum Maximum
- ** ========== ========== ==========
- ** Gregorian 1900/04/30 2077/11/17
- ** UmAlQura 1318/01/01 1500/12/30
- */
+ /*
+ ** 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 {
-
+ 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)
+ internal DateMapping(int MonthsLengthFlags, int GYear, int GMonth, int GDay)
{
HijriMonthsLengthFlags = MonthsLengthFlags;
GregorianDate = new DateTime(GYear, GMonth, GDay);
@@ -38,9 +38,9 @@ namespace System.Globalization {
internal DateTime GregorianDate;
}
- static readonly DateMapping [] HijriYearInfo = InitDateMapping();
+ private static readonly DateMapping[] HijriYearInfo = InitDateMapping();
- static DateMapping[] InitDateMapping()
+ private 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
@@ -239,7 +239,7 @@ namespace System.Globalization {
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]);
+ mapping[i] = new DateMapping(rawData[i * 4], rawData[i * 4 + 1], rawData[i * 4 + 2], rawData[i * 4 + 3]);
return mapping;
}
@@ -298,25 +298,32 @@ namespace System.Globalization {
//
- public override CalendarAlgorithmType AlgorithmType {
- get {
+ public override CalendarAlgorithmType AlgorithmType
+ {
+ get
+ {
return CalendarAlgorithmType.LunarCalendar;
}
}
// Construct an instance of UmAlQura calendar.
- public UmAlQuraCalendar() {
+ public UmAlQuraCalendar()
+ {
}
- internal override int BaseCalendarID {
- get {
+ internal override int BaseCalendarID
+ {
+ get
+ {
return (CAL_HIJRI);
}
}
- internal override int ID {
- get {
+ internal override int ID
+ {
+ get
+ {
return (CAL_UMALQURA);
}
}
@@ -337,14 +344,14 @@ namespace System.Globalization {
** 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)
+ private 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;
+ 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;
@@ -352,7 +359,7 @@ namespace System.Globalization {
b = HijriYearInfo[index].HijriMonthsLengthFlags;
- for(int m = 1; m < HijriMonth; m++)
+ for (int m = 1; m < HijriMonth; m++)
{
nDays += 29 + (b & 0x1);
b = b >> 1;
@@ -371,16 +378,19 @@ namespace System.Globalization {
**Arguments:
**Exceptions:
============================================================================*/
- static long GetAbsoluteDateUmAlQura(int year, int month, int day) {
+ private 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;
+ int yg = 0, mg = 0, dg = 0;
ConvertHijriToGregorian(year, month, day, ref yg, ref mg, ref dg);
- return GregorianCalendar.GetAbsoluteDate(yg,mg,dg);
+ return GregorianCalendar.GetAbsoluteDate(yg, mg, dg);
}
- static internal void CheckTicksRange(long ticks) {
- if (ticks < minDate.Ticks || ticks > maxDate.Ticks) {
+ static internal void CheckTicksRange(long ticks)
+ {
+ if (ticks < minDate.Ticks || ticks > maxDate.Ticks)
+ {
throw new ArgumentOutOfRangeException(
"time",
String.Format(
@@ -391,15 +401,19 @@ namespace System.Globalization {
}
}
- static internal void CheckEraRange(int era) {
- if (era != CurrentEra && era != UmAlQuraEra) {
+ 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) {
+ static internal void CheckYearRange(int year, int era)
+ {
CheckEraRange(era);
- if (year < MinCalendarYear || year > MaxCalendarYear) {
+ if (year < MinCalendarYear || year > MaxCalendarYear)
+ {
throw new ArgumentOutOfRangeException(
nameof(year),
String.Format(
@@ -410,9 +424,11 @@ namespace System.Globalization {
}
}
- static internal void CheckYearMonthRange(int year, int month, int era) {
+ static internal void CheckYearMonthRange(int year, int month, int era)
+ {
CheckYearRange(year, era);
- if (month < 1 || month > 12) {
+ if (month < 1 || month > 12)
+ {
throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Month"));
}
}
@@ -423,23 +439,22 @@ namespace System.Globalization {
** 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)
+ private 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;
+ 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
+ do
{
- } while (time.CompareTo(HijriYearInfo[++index].GregorianDate)>0); //while greater
+ } while (time.CompareTo(HijriYearInfo[++index].GregorianDate) > 0); //while greater
if (time.CompareTo(HijriYearInfo[index].GregorianDate) != 0)
{
@@ -448,18 +463,18 @@ namespace System.Globalization {
ts = time.Subtract(HijriYearInfo[index].GregorianDate);
yh1 = index + MinCalendarYear;
-
+
mh1 = 1;
dh1 = 1;
nDays = ts.TotalDays;
b = HijriYearInfo[index].HijriMonthsLengthFlags;
- DaysPerThisMonth = 29 + (b&1);
+ DaysPerThisMonth = 29 + (b & 1);
while (nDays >= DaysPerThisMonth)
{
nDays -= DaysPerThisMonth;
b = b >> 1;
- DaysPerThisMonth = 29 + (b&1);
+ DaysPerThisMonth = 29 + (b & 1);
mh1++;
}
dh1 += (int)nDays;
@@ -482,10 +497,11 @@ namespace System.Globalization {
** 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
+ 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);
@@ -526,8 +542,10 @@ namespace System.Globalization {
//
- public override DateTime AddMonths(DateTime time, int months) {
- if (months < -120000 || months > 120000) {
+ public override DateTime AddMonths(DateTime time, int months)
+ {
+ if (months < -120000 || months > 120000)
+ {
throw new ArgumentOutOfRangeException(
nameof(months),
String.Format(
@@ -543,22 +561,26 @@ namespace System.Globalization {
int d = GetDatePart(time, 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;
}
- if (d>29)
+ if (d > 29)
{
int days = GetDaysInMonth(y, m);
- if (d > days) {
+ if (d > days)
+ {
d = days;
}
}
- CheckYearRange(y, UmAlQuraEra);
+ CheckYearRange(y, UmAlQuraEra);
DateTime dt = new DateTime(GetAbsoluteDateUmAlQura(y, m, d) * TicksPerDay + time.Ticks % TicksPerDay);
Calendar.CheckAddResult(dt.Ticks, MinSupportedDateTime, MaxSupportedDateTime);
return (dt);
@@ -574,7 +596,8 @@ namespace System.Globalization {
//
- public override DateTime AddYears(DateTime time, int years) {
+ public override DateTime AddYears(DateTime time, int years)
+ {
return (AddMonths(time, years * 12));
}
@@ -583,7 +606,8 @@ namespace System.Globalization {
//
- public override int GetDayOfMonth(DateTime time) {
+ public override int GetDayOfMonth(DateTime time)
+ {
return (GetDatePart(time, DatePartDay));
}
@@ -594,7 +618,8 @@ namespace System.Globalization {
//
- public override DayOfWeek GetDayOfWeek(DateTime time) {
+ public override DayOfWeek GetDayOfWeek(DateTime time)
+ {
return ((DayOfWeek)((int)(time.Ticks / TicksPerDay + 1) % 7));
}
@@ -603,7 +628,8 @@ namespace System.Globalization {
//
- public override int GetDayOfYear(DateTime time) {
+ public override int GetDayOfYear(DateTime time)
+ {
return (GetDatePart(time, DatePartDayOfYear));
}
@@ -613,16 +639,17 @@ namespace System.Globalization {
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) {
+ public override int GetDaysInMonth(int year, int month, int era)
+ {
CheckYearMonthRange(year, month, era);
- if ((HijriYearInfo[year-MinCalendarYear].HijriMonthsLengthFlags & (1<<month-1))==0)
+ if ((HijriYearInfo[year - MinCalendarYear].HijriMonthsLengthFlags & (1 << month - 1)) == 0)
return 29;
else
return 30;
@@ -632,16 +659,16 @@ namespace System.Globalization {
{
int days = 0, b;
- Debug.Assert( (year >= MinCalendarYear) && (year <= MaxCalendarYear), "Hijri year is out of range.");
+ Debug.Assert((year >= MinCalendarYear) && (year <= MaxCalendarYear), "Hijri year is out of range.");
- b = HijriYearInfo[year-MinCalendarYear].HijriMonthsLengthFlags;
+ b = HijriYearInfo[year - MinCalendarYear].HijriMonthsLengthFlags;
- for(int m = 1; m <= 12; m++)
+ 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.");
+ Debug.Assert((days == 354) || (days == 355), "Hijri year has to be 354 or 355 days.");
return days;
}
@@ -658,16 +685,19 @@ namespace System.Globalization {
// Returns the era for the specified DateTime value.
- public override int GetEra(DateTime time) {
+ public override int GetEra(DateTime time)
+ {
CheckTicksRange(time.Ticks);
return (UmAlQuraEra);
}
- public override int[] Eras {
- get {
- return (new int[] {UmAlQuraEra});
+ public override int[] Eras
+ {
+ get
+ {
+ return (new int[] { UmAlQuraEra });
}
}
@@ -676,14 +706,16 @@ namespace System.Globalization {
//
- public override int GetMonth(DateTime time) {
+ 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) {
+ public override int GetMonthsInYear(int year, int era)
+ {
CheckYearRange(year, era);
return (12);
}
@@ -693,7 +725,8 @@ namespace System.Globalization {
//
- public override int GetYear(DateTime time) {
+ public override int GetYear(DateTime time)
+ {
return (GetDatePart(time, DatePartYear));
}
@@ -702,8 +735,9 @@ namespace System.Globalization {
//
- public override bool IsLeapDay(int year, int month, int day, int era) {
- if (day>=1 && day <=29)
+ public override bool IsLeapDay(int year, int month, int day, int era)
+ {
+ if (day >= 1 && day <= 29)
{
CheckYearMonthRange(year, month, era);
return (false);
@@ -711,7 +745,8 @@ namespace System.Globalization {
// The year/month/era value checking is done in GetDaysInMonth().
int daysInMonth = GetDaysInMonth(year, month, era);
- if (day < 1 || day > daysInMonth) {
+ if (day < 1 || day > daysInMonth)
+ {
throw new ArgumentOutOfRangeException(
nameof(day),
String.Format(
@@ -739,7 +774,8 @@ namespace System.Globalization {
//
- public override bool IsLeapMonth(int year, int month, int era) {
+ public override bool IsLeapMonth(int year, int month, int era)
+ {
CheckYearMonthRange(year, month, era);
return (false);
}
@@ -762,7 +798,8 @@ namespace System.Globalization {
//
- public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) {
+ 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);
@@ -770,24 +807,28 @@ namespace System.Globalization {
}
// The year/month/era value checking is done in GetDaysInMonth().
- int daysInMonth = GetDaysInMonth(year, month, era);
+ 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:
+ 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) {
+ if (lDate >= 0)
+ {
return (new DateTime(lDate * GregorianCalendar.TicksPerDay + TimeToTicks(hour, minute, second, millisecond)));
- } else {
+ }
+ else
+ {
throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("ArgumentOutOfRange_BadYearMonthDay"));
}
}
@@ -796,16 +837,21 @@ DayInRang:
- public override int TwoDigitYearMax {
- get {
- if (twoDigitYearMax == -1) {
+ 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)) {
+ set
+ {
+ if (value != 99 && (value < MinCalendarYear || value > MaxCalendarYear))
+ {
throw new ArgumentOutOfRangeException(
nameof(value),
String.Format(
@@ -823,18 +869,22 @@ DayInRang:
- 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"));
}
Contract.EndContractBlock();
- if (year < 100) {
+ if (year < 100)
+ {
return (base.ToFourDigitYear(year));
}
- if ((year < MinCalendarYear) || (year > MaxCalendarYear)) {
+ if ((year < MinCalendarYear) || (year > MaxCalendarYear))
+ {
throw new ArgumentOutOfRangeException(
nameof(year),
String.Format(
diff --git a/src/mscorlib/src/System/Globalization/UnicodeCategory.cs b/src/mscorlib/src/System/Globalization/UnicodeCategory.cs
index c9898f135b..008f219b61 100644
--- a/src/mscorlib/src/System/Globalization/UnicodeCategory.cs
+++ b/src/mscorlib/src/System/Globalization/UnicodeCategory.cs
@@ -10,11 +10,12 @@
**
**
============================================================*/
-namespace System.Globalization {
+namespace System.Globalization
+{
[Serializable]
- public enum UnicodeCategory {
-
+ public enum UnicodeCategory
+ {
UppercaseLetter = 0,
LowercaseLetter = 1,
diff --git a/src/mscorlib/src/System/Guid.cs b/src/mscorlib/src/System/Guid.cs
index 1116faf027..0d4024b212 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,7 +47,7 @@ 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));
@@ -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)
+ if (d.Length != 8)
throw new ArgumentException(Environment.GetResourceString("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, Environment.GetResourceString(m_failureMessageID));
- case ParseFailureKind.FormatWithInnerException:
- return new FormatException(Environment.GetResourceString(m_failureMessageID), m_innerException);
+ case ParseFailureKind.FormatWithInnerException:
+ return new FormatException(Environment.GetResourceString(m_failureMessageID), m_innerException);
- case ParseFailureKind.FormatWithParameter:
- return new FormatException(Environment.GetResourceString(m_failureMessageID, m_failureMessageFormatArgument));
+ case ParseFailureKind.FormatWithParameter:
+ return new FormatException(Environment.GetResourceString(m_failureMessageID, m_failureMessageFormatArgument));
- case ParseFailureKind.Format:
- return new FormatException(Environment.GetResourceString(m_failureMessageID));
+ case ParseFailureKind.Format:
+ return new FormatException(Environment.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(Environment.GetResourceString("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"));
}
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
+ {
throw new FormatException(Environment.GetResourceString("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) {
+ else if (parseResult.throwStyle == GuidParseThrowStyle.AllButOverflow)
+ {
throw new FormatException(Environment.GetResourceString("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) {
+ else if (parseResult.throwStyle == GuidParseThrowStyle.AllButOverflow)
+ {
throw new FormatException(Environment.GetResourceString("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)) {
+ if (!(value is Guid))
+ {
throw new ArgumentException(Environment.GetResourceString("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,14 +1280,15 @@ namespace System {
return guid;
}
- public String ToString(String format) {
+ public String ToString(String format)
+ {
return ToString(format, null);
}
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)
@@ -1153,18 +1298,20 @@ namespace System {
unsafe private static int HexsToChars(char* guidChars, int offset, int a, int b, bool hex)
{
- if (hex) {
+ if (hex)
+ {
guidChars[offset++] = '0';
guidChars[offset++] = 'x';
}
- guidChars[offset++] = HexToChar(a>>4);
+ guidChars[offset++] = HexToChar(a >> 4);
guidChars[offset++] = HexToChar(a);
- if (hex) {
+ if (hex)
+ {
guidChars[offset++] = ',';
guidChars[offset++] = '0';
guidChars[offset++] = 'x';
}
- guidChars[offset++] = HexToChar(b>>4);
+ guidChars[offset++] = HexToChar(b >> 4);
guidChars[offset++] = HexToChar(b);
return offset;
}
@@ -1181,41 +1328,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"));
}
-
+
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,13 +1382,17 @@ namespace System {
dash = false;
hex = true;
}
- else {
+ else
+ {
throw new FormatException(Environment.GetResourceString("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';
@@ -1254,7 +1417,8 @@ namespace System {
offset = HexsToChars(guidChars, offset, _j, _k, true);
guidChars[offset++] = '}';
}
- else {
+ else
+ {
// [{|(]dddddddd[-]dddd[-]dddd[-]dddd[-]dddddddddddd[}|)]
offset = HexsToChars(guidChars, offset, _a >> 24, _a >> 16);
offset = HexsToChars(guidChars, offset, _a >> 8, _a);
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/ICloneable.cs b/src/mscorlib/src/System/ICloneable.cs
index 49657c2765..d50ba3beee 100644
--- a/src/mscorlib/src/System/ICloneable.cs
+++ b/src/mscorlib/src/System/ICloneable.cs
@@ -8,9 +8,11 @@
** This interface is implemented by classes that support cloning.
**
===========================================================*/
-namespace System {
-
- using System;
+
+using System;
+
+namespace 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
diff --git a/src/mscorlib/src/System/IO/BinaryReader.cs b/src/mscorlib/src/System/IO/BinaryReader.cs
index d973860472..2f81b0072c 100644
--- a/src/mscorlib/src/System/IO/BinaryReader.cs
+++ b/src/mscorlib/src/System/IO/BinaryReader.cs
@@ -13,44 +13,50 @@
**
**
============================================================*/
-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)
@@ -60,7 +66,7 @@ namespace System.IO {
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);
}
}
- 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) {
+ if (stringLength < 0)
+ {
throw new IOException(Environment.GetResourceString("IO.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) {
+ public virtual int Read(char[] buffer, int index, int count)
+ {
+ if (buffer == null)
+ {
throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
}
- if (index < 0) {
+ if (index < 0)
+ {
throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
- if (count < 0) {
+ if (count < 0)
+ {
throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
- if (buffer.Length - index < count) {
+ if (buffer.Length - index < count)
+ {
throw new ArgumentException(Environment.GetResourceString("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,35 +520,41 @@ namespace System.IO {
return m_singleChar[0];
}
- public virtual char[] ReadChars(int count) {
- if (count<0) {
+ public virtual char[] ReadChars(int count)
+ {
+ if (count < 0)
+ {
throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("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) {
+ if (count == 0)
+ {
return EmptyArray<Char>.Value;
}
// 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)
+ public virtual int Read(byte[] buffer, int index, int count)
+ {
+ if (buffer == null)
throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
@@ -508,25 +566,28 @@ namespace System.IO {
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) {
+ public virtual byte[] ReadBytes(int count)
+ {
if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("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) {
+ if (count == 0)
+ {
return EmptyArray<Byte>.Value;
}
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,42 +606,49 @@ namespace System.IO {
return result;
}
- protected virtual void FillBuffer(int numBytes) {
- if (m_buffer != null && (numBytes < 0 || numBytes > m_buffer.Length)) {
+ 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"));
}
- 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
diff --git a/src/mscorlib/src/System/IO/BinaryWriter.cs b/src/mscorlib/src/System/IO/BinaryWriter.cs
index b6c562534c..ffa5f6edaf 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"));
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"));
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..c8c0142363 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
@@ -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));
}
@@ -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)
+ if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_PathEmpty"));
if (path.Length >= Path.MaxPath)
throw new PathTooLongException(Environment.GetResourceString("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
index 21211a61e7..31b1eba6d5 100644
--- a/src/mscorlib/src/System/IO/DirectoryNotFoundException.cs
+++ b/src/mscorlib/src/System/IO/DirectoryNotFoundException.cs
@@ -12,10 +12,12 @@
**
**
===========================================================*/
+
using System;
using System.Runtime.Serialization;
-namespace System.IO {
+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:
@@ -23,23 +25,28 @@ namespace System.IO {
* and STG_E_PATHNOTFOUND (0x80030003).
*/
[Serializable]
- public class DirectoryNotFoundException : IOException {
- public DirectoryNotFoundException()
- : base(Environment.GetResourceString("Arg_DirectoryNotFoundException")) {
+ public class DirectoryNotFoundException : IOException
+ {
+ public DirectoryNotFoundException()
+ : base(Environment.GetResourceString("Arg_DirectoryNotFoundException"))
+ {
SetErrorCode(__HResults.COR_E_DIRECTORYNOTFOUND);
}
-
- public DirectoryNotFoundException(String message)
- : base(message) {
+
+ public DirectoryNotFoundException(String message)
+ : base(message)
+ {
SetErrorCode(__HResults.COR_E_DIRECTORYNOTFOUND);
}
-
- public DirectoryNotFoundException(String message, Exception innerException)
- : base(message, innerException) {
+
+ public DirectoryNotFoundException(String message, Exception innerException)
+ : base(message, innerException)
+ {
SetErrorCode(__HResults.COR_E_DIRECTORYNOTFOUND);
}
-
- protected DirectoryNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) {
+
+ 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..6c5bb765b2 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")) {
+ internal class DriveNotFoundException : IOException
+ {
+ public DriveNotFoundException()
+ : base(Environment.GetResourceString("Arg_DriveNotFoundException"))
+ {
SetErrorCode(__HResults.COR_E_DIRECTORYNOTFOUND);
}
-
- public DriveNotFoundException(String message)
- : base(message) {
+
+ public DriveNotFoundException(String message)
+ : base(message)
+ {
SetErrorCode(__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
index 558c792a9e..3b73dff7fb 100644
--- a/src/mscorlib/src/System/IO/EndOfStreamException.cs
+++ b/src/mscorlib/src/System/IO/EndOfStreamException.cs
@@ -16,27 +16,31 @@
using System;
using System.Runtime.Serialization;
-namespace System.IO {
+namespace System.IO
+{
[Serializable]
public class EndOfStreamException : IOException
{
- public EndOfStreamException()
- : base(Environment.GetResourceString("Arg_EndOfStreamException")) {
+ public EndOfStreamException()
+ : base(Environment.GetResourceString("Arg_EndOfStreamException"))
+ {
SetErrorCode(__HResults.COR_E_ENDOFSTREAM);
}
-
- public EndOfStreamException(String message)
- : base(message) {
+
+ public EndOfStreamException(String message)
+ : base(message)
+ {
SetErrorCode(__HResults.COR_E_ENDOFSTREAM);
}
-
- public EndOfStreamException(String message, Exception innerException)
- : base(message, innerException) {
+
+ public EndOfStreamException(String message, Exception innerException)
+ : base(message, innerException)
+ {
SetErrorCode(__HResults.COR_E_ENDOFSTREAM);
}
- protected EndOfStreamException(SerializationInfo info, StreamingContext context) : base (info, context) {
+ 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..5c6b5fcf01 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;
+ 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();
@@ -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
index 707b58f78b..ad6117ebd3 100644
--- a/src/mscorlib/src/System/IO/FileAccess.cs
+++ b/src/mscorlib/src/System/IO/FileAccess.cs
@@ -17,22 +17,23 @@
using System;
-namespace System.IO {
+namespace System.IO
+{
// Contains constants for specifying the access you want for a file.
// You can have Read, Write or ReadWrite access.
//
-[Serializable]
-[Flags]
+ [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.
diff --git a/src/mscorlib/src/System/IO/FileLoadException.cs b/src/mscorlib/src/System/IO/FileLoadException.cs
index 980d2514aa..e55fdbb118 100644
--- a/src/mscorlib/src/System/IO/FileLoadException.cs
+++ b/src/mscorlib/src/System/IO/FileLoadException.cs
@@ -23,26 +23,29 @@ using System.Security;
using System.Runtime.Versioning;
using SecurityException = System.Security.SecurityException;
-namespace System.IO {
-
+namespace System.IO
+{
[Serializable]
- public class FileLoadException : IOException {
-
+ 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")) {
+ public FileLoadException()
+ : base(Environment.GetResourceString("IO.FileLoad"))
+ {
SetErrorCode(__HResults.COR_E_FILELOAD);
}
-
- public FileLoadException(String message)
- : base(message) {
+
+ public FileLoadException(String message)
+ : base(message)
+ {
SetErrorCode(__HResults.COR_E_FILELOAD);
}
-
- public FileLoadException(String message, Exception inner)
- : base(message, inner) {
+
+ public FileLoadException(String message, Exception inner)
+ : base(message, inner)
+ {
SetErrorCode(__HResults.COR_E_FILELOAD);
}
@@ -52,15 +55,17 @@ namespace System.IO {
_fileName = fileName;
}
- public FileLoadException(String message, String fileName, Exception inner)
- : base(message, inner) {
+ public FileLoadException(String message, String fileName, Exception inner)
+ : base(message, inner)
+ {
SetErrorCode(__HResults.COR_E_FILELOAD);
_fileName = fileName;
}
public override String Message
{
- get {
+ get
+ {
SetMessageField();
return _message;
}
@@ -72,7 +77,8 @@ namespace System.IO {
_message = FormatFileLoadExceptionMessage(_fileName, HResult);
}
- public String FileName {
+ public String FileName
+ {
get { return _fileName; }
}
@@ -82,7 +88,7 @@ namespace System.IO {
if (_fileName != null && _fileName.Length != 0)
s += Environment.NewLine + Environment.GetResourceString("IO.FileName_Name", _fileName);
-
+
if (InnerException != null)
s = s + " ---> " + InnerException.ToString();
@@ -91,24 +97,24 @@ namespace System.IO {
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 FileLoadException(SerializationInfo info, StreamingContext context) : base (info, context) {
+ protected FileLoadException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
// Base class constructor will check info != null.
_fileName = info.GetString("FileLoad_FileName");
@@ -117,26 +123,28 @@ namespace System.IO {
{
_fusionLog = info.GetString("FileLoad_FusionLog");
}
- catch
+ catch
{
_fusionLog = null;
}
}
- private FileLoadException(String fileName, String fusionLog,int hResult)
+ private FileLoadException(String fileName, String fusionLog, int hResult)
: base(null)
{
SetErrorCode(hResult);
_fileName = fileName;
- _fusionLog=fusionLog;
+ _fusionLog = fusionLog;
SetMessageField();
}
- public String FusionLog {
+ public String FusionLog
+ {
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/IO/FileMode.cs b/src/mscorlib/src/System/IO/FileMode.cs
index 3972cf0533..6f222e7a60 100644
--- a/src/mscorlib/src/System/IO/FileMode.cs
+++ b/src/mscorlib/src/System/IO/FileMode.cs
@@ -14,10 +14,11 @@
**
**
===========================================================*/
-
+
using System;
-namespace System.IO {
+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.
@@ -31,21 +32,21 @@ namespace System.IO {
{
// 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.cs b/src/mscorlib/src/System/IO/FileNotFoundException.cs
index ad6b5386ba..e25667e302 100644
--- a/src/mscorlib/src/System/IO/FileNotFoundException.cs
+++ b/src/mscorlib/src/System/IO/FileNotFoundException.cs
@@ -19,26 +19,30 @@ using System.Runtime.Serialization;
using SecurityException = System.Security.SecurityException;
using System.Globalization;
-namespace System.IO {
+namespace System.IO
+{
// Thrown when trying to access a file that doesn't exist on disk.
[Serializable]
- public class FileNotFoundException : IOException {
-
+ 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")) {
+
+ public FileNotFoundException()
+ : base(Environment.GetResourceString("IO.FileNotFound"))
+ {
SetErrorCode(__HResults.COR_E_FILENOTFOUND);
}
-
- public FileNotFoundException(String message)
- : base(message) {
+
+ public FileNotFoundException(String message)
+ : base(message)
+ {
SetErrorCode(__HResults.COR_E_FILENOTFOUND);
}
-
- public FileNotFoundException(String message, Exception innerException)
- : base(message, innerException) {
+
+ public FileNotFoundException(String message, Exception innerException)
+ : base(message, innerException)
+ {
SetErrorCode(__HResults.COR_E_FILENOTFOUND);
}
@@ -48,15 +52,17 @@ namespace System.IO {
_fileName = fileName;
}
- public FileNotFoundException(String message, String fileName, Exception innerException)
- : base(message, innerException) {
+ public FileNotFoundException(String message, String fileName, Exception innerException)
+ : base(message, innerException)
+ {
SetErrorCode(__HResults.COR_E_FILENOTFOUND);
_fileName = fileName;
}
public override String Message
{
- get {
+ get
+ {
SetMessageField();
return _message;
}
@@ -64,17 +70,19 @@ namespace System.IO {
private void SetMessageField()
{
- if (_message == null) {
+ if (_message == null)
+ {
if ((_fileName == null) &&
(HResult == System.__HResults.COR_E_EXCEPTION))
_message = Environment.GetResourceString("IO.FileNotFound");
- else if( _fileName != null)
+ else if (_fileName != null)
_message = FileLoadException.FormatFileLoadExceptionMessage(_fileName, HResult);
}
}
- public String FileName {
+ public String FileName
+ {
get { return _fileName; }
}
@@ -84,7 +92,7 @@ namespace System.IO {
if (_fileName != null && _fileName.Length != 0)
s += Environment.NewLine + Environment.GetResourceString("IO.FileName_Name", _fileName);
-
+
if (InnerException != null)
s = s + " ---> " + InnerException.ToString();
@@ -93,24 +101,23 @@ namespace System.IO {
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 FileNotFoundException(SerializationInfo info, StreamingContext context) : base (info, context) {
+ protected FileNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
// Base class constructor will check info != null.
_fileName = info.GetString("FileNotFound_FileName");
@@ -118,26 +125,28 @@ namespace System.IO {
{
_fusionLog = info.GetString("FileNotFound_FusionLog");
}
- catch
+ catch
{
_fusionLog = null;
}
}
- private FileNotFoundException(String fileName, String fusionLog,int hResult)
+ private FileNotFoundException(String fileName, String fusionLog, int hResult)
: base(null)
{
SetErrorCode(hResult);
_fileName = fileName;
- _fusionLog=fusionLog;
+ _fusionLog = fusionLog;
SetMessageField();
}
- public String FusionLog {
+ public String FusionLog
+ {
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/IO/FileOptions.cs b/src/mscorlib/src/System/IO/FileOptions.cs
index 02bc99eea4..c01d70510f 100644
--- a/src/mscorlib/src/System/IO/FileOptions.cs
+++ b/src/mscorlib/src/System/IO/FileOptions.cs
@@ -18,7 +18,8 @@
using System;
using System.Runtime.InteropServices;
-namespace System.IO {
+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.
diff --git a/src/mscorlib/src/System/IO/FileShare.cs b/src/mscorlib/src/System/IO/FileShare.cs
index 8a7d1f05e9..812a0013bb 100644
--- a/src/mscorlib/src/System/IO/FileShare.cs
+++ b/src/mscorlib/src/System/IO/FileShare.cs
@@ -18,7 +18,8 @@
using System;
-namespace System.IO {
+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.
@@ -26,24 +27,24 @@ namespace System.IO {
// Note these values currently match the values for FILE_SHARE_READ,
// FILE_SHARE_WRITE, and FILE_SHARE_DELETE in winnt.h
//
-[Serializable]
-[Flags]
+ [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.
diff --git a/src/mscorlib/src/System/IO/IOException.cs b/src/mscorlib/src/System/IO/IOException.cs
index ab612811b0..c2603e6fab 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")) {
+ public IOException()
+ : base(Environment.GetResourceString("Arg_IOException"))
+ {
SetErrorCode(__HResults.COR_E_IO);
}
-
- public IOException(String message)
- : base(message) {
+
+ public IOException(String message)
+ : base(message)
+ {
SetErrorCode(__HResults.COR_E_IO);
}
- public IOException(String message, int hresult)
- : base(message) {
+ public IOException(String message, int hresult)
+ : base(message)
+ {
SetErrorCode(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) {
+ internal IOException(String message, int hresult, String maybeFullPath)
+ : base(message)
+ {
SetErrorCode(hresult);
_maybeFullPath = maybeFullPath;
}
-
- public IOException(String message, Exception innerException)
- : base(message, innerException) {
+
+ public IOException(String message, Exception innerException)
+ : base(message, innerException)
+ {
SetErrorCode(__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..920157723e 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,12 +55,15 @@ namespace System.IO {
private const int MemStreamMaxLength = Int32.MaxValue;
- public MemoryStream()
- : this(0) {
+ public MemoryStream()
+ : this(0)
+ {
}
-
- public MemoryStream(int capacity) {
- if (capacity < 0) {
+
+ public MemoryStream(int capacity)
+ {
+ if (capacity < 0)
+ {
throw new ArgumentOutOfRangeException(nameof(capacity), Environment.GetResourceString("ArgumentOutOfRange_NegativeCapacity"));
}
Contract.EndContractBlock();
@@ -72,12 +76,14 @@ 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) {
+
+ public MemoryStream(byte[] buffer, bool writable)
+ {
if (buffer == null) throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
Contract.EndContractBlock();
_buffer = buffer;
@@ -87,17 +93,20 @@ 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)
+
+ public MemoryStream(byte[] buffer, int index, int count, bool writable, bool publiclyVisible)
+ {
+ if (buffer == null)
throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
@@ -106,7 +115,7 @@ namespace System.IO {
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("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) {
+ 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"));
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,17 +286,20 @@ 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"));
@@ -281,33 +310,41 @@ 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"));
Contract.Ensures(Position == value);
@@ -321,8 +358,9 @@ namespace System.IO {
}
}
- public override int Read([In, Out] byte[] buffer, int offset, int count) {
- if (buffer==null)
+ public override int Read([In, Out] byte[] buffer, int offset, int count)
+ {
+ if (buffer == null)
throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
@@ -356,7 +394,7 @@ namespace System.IO {
public override Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
- if (buffer==null)
+ if (buffer == null)
throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
@@ -367,14 +405,14 @@ namespace System.IO {
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"));
+ 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"));
}
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,8 +558,10 @@ 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) {
+ public override void SetLength(long value)
+ {
+ if (value < 0 || value > Int32.MaxValue)
+ {
throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_StreamLength"));
}
Contract.Ensures(_length - _origin == value);
@@ -523,7 +570,8 @@ 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)) {
+ if (value > (Int32.MaxValue - _origin))
+ {
throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_StreamLength"));
}
@@ -533,18 +581,19 @@ 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)
+
+ public override void Write(byte[] buffer, int offset, int count)
+ {
+ if (buffer == null)
throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
@@ -562,9 +611,11 @@ namespace System.IO {
if (i < 0)
throw new IOException(Environment.GetResourceString("IO.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,7 +633,6 @@ 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)
@@ -598,7 +648,7 @@ namespace System.IO {
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,12 +686,12 @@ namespace System.IO {
_length = newLength;
}
_buffer[_position++] = value;
-
}
-
+
// Writes this MemoryStream to another stream.
- public virtual void WriteTo(Stream stream) {
- if (stream==null)
+ public virtual void WriteTo(Stream stream)
+ {
+ if (stream == null)
throw new ArgumentNullException(nameof(stream), Environment.GetResourceString("ArgumentNull_Stream"));
Contract.EndContractBlock();
diff --git a/src/mscorlib/src/System/IO/PathTooLongException.cs b/src/mscorlib/src/System/IO/PathTooLongException.cs
index a84fdfbb36..07ecb38db4 100644
--- a/src/mscorlib/src/System/IO/PathTooLongException.cs
+++ b/src/mscorlib/src/System/IO/PathTooLongException.cs
@@ -17,27 +17,31 @@
using System;
using System.Runtime.Serialization;
-namespace System.IO {
-
+namespace System.IO
+{
[Serializable]
public class PathTooLongException : IOException
{
- public PathTooLongException()
- : base(Environment.GetResourceString("IO.PathTooLong")) {
+ public PathTooLongException()
+ : base(Environment.GetResourceString("IO.PathTooLong"))
+ {
SetErrorCode(__HResults.COR_E_PATHTOOLONG);
}
-
- public PathTooLongException(String message)
- : base(message) {
+
+ public PathTooLongException(String message)
+ : base(message)
+ {
SetErrorCode(__HResults.COR_E_PATHTOOLONG);
}
-
- public PathTooLongException(String message, Exception innerException)
- : base(message, innerException) {
+
+ public PathTooLongException(String message, Exception innerException)
+ : base(message, innerException)
+ {
SetErrorCode(__HResults.COR_E_PATHTOOLONG);
}
- protected PathTooLongException(SerializationInfo info, StreamingContext context) : base (info, context) {
+ 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..6f3139f17f 100644
--- a/src/mscorlib/src/System/IO/SearchOption.cs
+++ b/src/mscorlib/src/System/IO/SearchOption.cs
@@ -18,7 +18,8 @@
using System;
-namespace System.IO {
+namespace System.IO
+{
[Serializable]
public enum SearchOption
{
diff --git a/src/mscorlib/src/System/IO/SeekOrigin.cs b/src/mscorlib/src/System/IO/SeekOrigin.cs
index bff49e610f..efb319a2e2 100644
--- a/src/mscorlib/src/System/IO/SeekOrigin.cs
+++ b/src/mscorlib/src/System/IO/SeekOrigin.cs
@@ -17,7 +17,8 @@
using System;
-namespace System.IO {
+namespace System.IO
+{
// Provides seek reference points. To seek to the end of a stream,
// call stream.Seek(0, SeekOrigin.End).
[Serializable]
diff --git a/src/mscorlib/src/System/IO/Stream.cs b/src/mscorlib/src/System/IO/Stream.cs
index 790f0a09ab..585f5999a3 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,54 +54,67 @@ 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"));
}
- set {
+ set
+ {
throw new InvalidOperationException(Environment.GetResourceString("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"));
}
- set {
+ set
+ {
throw new InvalidOperationException(Environment.GetResourceString("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
}
@@ -377,8 +392,8 @@ namespace System.IO {
{
throw new ArgumentException(Environment.GetResourceString("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,14 +552,14 @@ 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();
@@ -561,7 +577,7 @@ namespace System.IO {
throw new ArgumentException(Environment.GetResourceString("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/UnmanagedMemoryAccessor.cs b/src/mscorlib/src/System/IO/UnmanagedMemoryAccessor.cs
index f3fd71833c..347aea8d26 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) {
+ if (offset < 0)
+ {
throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
- if (capacity < 0) {
+ if (capacity < 0)
+ {
throw new ArgumentOutOfRangeException(nameof(capacity), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
- if (buffer.ByteLength < (UInt64)(offset + capacity)) {
+ if (buffer.ByteLength < (UInt64)(offset + capacity))
+ {
throw new ArgumentException(Environment.GetResourceString("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) {
+ if (_isOpen)
+ {
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CalledTwice"));
}
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
buffer.AcquirePointer(ref pointer);
- if (((byte*)((Int64)pointer + offset + capacity)) < pointer) {
+ if (((byte*)((Int64)pointer + offset + capacity)) < pointer)
+ {
throw new ArgumentException(Environment.GetResourceString("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,31 +167,35 @@ 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) {
+ public char ReadChar(Int64 position)
+ {
int sizeOfType = sizeof(char);
EnsureSafeToRead(position, sizeOfType);
-
+
char 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 = *((char*)(pointer));
+ result = *((char*)(pointer));
#if ALIGN_ACCESS
}
else {
@@ -173,8 +203,10 @@ namespace System.IO {
}
#endif
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -184,16 +216,19 @@ namespace System.IO {
}
// See comment above.
- public Int16 ReadInt16(Int64 position) {
+ public Int16 ReadInt16(Int64 position)
+ {
int sizeOfType = sizeof(Int16);
EnsureSafeToRead(position, sizeOfType);
Int16 result;
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
pointer += (_offset + position);
@@ -201,7 +236,7 @@ namespace System.IO {
// check if pointer is aligned
if (((int)pointer & (sizeOfType - 1)) == 0) {
#endif
- result = *((Int16*)(pointer));
+ result = *((Int16*)(pointer));
#if ALIGN_ACCESS
}
else {
@@ -209,8 +244,10 @@ namespace System.IO {
}
#endif
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -220,15 +257,18 @@ namespace System.IO {
}
- public Int32 ReadInt32(Int64 position) {
+ public Int32 ReadInt32(Int64 position)
+ {
int sizeOfType = sizeof(Int32);
EnsureSafeToRead(position, sizeOfType);
Int32 result;
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
pointer += (_offset + position);
@@ -236,7 +276,7 @@ namespace System.IO {
// check if pointer is aligned
if (((int)pointer & (sizeOfType - 1)) == 0) {
#endif
- result = *((Int32*)(pointer));
+ result = *((Int32*)(pointer));
#if ALIGN_ACCESS
}
else {
@@ -244,8 +284,10 @@ namespace System.IO {
}
#endif
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -254,15 +296,18 @@ namespace System.IO {
return result;
}
- public Int64 ReadInt64(Int64 position) {
+ public Int64 ReadInt64(Int64 position)
+ {
int sizeOfType = sizeof(Int64);
EnsureSafeToRead(position, sizeOfType);
Int64 result;
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
pointer += (_offset + position);
@@ -270,7 +315,7 @@ namespace System.IO {
// check if pointer is aligned
if (((int)pointer & (sizeOfType - 1)) == 0) {
#endif
- result = *((Int64*)(pointer));
+ result = *((Int64*)(pointer));
#if ALIGN_ACCESS
}
else {
@@ -279,9 +324,11 @@ namespace System.IO {
result = (Int64)(((Int64)hi << 32) | (UInt32)lo);
}
#endif
- }
- finally {
- if (pointer != null) {
+ }
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -306,7 +353,8 @@ namespace System.IO {
return result;
}
- public Decimal ReadDecimal(Int64 position) {
+ public Decimal ReadDecimal(Int64 position)
+ {
const int ScaleMask = 0x00FF0000;
const int SignMask = unchecked((int)0x80000000);
@@ -347,15 +395,18 @@ namespace System.IO {
}
}
- public Single ReadSingle(Int64 position) {
+ public Single ReadSingle(Int64 position)
+ {
int sizeOfType = sizeof(Single);
EnsureSafeToRead(position, sizeOfType);
Single result;
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
pointer += (_offset + position);
@@ -372,8 +423,10 @@ namespace System.IO {
}
#endif
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -382,15 +435,18 @@ namespace System.IO {
return result;
}
- public Double ReadDouble(Int64 position) {
+ public Double ReadDouble(Int64 position)
+ {
int sizeOfType = sizeof(Double);
EnsureSafeToRead(position, sizeOfType);
Double result;
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
pointer += (_offset + position);
@@ -411,8 +467,10 @@ namespace System.IO {
}
#endif
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -422,21 +480,26 @@ 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);
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -444,17 +507,20 @@ namespace System.IO {
return result;
}
-
+
[CLSCompliant(false)]
- public UInt16 ReadUInt16(Int64 position) {
+ public UInt16 ReadUInt16(Int64 position)
+ {
int sizeOfType = sizeof(UInt16);
EnsureSafeToRead(position, sizeOfType);
UInt16 result;
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
pointer += (_offset + position);
@@ -471,8 +537,10 @@ namespace System.IO {
#endif
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -480,17 +548,20 @@ namespace System.IO {
return result;
}
-
+
[CLSCompliant(false)]
- public UInt32 ReadUInt32(Int64 position) {
+ public UInt32 ReadUInt32(Int64 position)
+ {
int sizeOfType = sizeof(UInt32);
EnsureSafeToRead(position, sizeOfType);
UInt32 result;
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
pointer += (_offset + position);
@@ -507,8 +578,10 @@ namespace System.IO {
#endif
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -518,15 +591,18 @@ namespace System.IO {
}
[CLSCompliant(false)]
- public UInt64 ReadUInt64(Int64 position) {
+ public UInt64 ReadUInt64(Int64 position)
+ {
int sizeOfType = sizeof(UInt64);
EnsureSafeToRead(position, sizeOfType);
UInt64 result;
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
pointer += (_offset + position);
@@ -545,8 +621,10 @@ namespace System.IO {
#endif
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -569,25 +647,32 @@ 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) {
+ public void Read<T>(Int64 position, out T structure) where T : struct
+ {
+ if (position < 0)
+ {
throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
Contract.EndContractBlock();
- if (!_isOpen) {
+ if (!_isOpen)
+ {
throw new ObjectDisposedException("UnmanagedMemoryAccessor", Environment.GetResourceString("ObjectDisposed_ViewAccessorClosed"));
}
- if (!CanRead) {
+ if (!CanRead)
+ {
throw new NotSupportedException(Environment.GetResourceString("NotSupported_Reading"));
}
UInt32 sizeOfT = Marshal.SizeOfType(typeof(T));
- if (position > _capacity - sizeOfT) {
- if (position >= _capacity) {
+ if (position > _capacity - sizeOfT)
+ {
+ if (position >= _capacity)
+ {
throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_PositionLessThanCapacityRequired"));
}
- else {
+ else
+ {
throw new ArgumentException(Environment.GetResourceString("Argument_NotEnoughBytesToRead", typeof(T).FullName), nameof(position));
}
}
@@ -601,47 +686,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) {
+ if (offset < 0)
+ {
throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
- if (count < 0) {
+ if (count < 0)
+ {
throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
- if (array.Length - offset < count) {
+ if (array.Length - offset < count)
+ {
throw new ArgumentException(Environment.GetResourceString("Argument_OffsetAndLengthOutOfBounds"));
}
Contract.EndContractBlock();
- if (!CanRead) {
- if (!_isOpen) {
+ if (!CanRead)
+ {
+ if (!_isOpen)
+ {
throw new ObjectDisposedException("UnmanagedMemoryAccessor", Environment.GetResourceString("ObjectDisposed_ViewAccessorClosed"));
}
- else {
+ else
+ {
throw new NotSupportedException(Environment.GetResourceString("NotSupported_Reading"));
}
}
- if (position < 0) {
+ if (position < 0)
+ {
throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
UInt32 sizeOfT = Marshal.AlignedSizeOf<T>();
// only check position and ask for fewer Ts if count is too big
- if (position >= _capacity) {
+ if (position >= _capacity)
+ {
throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("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 +757,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,21 +766,25 @@ 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) {
+ public void Write(Int64 position, char value)
+ {
int sizeOfType = sizeof(char);
EnsureSafeToWrite(position, sizeOfType);
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
pointer += (_offset + position);
@@ -689,7 +792,7 @@ namespace System.IO {
// check if pointer is aligned
if (((int)pointer & (sizeOfType - 1)) == 0) {
#endif
- *((char*)pointer) = value;
+ *((char*)pointer) = value;
#if ALIGN_ACCESS
}
else {
@@ -698,24 +801,28 @@ namespace System.IO {
}
#endif
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
}
-
}
- public void Write(Int64 position, Int16 value) {
+ public void Write(Int64 position, Int16 value)
+ {
int sizeOfType = sizeof(Int16);
EnsureSafeToWrite(position, sizeOfType);
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
pointer += (_offset + position);
@@ -723,7 +830,7 @@ namespace System.IO {
// check if pointer is aligned
if (((int)pointer & (sizeOfType - 1)) == 0) {
#endif
- *((Int16*)pointer) = value;
+ *((Int16*)pointer) = value;
#if ALIGN_ACCESS
}
else {
@@ -732,8 +839,10 @@ namespace System.IO {
}
#endif
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -741,14 +850,17 @@ namespace System.IO {
}
- public void Write(Int64 position, Int32 value) {
+ public void Write(Int64 position, Int32 value)
+ {
int sizeOfType = sizeof(Int32);
EnsureSafeToWrite(position, sizeOfType);
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
pointer += (_offset + position);
@@ -756,7 +868,7 @@ namespace System.IO {
// check if pointer is aligned
if (((int)pointer & (sizeOfType - 1)) == 0) {
#endif
- *((Int32*)pointer) = value;
+ *((Int32*)pointer) = value;
#if ALIGN_ACCESS
}
else {
@@ -767,29 +879,34 @@ namespace System.IO {
}
#endif
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
}
}
- public void Write(Int64 position, Int64 value) {
+ public void Write(Int64 position, Int64 value)
+ {
int sizeOfType = sizeof(Int64);
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
- *((Int64*)pointer) = value;
+ *((Int64*)pointer) = value;
#if ALIGN_ACCESS
}
else {
@@ -804,8 +921,10 @@ namespace System.IO {
}
#endif
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -829,7 +948,8 @@ namespace System.IO {
}
}
- public void Write(Int64 position, Decimal value) {
+ public void Write(Int64 position, Decimal value)
+ {
int sizeOfType = sizeof(Decimal);
EnsureSafeToWrite(position, sizeOfType);
@@ -862,14 +982,17 @@ namespace System.IO {
}
}
- public void Write(Int64 position, Single value) {
+ public void Write(Int64 position, Single value)
+ {
int sizeOfType = sizeof(Single);
EnsureSafeToWrite(position, sizeOfType);
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
pointer += (_offset + position);
#if ALIGN_ACCESS
@@ -889,22 +1012,27 @@ namespace System.IO {
}
#endif
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
}
}
- public void Write(Int64 position, Double value) {
+ public void Write(Int64 position, Double value)
+ {
int sizeOfType = sizeof(Double);
EnsureSafeToWrite(position, sizeOfType);
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
pointer += (_offset + position);
#if ALIGN_ACCESS
@@ -928,8 +1056,10 @@ namespace System.IO {
}
#endif
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -937,20 +1067,25 @@ namespace System.IO {
}
[CLSCompliant(false)]
- public void Write(Int64 position, SByte value) {
+ public void Write(Int64 position, SByte value)
+ {
int sizeOfType = sizeof(SByte);
EnsureSafeToWrite(position, sizeOfType);
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
pointer += (_offset + position);
*((SByte*)pointer) = value;
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -958,14 +1093,17 @@ 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);
@@ -982,8 +1120,10 @@ namespace System.IO {
}
#endif
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -991,14 +1131,17 @@ namespace System.IO {
}
[CLSCompliant(false)]
- public void Write(Int64 position, UInt32 value) {
+ public void Write(Int64 position, UInt32 value)
+ {
int sizeOfType = sizeof(UInt32);
EnsureSafeToWrite(position, sizeOfType);
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
pointer += (_offset + position);
@@ -1018,8 +1161,10 @@ namespace System.IO {
#endif
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -1027,14 +1172,17 @@ namespace System.IO {
}
[CLSCompliant(false)]
- public void Write(Int64 position, UInt64 value) {
+ public void Write(Int64 position, UInt64 value)
+ {
int sizeOfType = sizeof(UInt64);
EnsureSafeToWrite(position, sizeOfType);
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
pointer += (_offset + position);
#if ALIGN_ACCESS
@@ -1057,8 +1205,10 @@ namespace System.IO {
#endif
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -1070,25 +1220,32 @@ 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) {
+ public void Write<T>(Int64 position, ref T structure) where T : struct
+ {
+ if (position < 0)
+ {
throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
Contract.EndContractBlock();
- if (!_isOpen) {
+ if (!_isOpen)
+ {
throw new ObjectDisposedException("UnmanagedMemoryAccessor", Environment.GetResourceString("ObjectDisposed_ViewAccessorClosed"));
}
- if (!CanWrite) {
+ if (!CanWrite)
+ {
throw new NotSupportedException(Environment.GetResourceString("NotSupported_Writing"));
}
UInt32 sizeOfT = Marshal.SizeOfType(typeof(T));
- if (position > _capacity - sizeOfT) {
- if (position >= _capacity) {
+ if (position > _capacity - sizeOfT)
+ {
+ if (position >= _capacity)
+ {
throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_PositionLessThanCapacityRequired"));
}
- else {
+ else
+ {
throw new ArgumentException(Environment.GetResourceString("Argument_NotEnoughBytesToWrite", typeof(T).FullName), nameof(position));
}
}
@@ -1099,52 +1256,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) {
+ if (offset < 0)
+ {
throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
- if (count < 0) {
+ if (count < 0)
+ {
throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
- if (array.Length - offset < count) {
+ if (array.Length - offset < count)
+ {
throw new ArgumentException(Environment.GetResourceString("Argument_OffsetAndLengthOutOfBounds"));
}
- if (position < 0) {
+ if (position < 0)
+ {
throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
- if (position >= Capacity) {
+ if (position >= Capacity)
+ {
throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_PositionLessThanCapacityRequired"));
}
Contract.EndContractBlock();
- if (!_isOpen) {
+ if (!_isOpen)
+ {
throw new ObjectDisposedException("UnmanagedMemoryAccessor", Environment.GetResourceString("ObjectDisposed_ViewAccessorClosed"));
}
- if (!CanWrite) {
+ if (!CanWrite)
+ {
throw new NotSupportedException(Environment.GetResourceString("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));
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -1152,67 +1323,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;
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
}
}
- private void EnsureSafeToRead(Int64 position, int sizeOfType) {
- if (!_isOpen) {
+ private void EnsureSafeToRead(Int64 position, int sizeOfType)
+ {
+ if (!_isOpen)
+ {
throw new ObjectDisposedException("UnmanagedMemoryAccessor", Environment.GetResourceString("ObjectDisposed_ViewAccessorClosed"));
}
- if (!CanRead) {
+ if (!CanRead)
+ {
throw new NotSupportedException(Environment.GetResourceString("NotSupported_Reading"));
}
- if (position < 0) {
+ if (position < 0)
+ {
throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
Contract.EndContractBlock();
- if (position > _capacity - sizeOfType) {
- if (position >= _capacity) {
+ if (position > _capacity - sizeOfType)
+ {
+ if (position >= _capacity)
+ {
throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_PositionLessThanCapacityRequired"));
}
- else {
+ else
+ {
throw new ArgumentException(Environment.GetResourceString("Argument_NotEnoughBytesToRead"), nameof(position));
}
}
}
- private void EnsureSafeToWrite(Int64 position, int sizeOfType) {
- if (!_isOpen) {
+ private void EnsureSafeToWrite(Int64 position, int sizeOfType)
+ {
+ if (!_isOpen)
+ {
throw new ObjectDisposedException("UnmanagedMemoryAccessor", Environment.GetResourceString("ObjectDisposed_ViewAccessorClosed"));
}
- if (!CanWrite) {
+ if (!CanWrite)
+ {
throw new NotSupportedException(Environment.GetResourceString("NotSupported_Writing"));
}
- if (position < 0) {
+ if (position < 0)
+ {
throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
Contract.EndContractBlock();
- if (position > _capacity - sizeOfType) {
- if (position >= _capacity) {
+ if (position > _capacity - sizeOfType)
+ {
+ if (position >= _capacity)
+ {
throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_PositionLessThanCapacityRequired"));
}
- else {
+ else
+ {
throw new ArgumentException(Environment.GetResourceString("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..086c19bafa 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) {
+ if (offset < 0)
+ {
throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
- if (length < 0) {
+ if (length < 0)
+ {
throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
- if (buffer.ByteLength < (ulong)(offset + length)) {
+ if (buffer.ByteLength < (ulong)(offset + length))
+ {
throw new ArgumentException(Environment.GetResourceString("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) {
+ if (_isOpen)
+ {
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CalledTwice"));
}
// check for wraparound
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
buffer.AcquirePointer(ref pointer);
- if ( (pointer + offset + length) < pointer) {
+ if ((pointer + offset + length) < pointer)
+ {
throw new ArgumentException(Environment.GetResourceString("ArgumentOutOfRange_UnmanagedMemStreamWrapAround"));
}
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
buffer.ReleasePointer();
}
}
@@ -168,13 +184,13 @@ 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));
@@ -184,7 +200,7 @@ namespace System.IO {
throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_LengthGreaterThanCapacity"));
Contract.EndContractBlock();
// Check for wraparound.
- if (((byte*) ((long)pointer + capacity)) < pointer)
+ if (((byte*)((long)pointer + capacity)) < pointer)
throw new ArgumentOutOfRangeException(nameof(capacity), Environment.GetResourceString("ArgumentOutOfRange_UnmanagedMemStreamWrapAround"));
if (access < FileAccess.Read || access > FileAccess.ReadWrite)
throw new ArgumentOutOfRangeException(nameof(access), Environment.GetResourceString("ArgumentOutOfRange_Enum"));
@@ -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,53 +244,61 @@ 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"));
Contract.EndContractBlock();
if (!CanSeek) __Error.StreamIsClosed();
-
+
#if !BIT64
unsafe {
// On 32 bit machines, ensure we don't wrap around.
@@ -284,9 +311,12 @@ namespace System.IO {
}
[CLSCompliant(false)]
- public unsafe byte* PositionPointer {
- get {
- if (_buffer != null) {
+ public unsafe byte* PositionPointer
+ {
+ get
+ {
+ if (_buffer != null)
+ {
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UmsSafeBuffer"));
}
@@ -294,11 +324,12 @@ namespace System.IO {
long pos = Interlocked.Read(ref _position);
if (pos > _capacity)
throw new IndexOutOfRangeException(Environment.GetResourceString("IndexOutOfRange_UMSPosition"));
- byte * ptr = _mem + pos;
+ byte* ptr = _mem + pos;
if (!_isOpen) __Error.StreamIsClosed();
return ptr;
}
- set {
+ set
+ {
if (_buffer != null)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UmsSafeBuffer"));
if (!_isOpen) __Error.StreamIsClosed();
@@ -314,17 +345,20 @@ namespace System.IO {
}
}
- internal unsafe byte* Pointer {
- get {
+ internal unsafe byte* Pointer
+ {
+ get
+ {
if (_buffer != null)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UmsSafeBuffer"));
return _mem;
}
}
-
- public override int Read([In, Out] byte[] buffer, int offset, int count) {
- if (buffer==null)
+
+ public override int Read([In, Out] byte[] buffer, int offset, int count)
+ {
+ if (buffer == null)
throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
@@ -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,9 +417,10 @@ 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)
+
+ 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"));
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
@@ -394,24 +429,25 @@ namespace System.IO {
if (buffer.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("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"));
+ 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"));
}
long finalPos = Interlocked.Read(ref _position);
@@ -478,7 +523,8 @@ 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"));
Contract.EndContractBlock();
@@ -492,19 +538,23 @@ namespace System.IO {
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)
+ public override void Write(byte[] buffer, int offset, int count)
+ {
+ if (buffer == null)
throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
@@ -524,21 +574,26 @@ namespace System.IO {
if (n < 0)
throw new IOException(Environment.GetResourceString("IO.IO_StreamTooLong"));
- if (n > _capacity) {
+ if (n > _capacity)
+ {
throw new NotSupportedException(Environment.GetResourceString("IO.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);
}
}
@@ -579,10 +634,10 @@ namespace System.IO {
Interlocked.Exchange(ref _position, n);
return;
}
-
- public override Task WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) {
-
- if (buffer==null)
+
+ public override Task WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
+ {
+ if (buffer == null)
throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
@@ -591,45 +646,50 @@ namespace System.IO {
if (buffer.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("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"));
-
+
if (n > _capacity)
throw new NotSupportedException(Environment.GetResourceString("IO.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..04d5be3c5e 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() {
+
+ public override byte[] GetBuffer()
+ {
throw new UnauthorizedAccessException(Environment.GetResourceString("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 {
+ set
+ {
throw new IOException(Environment.GetResourceString("IO.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,18 +136,21 @@ 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)
+ public unsafe override void WriteTo(Stream stream)
+ {
+ if (stream == null)
throw new ArgumentNullException(nameof(stream), Environment.GetResourceString("ArgumentNull_Stream"));
Contract.EndContractBlock();
@@ -132,12 +158,12 @@ namespace System.IO {
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,12 +171,12 @@ 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"));
@@ -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..14c8eb9f3b 100644
--- a/src/mscorlib/src/System/IO/__Error.cs
+++ b/src/mscorlib/src/System/IO/__Error.cs
@@ -23,44 +23,54 @@ 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() {
+ internal static void EndOfFile()
+ {
throw new EndOfStreamException(Environment.GetResourceString("IO.EOF_ReadBeyondEOF"));
}
- internal static void FileNotOpen() {
+ internal static void FileNotOpen()
+ {
throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_FileClosed"));
}
-
- internal static void StreamIsClosed() {
+
+ internal static void StreamIsClosed()
+ {
throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_StreamClosed"));
}
-
- internal static void MemoryStreamNotExpandable() {
+
+ internal static void MemoryStreamNotExpandable()
+ {
throw new NotSupportedException(Environment.GetResourceString("NotSupported_MemStreamNotExpandable"));
}
-
- internal static void ReaderClosed() {
+
+ internal static void ReaderClosed()
+ {
throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_ReaderClosed"));
}
- internal static void ReadNotSupported() {
+ internal static void ReadNotSupported()
+ {
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnreadableStream"));
}
- internal static void WrongAsyncResult() {
+ internal static void WrongAsyncResult()
+ {
throw new ArgumentException(Environment.GetResourceString("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"));
}
- 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"));
}
@@ -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,24 +99,30 @@ 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");
else
@@ -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(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);
}
}
-
- internal static void WriteNotSupported() {
+
+ internal static void WriteNotSupported()
+ {
throw new NotSupportedException(Environment.GetResourceString("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/IServiceObjectProvider.cs b/src/mscorlib/src/System/IServiceObjectProvider.cs
index feb1143487..434ee2b5f8 100644
--- a/src/mscorlib/src/System/IServiceObjectProvider.cs
+++ b/src/mscorlib/src/System/IServiceObjectProvider.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.
-namespace System {
-
- using System;
- using System.Runtime.InteropServices;
+using System;
+using System.Runtime.InteropServices;
+namespace System
+{
public interface IServiceProvider
{
// Interface does not need to be marked with the serializable attribute
diff --git a/src/mscorlib/src/System/InsufficientMemoryException.cs b/src/mscorlib/src/System/InsufficientMemoryException.cs
index 448a061821..cd963e84b6 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)) {
+ public InsufficientMemoryException()
+ : base(GetMessageFromNativeResources(ExceptionMessageKind.OutOfMemory))
+ {
SetErrorCode(__HResults.COR_E_INSUFFICIENTMEMORY);
}
-
- public InsufficientMemoryException(String message)
- : base(message) {
+
+ public InsufficientMemoryException(String message)
+ : base(message)
+ {
SetErrorCode(__HResults.COR_E_INSUFFICIENTMEMORY);
}
-
- public InsufficientMemoryException(String message, Exception innerException)
- : base(message, innerException) {
+
+ public InsufficientMemoryException(String message, Exception innerException)
+ : base(message, innerException)
+ {
SetErrorCode(__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..89b081b55b 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"));
}
- 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,235 @@ 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) {
+ catch (OverflowException e)
+ {
throw new OverflowException(Environment.GetResourceString("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)) {
+ if ((style & NumberStyles.AllowHexSpecifier) != 0)
+ { // We are parsing a hexadecimal number
+ if ((i < 0) || (i > UInt16.MaxValue))
+ {
throw new OverflowException(Environment.GetResourceString("Overflow_Int16"));
}
return (short)i;
}
-
+
if (i < MinValue || i > MaxValue) throw new OverflowException(Environment.GetResourceString("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) {
+ DateTime IConvertible.ToDateTime(IFormatProvider provider)
+ {
throw new InvalidCastException(Environment.GetResourceString("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..cbbd5f912b 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(Environment.GetResourceString("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,100 @@ 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) {
+ DateTime IConvertible.ToDateTime(IFormatProvider provider)
+ {
throw new InvalidCastException(Environment.GetResourceString("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..9e68c423cf 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(Environment.GetResourceString("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,99 @@ 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) {
+ DateTime IConvertible.ToDateTime(IFormatProvider provider)
+ {
throw new InvalidCastException(Environment.GetResourceString("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..17a2d3864c 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)) {
+ if (Size == 4 && (l > Int32.MaxValue || l < Int32.MinValue))
+ {
throw new ArgumentException(Environment.GetResourceString("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..6c1b3b8243 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
+ internal static class Internal
{
// 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()
+ private static void 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/Lazy.cs b/src/mscorlib/src/System/Lazy.cs
index 0ddd6da3a2..446ec30cd6 100644
--- a/src/mscorlib/src/System/Lazy.cs
+++ b/src/mscorlib/src/System/Lazy.cs
@@ -50,14 +50,13 @@ namespace System
[DebuggerDisplay("ThreadSafetyMode={Mode}, IsValueCreated={IsValueCreated}, IsValueFaulted={IsValueFaulted}, Value={ValueForDebugDisplay}")]
public class Lazy<T>
{
-
-#region Inner classes
+ #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
+ private class Boxed
{
internal Boxed(T value)
{
@@ -70,7 +69,7 @@ namespace System
/// <summary>
/// Wrapper class to wrap the excpetion thrown by the value factory
/// </summary>
- class LazyInternalExceptionHolder
+ private class LazyInternalExceptionHolder
{
internal ExceptionDispatchInfo m_edi;
internal LazyInternalExceptionHolder(Exception ex)
@@ -78,12 +77,12 @@ namespace System
m_edi = ExceptionDispatchInfo.Capture(ex);
}
}
-#endregion
+ #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
+ private static readonly Func<T> ALREADY_INVOKED_SENTINEL = delegate
{
Debug.Assert(false, "ALREADY_INVOKED_SENTINEL should never be invoked.");
return default(T);
@@ -155,8 +154,8 @@ namespace System
/// </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)
+ public Lazy(bool isThreadSafe) :
+ this(isThreadSafe ? LazyThreadSafetyMode.ExecutionAndPublication : LazyThreadSafetyMode.None)
{
}
@@ -219,7 +218,7 @@ namespace System
return LazyHelpers.PUBLICATION_ONLY_SENTINEL;
else if (mode != LazyThreadSafetyMode.None)
throw new ArgumentOutOfRangeException(nameof(mode), Environment.GetResourceString("Lazy_ctor_ModeInvalid"));
-
+
return null; // None mode
}
@@ -321,7 +320,7 @@ namespace System
get
{
Boxed boxed = null;
- if (m_boxed != null )
+ if (m_boxed != null)
{
// Do a quick check up front for the fast path.
boxed = m_boxed as Boxed;
@@ -447,7 +446,6 @@ namespace System
try
{
boxed = new Boxed((T)Activator.CreateInstance(typeof(T)));
-
}
catch (System.MissingMethodException)
{
@@ -460,7 +458,6 @@ namespace System
return boxed;
}
-
}
/// <summary>A debugger view of the Lazy&lt;T&gt; to surface additional debugging properties and
@@ -501,6 +498,5 @@ namespace System
{
get { return m_lazy.IsValueFaulted; }
}
-
}
}
diff --git a/src/mscorlib/src/System/LowLevelConsole.cs b/src/mscorlib/src/System/LowLevelConsole.cs
index 29e69185ac..8fa29e5fd4 100644
--- a/src/mscorlib/src/System/LowLevelConsole.cs
+++ b/src/mscorlib/src/System/LowLevelConsole.cs
@@ -23,7 +23,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,14 +39,14 @@ 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
- {
+ //
+ // 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);
diff --git a/src/mscorlib/src/System/Math.cs b/src/mscorlib/src/System/Math.cs
index 8b2af3d3e4..4cdb7944b2 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), 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);
// 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====================================
**
@@ -575,26 +634,29 @@ namespace System {
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));
- }
-
-
+ /*=====================================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;
@@ -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..2abac7b5db 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), Environment.GetResourceString("ArgumentOutOfRange_RoundingDigits"));
}
Contract.EndContractBlock();
@@ -170,7 +172,7 @@ namespace System {
{
throw new ArgumentOutOfRangeException(nameof(digits), Environment.GetResourceString("ArgumentOutOfRange_RoundingDigits"));
}
-
+
if (mode < MidpointRounding.ToEven || mode > MidpointRounding.AwayFromZero)
{
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidEnumx", mode, nameof(MidpointRounding)), nameof(mode));
@@ -187,7 +189,7 @@ namespace System {
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidEnumx", 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/MissingFieldException.cs b/src/mscorlib/src/System/MissingFieldException.cs
index 660e39cb47..15d1a684bc 100644
--- a/src/mscorlib/src/System/MissingFieldException.cs
+++ b/src/mscorlib/src/System/MissingFieldException.cs
@@ -9,39 +9,50 @@
**
=============================================================================*/
-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")) {
+ public class MissingFieldException : MissingMemberException, ISerializable
+ {
+ public MissingFieldException()
+ : base(Environment.GetResourceString("Arg_MissingFieldException"))
+ {
SetErrorCode(__HResults.COR_E_MISSINGFIELD);
}
-
- public MissingFieldException(String message)
- : base(message) {
+
+ public MissingFieldException(String message)
+ : base(message)
+ {
SetErrorCode(__HResults.COR_E_MISSINGFIELD);
}
-
- public MissingFieldException(String message, Exception inner)
- : base(message, inner) {
+
+ public MissingFieldException(String message, Exception inner)
+ : base(message, inner)
+ {
SetErrorCode(__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) + " " : "") +
@@ -49,13 +60,13 @@ namespace System {
}
}
}
-
+
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..be5ac83743 100644
--- a/src/mscorlib/src/System/MissingMemberException.cs
+++ b/src/mscorlib/src/System/MissingMemberException.cs
@@ -11,65 +11,77 @@
**
=============================================================================*/
-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")) {
+ public class MissingMemberException : MemberAccessException, ISerializable
+ {
+ public MissingMemberException()
+ : base(Environment.GetResourceString("Arg_MissingMemberException"))
+ {
SetErrorCode(__HResults.COR_E_MISSINGMEMBER);
}
-
- public MissingMemberException(String message)
- : base(message) {
+
+ public MissingMemberException(String message)
+ : base(message)
+ {
SetErrorCode(__HResults.COR_E_MISSINGMEMBER);
}
-
- public MissingMemberException(String message, Exception inner)
- : base(message, inner) {
+
+ public MissingMemberException(String message, Exception inner)
+ : base(message, inner)
+ {
SetErrorCode(__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",
+ return Environment.GetResourceString("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 +90,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
index 426711f953..81b2f61205 100644
--- a/src/mscorlib/src/System/MissingMethodException.cs
+++ b/src/mscorlib/src/System/MissingMethodException.cs
@@ -11,39 +11,50 @@
**
=============================================================================*/
-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 MissingMethodException : MissingMemberException, ISerializable {
- public MissingMethodException()
- : base(Environment.GetResourceString("Arg_MissingMethodException")) {
+ public class MissingMethodException : MissingMemberException, ISerializable
+ {
+ public MissingMethodException()
+ : base(Environment.GetResourceString("Arg_MissingMethodException"))
+ {
SetErrorCode(__HResults.COR_E_MISSINGMETHOD);
}
-
- public MissingMethodException(String message)
- : base(message) {
+
+ public MissingMethodException(String message)
+ : base(message)
+ {
SetErrorCode(__HResults.COR_E_MISSINGMETHOD);
}
-
- public MissingMethodException(String message, Exception inner)
- : base(message, inner) {
+
+ public MissingMethodException(String message, Exception inner)
+ : base(message, inner)
+ {
SetErrorCode(__HResults.COR_E_MISSINGMETHOD);
}
- protected MissingMethodException(SerializationInfo info, StreamingContext context) : base(info, context) {
+ protected MissingMethodException(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("MissingMethod_Name",
ClassName + "." + MemberName +
@@ -51,13 +62,13 @@ namespace System {
}
}
}
-
+
public MissingMethodException(String className, String methodName)
{
- ClassName = className;
- MemberName = 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..6d4d28891f 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() )
+ if (!(method is RuntimeMethodInfo) || IsUnmanagedFunctionPtr())
throw new SerializationException(Environment.GetResourceString("Serialization_InvalidDelegateType"));
// We can't deal with secure delegates either.
if (!InvocationListLogicallyNull() && !_invocationCount.IsNull() && !_methodPtrAux.IsNull())
throw new SerializationException(Environment.GetResourceString("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,11 +86,11 @@ 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)
+ if (nextDe == null)
throw new SerializationException(Environment.GetResourceString("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;
}
@@ -274,8 +273,8 @@ namespace System
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,10 +587,10 @@ 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"));
}
@@ -598,7 +598,7 @@ namespace System
[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/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
index 68e8f88d81..5bc8df1e28 100644
--- a/src/mscorlib/src/System/NotFiniteNumberException.cs
+++ b/src/mscorlib/src/System/NotFiniteNumberException.cs
@@ -4,66 +4,66 @@
using System.Runtime.Serialization;
-namespace System
+namespace System
{
[Serializable]
- public class NotFiniteNumberException : ArithmeticException
+ public class NotFiniteNumberException : ArithmeticException
{
- private double _offendingNumber;
-
- public NotFiniteNumberException()
- : base(SR.Arg_NotFiniteNumberException)
+ private double _offendingNumber;
+
+ public NotFiniteNumberException()
+ : base(SR.Arg_NotFiniteNumberException)
{
_offendingNumber = 0;
HResult = __HResults.COR_E_NOTFINITENUMBER;
}
- public NotFiniteNumberException(double offendingNumber)
- : base()
+ public NotFiniteNumberException(double offendingNumber)
+ : base()
{
_offendingNumber = offendingNumber;
HResult = __HResults.COR_E_NOTFINITENUMBER;
}
- public NotFiniteNumberException(String message)
- : base(message)
+ public NotFiniteNumberException(String message)
+ : base(message)
{
_offendingNumber = 0;
HResult = __HResults.COR_E_NOTFINITENUMBER;
}
- public NotFiniteNumberException(String message, double offendingNumber)
- : base(message)
+ public NotFiniteNumberException(String message, double offendingNumber)
+ : base(message)
{
_offendingNumber = offendingNumber;
HResult = __HResults.COR_E_NOTFINITENUMBER;
}
- public NotFiniteNumberException(String message, Exception innerException)
- : base(message, innerException)
+ 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)
+
+ 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)
+ protected NotFiniteNumberException(SerializationInfo info, StreamingContext context) : base(info, context)
{
_offendingNumber = info.GetInt32("OffendingNumber");
}
- public override void GetObjectData(SerializationInfo info, StreamingContext context)
+ public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("OffendingNumber", _offendingNumber, typeof(Int32));
}
- public double OffendingNumber
+ public double OffendingNumber
{
get { return _offendingNumber; }
}
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..d7a1bc12e1 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)) {
+ if (!NumberBufferToDecimal(number.PackForNative(), ref result))
+ {
throw new OverflowException(Environment.GetResourceString("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"));
}
- if (!NumberBufferToDouble(number.PackForNative(), ref d)) {
+ if (!NumberBufferToDouble(number.PackForNative(), ref d))
+ {
throw new OverflowException(Environment.GetResourceString("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)) {
+ if ((style & NumberStyles.AllowHexSpecifier) != 0)
+ {
+ if (!HexNumberToInt32(ref number, ref i))
+ {
throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
}
}
- else {
- if (!NumberToInt32(ref number, ref i)) {
+ else
+ {
+ if (!NumberToInt32(ref number, ref i))
+ {
throw new OverflowException(Environment.GetResourceString("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)) {
+ if ((options & NumberStyles.AllowHexSpecifier) != 0)
+ {
+ if (!HexNumberToInt64(ref number, ref i))
+ {
throw new OverflowException(Environment.GetResourceString("Overflow_Int64"));
}
}
- else {
- if (!NumberToInt64(ref number, ref i)) {
+ else
+ {
+ if (!NumberToInt64(ref number, ref i))
+ {
throw new OverflowException(Environment.GetResourceString("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"));
}
- if (!NumberBufferToDouble(number.PackForNative(), ref d)) {
+ if (!NumberBufferToDouble(number.PackForNative(), ref d))
+ {
throw new OverflowException(Environment.GetResourceString("Overflow_Single"));
}
Single castSingle = (Single)d;
- if (Single.IsInfinity(castSingle)) {
+ if (Single.IsInfinity(castSingle))
+ {
throw new OverflowException(Environment.GetResourceString("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)) {
+ if ((options & NumberStyles.AllowHexSpecifier) != 0)
+ {
+ if (!HexNumberToUInt32(ref number, ref i))
+ {
throw new OverflowException(Environment.GetResourceString("Overflow_UInt32"));
}
}
- else {
- if (!NumberToUInt32(ref number, ref i)) {
+ else
+ {
+ if (!NumberToUInt32(ref number, ref i))
+ {
throw new OverflowException(Environment.GetResourceString("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)) {
+ if ((options & NumberStyles.AllowHexSpecifier) != 0)
+ {
+ if (!HexNumberToUInt64(ref number, ref i))
+ {
throw new OverflowException(Environment.GetResourceString("Overflow_UInt64"));
}
}
- else {
- if (!NumberToUInt64(ref number, ref i)) {
+ else
+ {
+ if (!NumberToUInt64(ref number, ref i))
+ {
throw new OverflowException(Environment.GetResourceString("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)))) {
+ 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"));
}
}
}
-
- 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..643e1d933e 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(Environment.GetResourceString("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
index 1f77b1f009..abb7c89dae 100644
--- a/src/mscorlib/src/System/ObjectDisposedException.cs
+++ b/src/mscorlib/src/System/ObjectDisposedException.cs
@@ -48,7 +48,7 @@ namespace System
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
- info.AddValue("ObjectName",ObjectName,typeof(String));
+ info.AddValue("ObjectName", ObjectName, typeof(String));
}
/// <devdoc>
diff --git a/src/mscorlib/src/System/OleAutBinder.cs b/src/mscorlib/src/System/OleAutBinder.cs
index acae95a214..fafaa8d6ee 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,7 +78,7 @@ namespace System {
#if DISPLAY_DEBUG_INFO
catch(NotSupportedException e)
#else
- catch(NotSupportedException)
+ catch (NotSupportedException)
#endif
{
#if DISPLAY_DEBUG_INFO
diff --git a/src/mscorlib/src/System/OperatingSystem.cs b/src/mscorlib/src/System/OperatingSystem.cs
index a388fc6e33..d8f78d73c9 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),
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 ) {
+ if (_version == null)
+ {
throw new SerializationException(Environment.GetResourceString("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..371e1c04ce 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")) {
+ public OperationCanceledException()
+ : base(Environment.GetResourceString("OperationCanceled"))
+ {
SetErrorCode(__HResults.COR_E_OPERATIONCANCELED);
}
-
- public OperationCanceledException(String message)
- : base(message) {
+
+ public OperationCanceledException(String message)
+ : base(message)
+ {
SetErrorCode(__HResults.COR_E_OPERATIONCANCELED);
}
-
- public OperationCanceledException(String message, Exception innerException)
- : base(message, innerException) {
+
+ public OperationCanceledException(String message, Exception innerException)
+ : base(message, innerException)
+ {
SetErrorCode(__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..a4327584c6 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)) {
+ public class OutOfMemoryException : SystemException
+ {
+ public OutOfMemoryException()
+ : base(GetMessageFromNativeResources(ExceptionMessageKind.OutOfMemory))
+ {
SetErrorCode(__HResults.COR_E_OUTOFMEMORY);
}
-
- public OutOfMemoryException(String message)
- : base(message) {
+
+ public OutOfMemoryException(String message)
+ : base(message)
+ {
SetErrorCode(__HResults.COR_E_OUTOFMEMORY);
}
-
- public OutOfMemoryException(String message, Exception innerException)
- : base(message, innerException) {
+
+ public OutOfMemoryException(String message, Exception innerException)
+ : base(message, innerException)
+ {
SetErrorCode(__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/ParamsArray.cs b/src/mscorlib/src/System/ParamsArray.cs
index ed8919c586..ee28b9168b 100644
--- a/src/mscorlib/src/System/ParamsArray.cs
+++ b/src/mscorlib/src/System/ParamsArray.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.
+
namespace System
{
internal struct ParamsArray
@@ -23,21 +24,21 @@ namespace System
public ParamsArray(object arg0)
{
this.arg0 = arg0;
- this.arg1 = null;
- this.arg2 = null;
+ arg1 = null;
+ arg2 = null;
// Always assign this.args to make use of its "Length" property
- this.args = oneArgArray;
+ args = oneArgArray;
}
public ParamsArray(object arg0, object arg1)
{
this.arg0 = arg0;
this.arg1 = arg1;
- this.arg2 = null;
+ arg2 = null;
// Always assign this.args to make use of its "Length" property
- this.args = twoArgArray;
+ args = twoArgArray;
}
public ParamsArray(object arg0, object arg1, object arg2)
@@ -47,35 +48,35 @@ namespace System
this.arg2 = arg2;
// Always assign this.args to make use of its "Length" property
- this.args = threeArgArray;
+ 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;
+ arg0 = len > 0 ? args[0] : null;
+ arg1 = len > 1 ? args[1] : null;
+ arg2 = len > 2 ? args[2] : null;
this.args = args;
}
public int Length
{
- get { return this.args.Length; }
+ get { return args.Length; }
}
public object this[int index]
{
- get { return index == 0 ? this.arg0 : GetAtSlow(index); }
+ get { return index == 0 ? arg0 : GetAtSlow(index); }
}
private object GetAtSlow(int index)
{
if (index == 1)
- return this.arg1;
+ return arg1;
if (index == 2)
- return this.arg2;
- return this.args[index];
+ return arg2;
+ return 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/Random.cs b/src/mscorlib/src/System/Random.cs
index db6da0ea8b..507c2336c5 100644
--- a/src/mscorlib/src/System/Random.cs
+++ b/src/mscorlib/src/System/Random.cs
@@ -10,240 +10,265 @@
**
**
===========================================================*/
-namespace System {
- using System;
- using System.Runtime;
- using System.Runtime.CompilerServices;
- using System.Globalization;
- using System.Diagnostics.Contracts;
+using System;
+using System.Runtime;
+using System.Runtime.CompilerServices;
+using System.Globalization;
+using System.Diagnostics.Contracts;
+namespace System
+{
[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];
+ 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;
}
- 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;
- }
+
+
+ /*=====================================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);
}
- 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));
+
+
+ /*=====================================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/Reflection/AmbiguousMatchException.cs b/src/mscorlib/src/System/Reflection/AmbiguousMatchException.cs
index 795a8714d1..36091d0296 100644
--- a/src/mscorlib/src/System/Reflection/AmbiguousMatchException.cs
+++ b/src/mscorlib/src/System/Reflection/AmbiguousMatchException.cs
@@ -13,29 +13,33 @@
//
//
//
-namespace System.Reflection {
+
+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")) {
+ public AmbiguousMatchException()
+ : base(Environment.GetResourceString("RFLCT.Ambiguous"))
+ {
SetErrorCode(__HResults.COR_E_AMBIGUOUSMATCH);
}
-
- public AmbiguousMatchException(String message) : base(message) {
+
+ public AmbiguousMatchException(String message) : base(message)
+ {
SetErrorCode(__HResults.COR_E_AMBIGUOUSMATCH);
}
-
- public AmbiguousMatchException(String message, Exception inner) : base(message, inner) {
+
+ public AmbiguousMatchException(String message, Exception inner) : base(message, inner)
+ {
SetErrorCode(__HResults.COR_E_AMBIGUOUSMATCH);
}
- internal AmbiguousMatchException(SerializationInfo info, StreamingContext context) : base(info, context) {
+ internal AmbiguousMatchException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
}
-
}
}
diff --git a/src/mscorlib/src/System/Reflection/Assembly.cs b/src/mscorlib/src/System/Reflection/Assembly.cs
index 4bb1708ac0..37698f6629 100644
--- a/src/mscorlib/src/System/Reflection/Assembly.cs
+++ b/src/mscorlib/src/System/Reflection/Assembly.cs
@@ -14,7 +14,7 @@
**
=============================================================================*/
-namespace System.Reflection
+namespace System.Reflection
{
using System;
using System.Collections;
@@ -43,9 +43,9 @@ namespace System.Reflection
[Serializable]
public abstract class Assembly : ICustomAttributeProvider, ISerializable
{
- protected Assembly() {}
+ protected Assembly() { }
-#region public static methods
+ #region public static methods
public static String CreateQualifiedName(String assemblyName, String typeName)
{
@@ -95,7 +95,7 @@ namespace System.Reflection
public static Assembly LoadFrom(String assemblyFile)
{
- if(assemblyFile == null)
+ if (assemblyFile == null)
throw new ArgumentNullException(nameof(assemblyFile));
string fullPath = Path.GetFullPath(assemblyFile);
return AssemblyLoadContext.Default.LoadFromAssemblyPath(fullPath);
@@ -174,8 +174,10 @@ namespace System.Reflection
false /*forIntrospection*/,
out assembly);
- if (assembly == null) {
- if (assemblyName.ContentType == AssemblyContentType.WindowsRuntime) {
+ if (assembly == null)
+ {
+ if (assemblyName.ContentType == AssemblyContentType.WindowsRuntime)
+ {
return Type.GetType(typeName + ", " + assemblyString, true /*throwOnError*/, false /*ignoreCase*/);
}
@@ -236,7 +238,7 @@ namespace System.Reflection
[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)
+ if (partialName == null)
throw new ArgumentNullException(nameof(partialName));
return Load(partialName);
}
@@ -279,11 +281,11 @@ namespace System.Reflection
AppDomain.CheckLoadByteArraySupported();
- if(rawAssembly == null)
+ 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;
+ MemoryStream symbolStream = (rawSymbolStore != null) ? new MemoryStream(rawSymbolStore) : null;
return alc.LoadFromStream(assemblyStream, symbolStream);
}
@@ -297,7 +299,7 @@ namespace System.Reflection
AppDomain.CheckLoadFileSupported();
Assembly result = null;
- if(path == null)
+ if (path == null)
throw new ArgumentNullException(nameof(path));
if (PathInternal.IsPartiallyQualified(path))
@@ -307,9 +309,9 @@ namespace System.Reflection
string normalizedPath = Path.GetFullPath(path);
- lock(s_loadfile)
+ lock (s_loadfile)
{
- if(s_loadfile.TryGetValue(normalizedPath, out result))
+ if (s_loadfile.TryGetValue(normalizedPath, out result))
return result;
AssemblyLoadContext alc = new IndividualAssemblyLoadContext();
result = alc.LoadFromAssemblyPath(normalizedPath);
@@ -327,7 +329,7 @@ namespace System.Reflection
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()
{
@@ -337,17 +339,18 @@ namespace System.Reflection
StackCrawlMark stackMark = StackCrawlMark.LookForMyCallersCaller;
return RuntimeAssembly.GetExecutingAssembly(ref stackMark);
}
-
- public static Assembly GetEntryAssembly() {
+
+ public static Assembly GetEntryAssembly()
+ {
AppDomainManager domainManager = AppDomain.CurrentDomain.DomainManager;
if (domainManager == null)
domainManager = new AppDomainManager();
return domainManager.EntryAssembly;
}
-#endregion // public static methods
+ #endregion // public static methods
-#region public methods
+ #region public methods
public virtual event ModuleResolveEventHandler ModuleResolve
{
add
@@ -440,7 +443,6 @@ namespace System.Reflection
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));
@@ -613,9 +615,9 @@ namespace System.Reflection
null); // activation attributes
}
- public virtual Object CreateInstance(String typeName,
+ public virtual Object CreateInstance(String typeName,
bool ignoreCase,
- BindingFlags bindingAttr,
+ BindingFlags bindingAttr,
Binder binder,
Object[] args,
CultureInfo culture,
@@ -638,7 +640,7 @@ namespace System.Reflection
return GetLoadedModules(true);
}
}
-
+
public Module[] GetLoadedModules()
{
return GetLoadedModules(false);
@@ -648,7 +650,7 @@ namespace System.Reflection
{
throw new NotImplementedException();
}
-
+
public Module[] GetModules()
{
return GetModules(false);
@@ -699,7 +701,7 @@ namespace System.Reflection
public override String ToString()
{
- String displayName = FullName;
+ String displayName = FullName;
if (displayName == null)
return base.ToString();
else
@@ -724,7 +726,7 @@ namespace System.Reflection
/*
Returns true if the assembly was loaded from the global assembly cache.
- */
+ */
public virtual bool GlobalAssemblyCache
{
get
@@ -755,7 +757,7 @@ namespace System.Reflection
return false;
}
}
-#endregion // public methods
+ #endregion // public methods
}
@@ -767,11 +769,11 @@ 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_SAFE_REFLECTION = 0x04000000,
+ ASSEMBLY_FLAGS_TOKEN_MASK = 0x00FFFFFF,
}
#endif // FEATURE_APPX
@@ -779,7 +781,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,7 +790,7 @@ namespace System.Reflection
#if FEATURE_APPX
private ASSEMBLY_FLAGS m_flags;
#endif
-#endregion
+ #endregion
#if FEATURE_APPX
internal int InvocableAttributeCtorToken
@@ -829,7 +831,7 @@ namespace System.Reflection
return m_syncRoot;
}
}
-
+
public override event ModuleResolveEventHandler ModuleResolve
{
add
@@ -846,8 +848,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 +861,8 @@ namespace System.Reflection
public override String CodeBase
{
- get {
+ get
+ {
String codeBase = GetCodeBase(false);
return codeBase;
}
@@ -879,7 +882,7 @@ namespace System.Reflection
String codeBase = GetCodeBase(copiedName);
- an.Init(GetSimpleName(),
+ an.Init(GetSimpleName(),
GetPublicKey(),
null, // public key token
GetVersion(),
@@ -892,14 +895,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 +914,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 +931,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 +965,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;
@@ -999,7 +1004,7 @@ namespace System.Reflection
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return GetManifestResourceStream(type, name, false, ref stackMark);
}
-
+
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public override Stream GetManifestResourceStream(String name)
{
@@ -1010,14 +1015,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 +1049,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(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType));
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
}
@@ -1058,8 +1063,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(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType));
return CustomAttribute.IsDefined(this, attributeRuntimeType);
}
@@ -1070,9 +1075,9 @@ namespace System.Reflection
}
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
- internal static RuntimeAssembly InternalLoadFrom(String assemblyFile,
+ internal static RuntimeAssembly InternalLoadFrom(String assemblyFile,
Evidence securityEvidence,
- byte[] hashValue,
+ byte[] hashValue,
AssemblyHashAlgorithm hashAlgorithm,
bool forIntrospection,
ref StackCrawlMark stackMark)
@@ -1095,7 +1100,7 @@ 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);
}
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
@@ -1108,20 +1113,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)
@@ -1139,10 +1145,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 +1163,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 +1183,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 +1200,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"
};
@@ -1314,7 +1320,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);
@@ -1338,7 +1344,7 @@ namespace System.Reflection
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 +1353,7 @@ namespace System.Reflection
return null;
return new ManifestResourceInfo(retAssembly, fileName,
- (ResourceLocation) location);
+ (ResourceLocation)location);
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
@@ -1356,7 +1362,8 @@ namespace System.Reflection
public override String Location
{
- get {
+ get
+ {
String location = null;
GetLocation(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref location));
@@ -1371,7 +1378,8 @@ namespace System.Reflection
public override String ImageRuntimeVersion
{
- get{
+ get
+ {
String s = null;
GetImageRuntimeVersion(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref s));
return s;
@@ -1396,7 +1404,7 @@ namespace System.Reflection
private static String VerifyCodeBase(String codebase)
{
- if(codebase == null)
+ if (codebase == null)
return null;
int len = codebase.Length;
@@ -1406,10 +1414,10 @@ 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
else if ((len > 2) && (codebase[0] == '\\') && (codebase[1] == '\\'))
@@ -1429,20 +1437,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,7 +1473,8 @@ 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"));
@@ -1476,9 +1488,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 +1498,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 +1522,8 @@ namespace System.Reflection
public override bool IsDynamic
{
- get {
+ get
+ {
return FCallIsDynamic(GetNativeHandle());
}
}
@@ -1534,7 +1547,7 @@ namespace System.Reflection
{
return GetHashAlgorithm(GetNativeHandle());
}
-
+
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static AssemblyNameFlags GetFlags(RuntimeAssembly assembly);
@@ -1575,8 +1588,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;
}
@@ -1620,7 +1634,6 @@ namespace System.Reflection
bool throwOnFileNotFound,
ref StackCrawlMark stackMark)
{
-
AssemblyName an = new AssemblyName();
an.SetPublicKey(GetPublicKey());
@@ -1634,7 +1647,7 @@ 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);
@@ -1648,11 +1661,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/AssemblyAttributes.cs b/src/mscorlib/src/System/Reflection/AssemblyAttributes.cs
index 1e6688d1f4..fc1d025240 100644
--- a/src/mscorlib/src/System/Reflection/AssemblyAttributes.cs
+++ b/src/mscorlib/src/System/Reflection/AssemblyAttributes.cs
@@ -13,14 +13,15 @@
**
=============================================================================*/
-namespace System.Reflection {
- using System;
- using System.Configuration.Assemblies;
- using System.Diagnostics.Contracts;
+using System;
+using System.Configuration.Assemblies;
+using System.Diagnostics.Contracts;
- [AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
- public sealed class AssemblyCopyrightAttribute : Attribute
+namespace System.Reflection
+{
+ [AttributeUsage(AttributeTargets.Assembly, Inherited = false)]
+ public sealed class AssemblyCopyrightAttribute : Attribute
{
private String m_copyright;
@@ -36,8 +37,8 @@ namespace System.Reflection {
}
- [AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
- public sealed class AssemblyTrademarkAttribute : Attribute
+ [AttributeUsage(AttributeTargets.Assembly, Inherited = false)]
+ public sealed class AssemblyTrademarkAttribute : Attribute
{
private String m_trademark;
@@ -53,8 +54,8 @@ namespace System.Reflection {
}
- [AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
- public sealed class AssemblyProductAttribute : Attribute
+ [AttributeUsage(AttributeTargets.Assembly, Inherited = false)]
+ public sealed class AssemblyProductAttribute : Attribute
{
private String m_product;
@@ -70,10 +71,10 @@ namespace System.Reflection {
}
- [AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
- public sealed class AssemblyCompanyAttribute : Attribute
+ [AttributeUsage(AttributeTargets.Assembly, Inherited = false)]
+ public sealed class AssemblyCompanyAttribute : Attribute
{
- private String m_company;
+ private String m_company;
public AssemblyCompanyAttribute(String company)
{
@@ -87,10 +88,10 @@ namespace System.Reflection {
}
- [AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
- public sealed class AssemblyDescriptionAttribute : Attribute
+ [AttributeUsage(AttributeTargets.Assembly, Inherited = false)]
+ public sealed class AssemblyDescriptionAttribute : Attribute
{
- private String m_description;
+ private String m_description;
public AssemblyDescriptionAttribute(String description)
{
@@ -104,8 +105,8 @@ namespace System.Reflection {
}
- [AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
- public sealed class AssemblyTitleAttribute : Attribute
+ [AttributeUsage(AttributeTargets.Assembly, Inherited = false)]
+ public sealed class AssemblyTitleAttribute : Attribute
{
private String m_title;
@@ -121,10 +122,10 @@ namespace System.Reflection {
}
- [AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
- public sealed class AssemblyConfigurationAttribute : Attribute
+ [AttributeUsage(AttributeTargets.Assembly, Inherited = false)]
+ public sealed class AssemblyConfigurationAttribute : Attribute
{
- private String m_configuration;
+ private String m_configuration;
public AssemblyConfigurationAttribute(String configuration)
{
@@ -138,8 +139,8 @@ namespace System.Reflection {
}
- [AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
- public sealed class AssemblyDefaultAliasAttribute : Attribute
+ [AttributeUsage(AttributeTargets.Assembly, Inherited = false)]
+ public sealed class AssemblyDefaultAliasAttribute : Attribute
{
private String m_defaultAlias;
@@ -153,10 +154,10 @@ namespace System.Reflection {
get { return m_defaultAlias; }
}
}
-
- [AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
- public sealed class AssemblyInformationalVersionAttribute : Attribute
+
+ [AttributeUsage(AttributeTargets.Assembly, Inherited = false)]
+ public sealed class AssemblyInformationalVersionAttribute : Attribute
{
private String m_informationalVersion;
@@ -169,11 +170,11 @@ namespace System.Reflection {
{
get { return m_informationalVersion; }
}
- }
-
+ }
- [AttributeUsage(AttributeTargets.Assembly, Inherited=false)]
- public sealed class AssemblyFileVersionAttribute : Attribute
+
+ [AttributeUsage(AttributeTargets.Assembly, Inherited = false)]
+ public sealed class AssemblyFileVersionAttribute : Attribute
{
private String _version;
@@ -185,16 +186,17 @@ namespace System.Reflection {
_version = version;
}
- public String Version {
+ public String Version
+ {
get { return _version; }
}
}
-
- [AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
- public unsafe sealed class AssemblyCultureAttribute : Attribute
+
+ [AttributeUsage(AttributeTargets.Assembly, Inherited = false)]
+ public unsafe sealed class AssemblyCultureAttribute : Attribute
{
- private String m_culture;
+ private String m_culture;
public AssemblyCultureAttribute(String culture)
{
@@ -208,8 +210,8 @@ namespace System.Reflection {
}
- [AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
- public unsafe sealed class AssemblyVersionAttribute : Attribute
+ [AttributeUsage(AttributeTargets.Assembly, Inherited = false)]
+ public unsafe sealed class AssemblyVersionAttribute : Attribute
{
private String m_version;
@@ -225,8 +227,8 @@ namespace System.Reflection {
}
- [AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
- public sealed class AssemblyKeyFileAttribute : Attribute
+ [AttributeUsage(AttributeTargets.Assembly, Inherited = false)]
+ public sealed class AssemblyKeyFileAttribute : Attribute
{
private String m_keyFile;
@@ -242,10 +244,10 @@ namespace System.Reflection {
}
- [AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
- public sealed class AssemblyDelaySignAttribute : Attribute
+ [AttributeUsage(AttributeTargets.Assembly, Inherited = false)]
+ public sealed class AssemblyDelaySignAttribute : Attribute
{
- private bool m_delaySign;
+ private bool m_delaySign;
public AssemblyDelaySignAttribute(bool delaySign)
{
@@ -253,20 +255,21 @@ namespace System.Reflection {
}
public bool DelaySign
- { get
+ {
+ get
{ return m_delaySign; }
}
}
- [AttributeUsage(AttributeTargets.Assembly, Inherited=false)]
+ [AttributeUsage(AttributeTargets.Assembly, Inherited = false)]
public unsafe sealed class AssemblyAlgorithmIdAttribute : Attribute
{
private uint m_algId;
public AssemblyAlgorithmIdAttribute(AssemblyHashAlgorithm algorithmId)
{
- m_algId = (uint) algorithmId;
+ m_algId = (uint)algorithmId;
}
[CLSCompliant(false)]
@@ -283,7 +286,7 @@ namespace System.Reflection {
}
- [AttributeUsage(AttributeTargets.Assembly, Inherited=false)]
+ [AttributeUsage(AttributeTargets.Assembly, Inherited = false)]
public unsafe sealed class AssemblyFlagsAttribute : Attribute
{
private AssemblyNameFlags m_flags;
@@ -320,31 +323,31 @@ namespace System.Reflection {
m_flags = assemblyFlags;
}
}
-
- [AttributeUsage(AttributeTargets.Assembly, AllowMultiple=true, Inherited=false)]
- public sealed class AssemblyMetadataAttribute : Attribute
+
+ [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)
+
+ 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;}
+ get { return m_value; }
}
- }
+ }
- [AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple=false)]
+ [AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple = false)]
public sealed class AssemblySignatureKeyAttribute : Attribute
{
private String _publicKey;
@@ -367,10 +370,10 @@ namespace System.Reflection {
}
}
- [AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
- public sealed class AssemblyKeyNameAttribute : Attribute
+ [AttributeUsage(AttributeTargets.Assembly, Inherited = false)]
+ public sealed class AssemblyKeyNameAttribute : Attribute
{
- private String m_keyName;
+ private String m_keyName;
public AssemblyKeyNameAttribute(String keyName)
{
@@ -382,6 +385,5 @@ namespace System.Reflection {
get { return m_keyName; }
}
}
-
}
diff --git a/src/mscorlib/src/System/Reflection/AssemblyName.cs b/src/mscorlib/src/System/Reflection/AssemblyName.cs
index 01be855646..202bd07655 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)
@@ -368,13 +383,13 @@ namespace System.Reflection {
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);
+ bool parse);
@@ -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)
@@ -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
index b86955efa5..dd4fc4baf4 100644
--- a/src/mscorlib/src/System/Reflection/AssemblyNameFlags.cs
+++ b/src/mscorlib/src/System/Reflection/AssemblyNameFlags.cs
@@ -14,30 +14,32 @@
**
**
===========================================================*/
-namespace System.Reflection {
-
- using System;
+
+using System;
+
+namespace System.Reflection
+{
[Serializable]
[FlagsAttribute()]
public enum AssemblyNameFlags
{
- None = 0x0000,
+ 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,
+ PublicKey = 0x0001,
//ProcArchMask = 0x00F0, // Bits describing the processor architecture
- // Accessible via AssemblyName.ProcessorArchitecture
- EnableJITcompileOptimizer = 0x4000,
- EnableJITcompileTracking = 0x8000,
- Retargetable = 0x0100,
+ // 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
+ Default = 0x0000,
+ WindowsRuntime = 0x0001
}
[Serializable]
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
index bf4545fe81..002e9e1d41 100644
--- a/src/mscorlib/src/System/Reflection/Binder.cs
+++ b/src/mscorlib/src/System/Reflection/Binder.cs
@@ -10,39 +10,41 @@
// specific semantics to the binding and invocation process.
//
//
-namespace System.Reflection {
+
+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);
-
+ 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);
-
+ 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);
-
-
+ 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);
-
+ 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 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
index ae0a6d68d3..45f7f662df 100644
--- a/src/mscorlib/src/System/Reflection/BindingFlags.cs
+++ b/src/mscorlib/src/System/Reflection/BindingFlags.cs
@@ -12,52 +12,53 @@
// process works.
//
//
-namespace System.Reflection {
-
- using System;
+
+using System;
+
+namespace System.Reflection
+{
[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,
+ 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.
-
+ 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,
+ 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,
+ PutDispProperty = 0x4000,
+ PutRefDispProperty = 0x8000,
- ExactBinding = 0x010000, // Bind with Exact Type matching, No Change type
- SuppressChangeType = 0x020000,
+ 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,
+ OptionalParamBinding = 0x040000,
// These are a couple of misc attributes used
- IgnoreReturn = 0x01000000, // This is used in COM Interop
+ 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
index 266dd55184..2fbf2f3362 100644
--- a/src/mscorlib/src/System/Reflection/CallingConventions.cs
+++ b/src/mscorlib/src/System/Reflection/CallingConventions.cs
@@ -10,19 +10,22 @@
// in the system.
//
//
-namespace System.Reflection {
- using System.Runtime.InteropServices;
- using System;
+
+using System.Runtime.InteropServices;
+using System;
+
+namespace System.Reflection
+{
[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,
+ Standard = 0x0001,
+ VarArgs = 0x0002,
+ Any = Standard | VarArgs,
+ HasThis = 0x0020,
+ ExplicitThis = 0x0040,
}
}
diff --git a/src/mscorlib/src/System/Reflection/ConstructorInfo.cs b/src/mscorlib/src/System/Reflection/ConstructorInfo.cs
index c3198ae82d..6249a6a1c9 100644
--- a/src/mscorlib/src/System/Reflection/ConstructorInfo.cs
+++ b/src/mscorlib/src/System/Reflection/ConstructorInfo.cs
@@ -69,7 +69,7 @@ namespace System.Reflection
#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
@@ -119,9 +119,9 @@ namespace System.Reflection
if (rtAssembly.IsFrameworkAssembly())
{
int ctorToken = rtAssembly.InvocableAttributeCtorToken;
- if (System.Reflection.MetadataToken.IsNullToken(ctorToken) ||
+ if (System.Reflection.MetadataToken.IsNullToken(ctorToken) ||
!CustomAttribute.IsAttributeDefined(GetRuntimeModule(), MetadataToken, ctorToken))
- return true;
+ return true;
}
if (GetRuntimeType().IsNonW8PFrameworkAPI())
@@ -143,7 +143,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 +160,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;
@@ -233,21 +233,21 @@ 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)
+ if (target == null)
throw new TargetException(Environment.GetResourceString("RFLCT.Targ_StatMethReqTarg"));
throw new TargetException(Environment.GetResourceString("RFLCT.Targ_ITargMismatch"));
@@ -258,7 +258,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 +282,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(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType));
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
}
@@ -296,12 +296,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(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType));
return CustomAttribute.IsDefined(this, attributeRuntimeType);
}
-
+
public override IList<CustomAttributeData> GetCustomAttributesData()
{
return CustomAttributeData.GetCustomAttributesInternal(this);
@@ -315,12 +315,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 +349,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 +366,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,7 +377,7 @@ namespace System.Reflection
return RuntimeMethodHandle.GetImplAttributes(this);
}
- public override RuntimeMethodHandle MethodHandle
+ public override RuntimeMethodHandle MethodHandle
{
get
{
@@ -388,7 +388,7 @@ namespace System.Reflection
}
}
- public override MethodAttributes Attributes
+ public override MethodAttributes Attributes
{
get
{
@@ -396,7 +396,7 @@ namespace System.Reflection
}
}
- public override CallingConventions CallingConvention
+ public override CallingConventions CallingConvention
{
get
{
@@ -409,29 +409,29 @@ 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"));
-
+
// ctor is declared on interface class
else if (declaringType.IsInterface)
throw new MemberAccessException(
String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("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));
-
+
// 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)
{
@@ -451,7 +451,7 @@ namespace System.Reflection
// ctor is .cctor
if ((Attributes & MethodAttributes.Static) == MethodAttributes.Static)
throw new MemberAccessException(Environment.GetResourceString("Acc_NotClassInit"));
-
+
throw new TargetException();
}
@@ -463,14 +463,14 @@ namespace System.Reflection
{
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)
+ if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
RuntimeAssembly caller = RuntimeAssembly.GetExecutingAssembly(ref stackMark);
@@ -490,17 +490,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"));
-
+
// 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 +510,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;
}
@@ -549,12 +549,12 @@ namespace System.Reflection
// 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)
+ if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
RuntimeAssembly caller = RuntimeAssembly.GetExecutingAssembly(ref stackMark);
@@ -567,7 +567,7 @@ namespace System.Reflection
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"));
@@ -575,19 +575,19 @@ namespace System.Reflection
// JIT/NGen will insert the call to .cctor in the instance ctor.
// if we are here we passed all the previous checks. Time to look at the arguments
- 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)
{
@@ -609,6 +609,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/CustomAttribute.cs b/src/mscorlib/src/System/Reflection/CustomAttribute.cs
index b71c7bbff3..c12187d7c8 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
@@ -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
@@ -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,7 +729,7 @@ namespace System.Reflection
case (CustomAttributeEncoding.Object):
return typeof(object);
- default :
+ default:
throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)encodedType), nameof(encodedType));
}
}
@@ -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,7 +1278,7 @@ namespace System.Reflection
Contract.Requires(type != null);
Contract.Requires(caType != null);
- if (type.GetElementType() != null)
+ if (type.GetElementType() != null)
return (caType.IsValueType) ? EmptyArray<Object>.Value : CreateAttributeArrayHelper(caType, 0);
if (type.IsGenericType && !type.IsGenericTypeDefinition)
@@ -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);
@@ -1577,7 +1576,7 @@ 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)
@@ -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);
@@ -1707,7 +1705,7 @@ namespace System.Reflection
}
RuntimeMethodInfo setMethod = property.GetSetMethod(true) as RuntimeMethodInfo;
-
+
// Public properties may have non-public setter methods
if (!setMethod.IsPublic)
continue;
@@ -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.");
}
@@ -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
index 9aee911a6c..83ef54138e 100644
--- a/src/mscorlib/src/System/Reflection/CustomAttributeFormatException.cs
+++ b/src/mscorlib/src/System/Reflection/CustomAttributeFormatException.cs
@@ -10,28 +10,33 @@
// custom attribute is invalid.
//
//
-namespace System.Reflection {
+
+namespace System.Reflection
+{
using System;
using ApplicationException = System.ApplicationException;
using System.Runtime.Serialization;
[Serializable]
- public class CustomAttributeFormatException : FormatException {
-
+ public class CustomAttributeFormatException : FormatException
+ {
public CustomAttributeFormatException()
- : base(Environment.GetResourceString("Arg_CustomAttributeFormatException")) {
+ : base(Environment.GetResourceString("Arg_CustomAttributeFormatException"))
+ {
SetErrorCode(__HResults.COR_E_CUSTOMATTRIBUTEFORMAT);
}
-
- public CustomAttributeFormatException(String message) : base(message) {
+
+ public CustomAttributeFormatException(String message) : base(message)
+ {
SetErrorCode(__HResults.COR_E_CUSTOMATTRIBUTEFORMAT);
}
-
- public CustomAttributeFormatException(String message, Exception inner) : base(message, inner) {
+
+ public CustomAttributeFormatException(String message, Exception inner) : base(message, inner)
+ {
SetErrorCode(__HResults.COR_E_CUSTOMATTRIBUTEFORMAT);
}
- protected CustomAttributeFormatException(SerializationInfo info, StreamingContext context) : base(info, context) {
+ 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
index 4232fcd2a1..3a0fdbf48d 100644
--- a/src/mscorlib/src/System/Reflection/DefaultMemberAttribute.cs
+++ b/src/mscorlib/src/System/Reflection/DefaultMemberAttribute.cs
@@ -13,11 +13,12 @@
//
//
//
-namespace System.Reflection {
-
- using System;
-[Serializable]
+using System;
+
+namespace System.Reflection
+{
+ [Serializable]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface)]
public sealed class DefaultMemberAttribute : Attribute
{
@@ -25,15 +26,17 @@ namespace System.Reflection {
private String m_memberName;
// You must provide the name of the member, this is required
- public DefaultMemberAttribute(String memberName) {
+ 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;}
+ 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..6d77843efb 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,7 +100,7 @@ namespace System.Reflection.Emit
{
if (elementType.HasElementType)
AddElementType(elementType.GetElementType());
-
+
if (elementType.IsPointer)
AddPointer();
@@ -113,7 +113,7 @@ namespace System.Reflection.Emit
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 8ab5088272..ca273d65d1 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.
@@ -186,7 +186,7 @@ namespace System.Reflection.Emit
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)
@@ -328,7 +328,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.
@@ -424,7 +424,7 @@ namespace System.Reflection.Emit
**********************************************/
[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);
@@ -434,29 +434,29 @@ namespace System.Reflection.Emit
[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)
@@ -489,7 +489,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);
@@ -509,14 +509,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);
}
@@ -525,7 +525,7 @@ namespace System.Reflection.Emit
{
if (types == null)
return;
-
+
foreach (Type type in types)
{
if (type == null)
@@ -582,27 +582,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);
@@ -623,7 +623,7 @@ namespace System.Reflection.Emit
return InternalAssembly.ImageRuntimeVersion;
}
}
-
+
public override String CodeBase
{
get
@@ -634,9 +634,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;
}
@@ -735,7 +735,8 @@ namespace System.Reflection.Emit
public override bool IsDynamic
{
- get {
+ get
+ {
return true;
}
}
@@ -748,16 +749,16 @@ 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));
@@ -769,7 +770,7 @@ namespace System.Reflection.Emit
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;
@@ -789,8 +790,8 @@ namespace System.Reflection.Emit
if (binaryAttribute == null)
throw new ArgumentNullException(nameof(binaryAttribute));
Contract.EndContractBlock();
-
- lock(SyncRoot)
+
+ lock (SyncRoot)
{
SetCustomAttributeNoLock(con, binaryAttribute);
}
@@ -825,7 +826,7 @@ namespace System.Reflection.Emit
}
Contract.EndContractBlock();
- lock(SyncRoot)
+ lock (SyncRoot)
{
SetCustomAttributeNoLock(customBuilder);
}
@@ -834,7 +835,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
@@ -849,11 +850,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 e52135e6dc..ead2fafcef 100644
--- a/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderAccess.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderAccess.cs
@@ -7,7 +7,7 @@ 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]
diff --git a/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderData.cs b/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderData.cs
index 7ac9daeac0..a2fb2b602c 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);
@@ -124,57 +123,56 @@ namespace System.Reflection.Emit {
// throw new ArgumentException(Environment.GetResourceString("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..185d2041a2 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(Environment.GetResourceString("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(Environment.GetResourceString("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,15 +171,15 @@ 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"));
return m_methodBuilder.GetILGenerator();
}
-
+
public ILGenerator GetILGenerator(int streamSize)
{
if (m_isDefaultConstructor)
@@ -188,33 +188,33 @@ namespace System.Reflection.Emit
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..cbc73455ed 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
@@ -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);
@@ -527,7 +528,7 @@ namespace System.Reflection.Emit {
// If we allow this we will get into an infinite recursion
if (ot == typeof(object))
throw new ArgumentException(Environment.GetResourceString("Argument_BadParameterTypeForCAB", ot.ToString()));
-
+
EmitType(writer, ot);
EmitValue(writer, ot, value);
}
@@ -537,13 +538,13 @@ namespace System.Reflection.Emit {
if (value != null)
typename = value.GetType().ToString();
-
+
throw new ArgumentException(Environment.GetResourceString("Argument_BadParameterTypeForCAB", typename));
}
}
-
-
+
+
// return the byte interpretation of the custom attribute
internal void CreateCustomAttribute(ModuleBuilder mod, int tkOwner)
@@ -556,12 +557,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..f0a5945034 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;
@@ -962,8 +960,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
}
@@ -1119,5 +1117,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 b7f76b90aa..9aae25c715 100644
--- a/src/mscorlib/src/System/Reflection/Emit/DynamicMethod.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/DynamicMethod.cs
@@ -58,7 +58,7 @@ 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)
//
@@ -72,10 +72,10 @@ namespace System.Reflection.Emit
{
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
@@ -105,10 +105,11 @@ namespace System.Reflection.Emit
}
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
- public DynamicMethod(string name,
- Type returnType,
- Type[] parameterTypes,
- Module m) {
+ public DynamicMethod(string name,
+ Type returnType,
+ Type[] parameterTypes,
+ Module m)
+ {
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
PerformSecurityCheck(m, ref stackMark, false);
Init(name,
@@ -124,11 +125,12 @@ namespace System.Reflection.Emit
}
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
- public DynamicMethod(string name,
- Type returnType,
- Type[] parameterTypes,
- Module m,
- bool skipVisibility) {
+ public DynamicMethod(string name,
+ Type returnType,
+ Type[] parameterTypes,
+ Module m,
+ bool skipVisibility)
+ {
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
PerformSecurityCheck(m, ref stackMark, skipVisibility);
Init(name,
@@ -144,13 +146,14 @@ namespace System.Reflection.Emit
}
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
- public DynamicMethod(string name,
- MethodAttributes attributes,
- CallingConventions callingConvention,
- Type returnType,
- Type[] parameterTypes,
- Module m,
- bool skipVisibility) {
+ 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);
Init(name,
@@ -166,16 +169,17 @@ namespace System.Reflection.Emit
}
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
- public DynamicMethod(string name,
- Type returnType,
- Type[] parameterTypes,
- Type owner) {
+ 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,
+ Init(name,
+ MethodAttributes.Public | MethodAttributes.Static,
+ CallingConventions.Standard,
+ returnType,
parameterTypes,
owner, // owner
null, // m
@@ -183,52 +187,55 @@ namespace System.Reflection.Emit
false,
ref stackMark); // transparentMethod
}
-
+
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
- public DynamicMethod(string name,
- Type returnType,
- Type[] parameterTypes,
- Type owner,
- bool skipVisibility) {
+ 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,
+ Init(name,
+ MethodAttributes.Public | MethodAttributes.Static,
+ CallingConventions.Standard,
+ returnType,
+ parameterTypes,
owner, // owner
null, // m
skipVisibility,
false,
ref stackMark); // transparentMethod
}
-
+
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
- public DynamicMethod(string name,
- MethodAttributes attributes,
- CallingConventions callingConvention,
- Type returnType,
- Type[] parameterTypes,
- Type owner,
- bool skipVisibility) {
+ 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,
+ Init(name,
+ attributes,
+ callingConvention,
+ returnType,
+ parameterTypes,
owner, // owner
null, // m
- skipVisibility,
+ skipVisibility,
false,
ref stackMark); // transparentMethod
}
// 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"));
@@ -239,7 +246,7 @@ namespace System.Reflection.Emit
// only standard or varargs supported
if (callingConvention != CallingConventions.Standard && callingConvention != CallingConventions.VarArgs)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicMethodFlags"));
-
+
// vararg is not supported at the moment
if (callingConvention == CallingConventions.VarArgs)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicMethodFlags"));
@@ -283,13 +290,13 @@ 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)
@@ -297,23 +304,26 @@ namespace System.Reflection.Emit
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)
+ for (int i = 0; i < signature.Length; i++)
+ {
+ if (signature[i] == null)
throw new ArgumentException(Environment.GetResourceString("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) )
+ if (m_parameterTypes[i] == null || !(m_parameterTypes[i] is RuntimeType) || m_parameterTypes[i] == (RuntimeType)typeof(void))
throw new ArgumentException(Environment.GetResourceString("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 )
+ if ((m_returnType == null) || !(m_returnType is RuntimeType) || m_returnType.IsByRef)
throw new NotSupportedException(Environment.GetResourceString("Arg_InvalidTypeInRetType"));
if (transparentMethod)
@@ -324,7 +334,6 @@ namespace System.Reflection.Emit
{
m_restrictedSkipVisibility = true;
}
-
}
else
{
@@ -359,7 +368,7 @@ namespace System.Reflection.Emit
m_fInitLocals = true;
m_methodHandle = null;
- if (name == null)
+ if (name == null)
throw new ArgumentNullException(nameof(name));
#if FEATURE_APPX
@@ -378,7 +387,7 @@ namespace System.Reflection.Emit
private void PerformSecurityCheck(Module m, ref StackCrawlMark stackMark, bool skipVisibility)
{
- if (m == null)
+ if (m == null)
throw new ArgumentNullException(nameof(m));
Contract.EndContractBlock();
}
@@ -393,7 +402,8 @@ namespace System.Reflection.Emit
// 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 +417,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
@@ -438,16 +449,21 @@ namespace System.Reflection.Emit
#endif
// This is guaranteed to return a valid handle
- internal unsafe RuntimeMethodHandle GetMethodDescriptor() {
- if (m_methodHandle == null) {
- lock (this) {
- if (m_methodHandle == null) {
+ internal unsafe RuntimeMethodHandle GetMethodDescriptor()
+ {
+ 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));
-
+
m_ilGenerator.GetCallableMethod(m_module, this);
}
}
@@ -508,7 +524,8 @@ 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"));
Contract.EndContractBlock();
@@ -554,7 +571,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,12 +588,14 @@ 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"));
position--; // it's 1 based. 0 is the return value
-
- if (position >= 0) {
+
+ if (position >= 0)
+ {
ParameterInfo[] parameters = m_dynMethod.LoadParameters();
parameters[position].SetName(parameterName);
parameters[position].SetAttributes(attributes);
@@ -584,11 +603,12 @@ namespace System.Reflection.Emit
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 +619,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,78 +642,91 @@ 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 ParameterInfo[] 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(Environment.GetResourceString("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.
@@ -701,28 +736,31 @@ namespace System.Reflection.Emit
throw new ArgumentException(Environment.GetResourceString("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;
}
- 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 +789,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 +803,49 @@ namespace System.Reflection.Emit
// private implementation
//
- internal ParameterInfo[] LoadParameters() {
- if (m_parameters == null) {
+ internal ParameterInfo[] 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++)
+ 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) {
+ Object[] ICustomAttributeProvider.GetCustomAttributes(Type attributeType, bool inherit)
+ {
return EmptyArray<Object>.Value;
}
- Object[] ICustomAttributeProvider.GetCustomAttributes(bool inherit) {
+ Object[] ICustomAttributeProvider.GetCustomAttributes(bool inherit)
+ {
return EmptyArray<Object>.Value;
}
- 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..88b85e578b 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"));
}
-
+
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,12 @@ namespace System.Reflection.Emit {
{
return m_typeBuilder.GetEvents(bindingAttr);
}
-
+
protected override TypeAttributes GetAttributeFlagsImpl()
{
return m_typeBuilder.Attributes;
}
-
+
protected override bool IsArrayImpl()
{
return false;
@@ -236,7 +251,7 @@ namespace System.Reflection.Emit {
return false;
}
- protected override bool IsValueTypeImpl()
+ protected override bool IsValueTypeImpl()
{
return true;
}
@@ -250,7 +265,7 @@ namespace System.Reflection.Emit {
{
return false;
}
-
+
protected override bool IsCOMObjectImpl()
{
return false;
@@ -290,7 +305,7 @@ namespace System.Reflection.Emit {
return GetEnumUnderlyingType();
}
}
-
+
//ICustomAttributeProvider
public override Object[] GetCustomAttributes(bool inherit)
{
@@ -303,64 +318,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 +387,9 @@ namespace System.Reflection.Emit {
{
szrank = "*";
}
- else
+ else
{
- for(int i = 1; i < rank; i++)
+ for (int i = 1; i < rank; i++)
szrank += ",";
}
@@ -380,14 +397,14 @@ 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)
@@ -403,7 +420,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..ae28212732 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,7 +24,7 @@ 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)
@@ -47,13 +47,13 @@ namespace System.Reflection.Emit
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,13 +110,13 @@ 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.
@@ -124,8 +124,8 @@ namespace System.Reflection.Emit
throw new NotSupportedException(Environment.GetResourceString("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.
@@ -133,12 +133,12 @@ namespace System.Reflection.Emit
throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
}
- public override RuntimeFieldHandle FieldHandle
+ public override RuntimeFieldHandle FieldHandle
{
get { throw new NotSupportedException(Environment.GetResourceString("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"));
}
-
+
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
-
throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
}
public override bool IsDefined(Type attributeType, bool inherit)
{
-
throw new NotSupportedException(Environment.GetResourceString("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..475a4a5bde 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(); }
@@ -209,7 +210,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..fe32417b2e 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);
@@ -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(Environment.GetResourceString("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));
}
-
+
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,7 +340,7 @@ 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"));
@@ -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,16 +488,16 @@ 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)
@@ -507,7 +507,7 @@ namespace System.Reflection.Emit
}
}
- ModuleBuilder modBuilder = (ModuleBuilder) m_methodBuilder.Module;
+ ModuleBuilder modBuilder = (ModuleBuilder)m_methodBuilder.Module;
sig = GetMemberRefSignature(callingConvention,
returnType,
parameterTypes,
@@ -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);
@@ -802,7 +809,7 @@ namespace System.Reflection.Emit
// 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,13 +859,13 @@ 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
{
@@ -867,13 +874,13 @@ namespace System.Reflection.Emit
{
throw new InvalidOperationException(Environment.GetResourceString("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) {
+ public virtual void EndExceptionBlock()
+ {
+ if (m_currExcStackCount == 0)
+ {
throw new NotSupportedException(Environment.GetResourceString("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"));
}
- 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"));
- __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) {
+ if (m_currExcStackCount == 0)
+ {
throw new NotSupportedException(Environment.GetResourceString("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) {
+ if (current.GetCurrentState() == __ExceptionInfo.State_Filter)
+ {
+ if (exceptionType != null)
+ {
throw new ArgumentException(Environment.GetResourceString("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) {
+ if (m_currExcStackCount == 0)
+ {
throw new NotSupportedException(Environment.GetResourceString("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) {
+ if (m_currExcStackCount == 0)
+ {
throw new NotSupportedException(Environment.GetResourceString("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(Environment.GetResourceString("Argument_InvalidLabel"));
}
- if (m_labelList[labelIndex]!=-1) {
- throw new ArgumentException (Environment.GetResourceString("Argument_RedefinedLabel"));
+ if (m_labelList[labelIndex] != -1)
+ {
+ throw new ArgumentException(Environment.GetResourceString("Argument_RedefinedLabel"));
}
- m_labelList[labelIndex]=m_length;
+ m_labelList[labelIndex] = m_length;
}
#endregion
@@ -1089,16 +1115,19 @@ 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)) {
+ if (!excType.IsSubclassOf(typeof(Exception)) && excType != typeof(Exception))
+ {
throw new ArgumentException(Environment.GetResourceString("Argument_NotExceptionType"));
}
Contract.EndContractBlock();
ConstructorInfo con = excType.GetConstructor(Type.EmptyTypes);
- if (con==null) {
+ if (con == null)
+ {
throw new ArgumentException(Environment.GetResourceString("Argument_MissingDefaultConstructor"));
}
this.Emit(OpCodes.Newobj, con);
@@ -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,15 +1152,15 @@ 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"));
}
@@ -1141,12 +1170,14 @@ namespace System.Reflection.Emit
Emit(OpCodes.Ldloc, localBuilder);
Type[] parameterTypes = new Type[1];
cls = localBuilder.LocalType;
- if (cls is TypeBuilder || cls is EnumBuilder) {
+ if (cls is TypeBuilder || cls is EnumBuilder)
+ {
throw new ArgumentException(Environment.GetResourceString("NotSupported_OutputStreamUsingTypeBuilder"));
}
parameterTypes[0] = (Type)cls;
MethodInfo mi = prop.ReturnType.GetMethod("WriteLine", parameterTypes);
- if (mi==null) {
+ if (mi == null)
+ {
throw new ArgumentException(Environment.GetResourceString("Argument_EmitWriteLineType"), nameof(localBuilder));
}
@@ -1167,24 +1198,29 @@ 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) {
+ if (cls is TypeBuilder || cls is EnumBuilder)
+ {
throw new NotSupportedException(Environment.GetResourceString("NotSupported_OutputStreamUsingTypeBuilder"));
}
parameterTypes[0] = (Type)cls;
MethodInfo mi = prop.ReturnType.GetMethod("WriteLine", parameterTypes);
- if (mi==null) {
+ if (mi == null)
+ {
throw new ArgumentException(Environment.GetResourceString("Argument_EmitWriteLineType"), nameof(fld));
}
Emit(OpCodes.Callvirt, mi);
@@ -1203,10 +1239,10 @@ 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())
@@ -1215,11 +1251,13 @@ namespace System.Reflection.Emit
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TypeHasBeenCreated"));
}
- if (localType==null) {
+ if (localType == null)
+ {
throw new ArgumentNullException(nameof(localType));
}
- if (methodBuilder.m_bIsBaked) {
+ if (methodBuilder.m_bIsBaked)
+ {
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_MethodBaked"));
}
@@ -1245,7 +1283,7 @@ namespace System.Reflection.Emit
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) {
+ internal void MarkFinallyAddr(int finallyAddr, int endCatchAddr)
+ {
+ if (m_endFinally != -1)
+ {
throw new ArgumentException(Environment.GetResourceString("Argument_TooManyFinallyClause"));
- } else {
+ }
+ 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"));
}
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..42165075b4 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"));
}
-
+
// 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"));
}
-
+
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..ee4c68ebf4 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,7 +77,7 @@ 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)
@@ -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));
@@ -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(Environment.GetResourceString("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,16 +197,16 @@ 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();
@@ -223,7 +223,7 @@ namespace System.Reflection.Emit
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadILGeneratorUsage"));
}
-
+
ThrowIfShouldNotHaveBody();
if (il.m_ScopeTree.m_iOpenScopeCount != 0)
@@ -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,7 +328,7 @@ namespace System.Reflection.Emit
m_ubBody = null;
m_localSymInfo = null;
m_mdMethodFixups = null;
- m_localSignature = null;
+ m_localSignature = null;
m_exceptions = null;
}
@@ -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();
}
@@ -379,7 +377,7 @@ namespace System.Reflection.Emit
if (m_parameterTypes == null)
m_parameterTypes = EmptyArray<Type>.Value;
- 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;
}
@@ -571,7 +574,7 @@ namespace System.Reflection.Emit
public override CallingConventions CallingConvention
{
- get {return m_callingConvention;}
+ get { return m_callingConvention; }
}
public override RuntimeMethodHandle MethodHandle
@@ -637,19 +640,16 @@ namespace System.Reflection.Emit
#region ICustomAttributeProvider Implementation
public override Object[] GetCustomAttributes(bool inherit)
{
-
throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
}
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
-
throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
}
public override bool IsDefined(Type attributeType, bool inherit)
{
-
throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
}
@@ -663,16 +663,16 @@ 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));
@@ -684,7 +684,7 @@ namespace System.Reflection.Emit
if (m_inst != null)
throw new InvalidOperationException(Environment.GetResourceString("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));
@@ -693,13 +693,13 @@ namespace System.Reflection.Emit
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,7 +820,7 @@ namespace System.Reflection.Emit
m_parameterTypeOptionalCustomModifiers = parameterTypeOptionalCustomModifiers;
}
-
+
public ParameterBuilder DefineParameter(int position, ParameterAttributes attributes, String strParamName)
{
if (position < 0)
@@ -828,7 +828,7 @@ namespace System.Reflection.Emit
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"));
@@ -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 ||
@@ -890,13 +893,13 @@ namespace System.Reflection.Emit
throw new InvalidOperationException(Environment.GetResourceString("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..ad5cc70a30 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,7 +57,7 @@ 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 MethodAttributes Attributes { get { return m_method.Attributes; } }
@@ -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(Environment.GetResourceString("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..2d1920338d 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;
@@ -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);
@@ -218,7 +217,7 @@ namespace System.Reflection.Emit
{
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));
+ throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtField.FullName));
}
#endif
@@ -315,7 +314,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 +323,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
@@ -369,8 +368,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 +394,7 @@ namespace System.Reflection.Emit
#endregion
#region Module Overrides
-
+
// m_internalModuleBuilder is null iff this is a "internal" ModuleBuilder
internal InternalModuleBuilder InternalModule
{
@@ -532,7 +531,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 +543,8 @@ namespace System.Reflection.Emit
}
}
- if (optionalParameterTypes != null) {
+ if (optionalParameterTypes != null)
+ {
int i = 0;
foreach (Type type in optionalParameterTypes)
{
@@ -599,7 +599,7 @@ namespace System.Reflection.Emit
public override Type[] GetTypes()
{
- lock(SyncRoot)
+ lock (SyncRoot)
{
return GetTypesNoLock();
}
@@ -620,7 +620,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 +636,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 +658,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 +674,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 +709,7 @@ namespace System.Reflection.Emit
parameters = null;
}
- baseName = baseName.Replace(@"\\",@"\").Replace(@"\[",@"[").Replace(@"\*",@"*").Replace(@"\&",@"&");
+ baseName = baseName.Replace(@"\\", @"\").Replace(@"\[", @"[").Replace(@"\*", @"*").Replace(@"\&", @"&");
if (parameters != null)
{
@@ -742,9 +742,9 @@ namespace System.Reflection.Emit
return null;
}
- if (parameters == null)
+ if (parameters == null)
return baseType;
-
+
return GetType(parameters, baseType);
}
@@ -885,7 +885,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 +895,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 +905,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 +918,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 +938,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 +955,7 @@ namespace System.Reflection.Emit
{
Contract.Ensures(Contract.Result<TypeBuilder>() != null);
- lock(SyncRoot)
+ lock (SyncRoot)
{
return DefineTypeNoLock(name, attr, parent, packsize);
}
@@ -979,7 +979,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 +1006,7 @@ namespace System.Reflection.Emit
return new EnumBuilder(name, underlyingType, visibility, this);
}
-
+
#endregion
#region Define Resource
@@ -1021,7 +1021,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,31 +1029,31 @@ 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"));
-
+
if (name == null)
throw new ArgumentNullException(nameof(name));
if (name.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name));
-
+
if ((attributes & MethodAttributes.Static) == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_GlobalFunctionHasToBeStatic"));
Contract.Ensures(Contract.Result<MethodBuilder>() != null);
@@ -1066,14 +1066,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();
}
@@ -1089,7 +1089,7 @@ namespace System.Reflection.Emit
m_moduleData.m_globalTypeBuilder.CreateType();
m_moduleData.m_fGlobalBeenCreated = true;
}
-
+
#endregion
#region Define Data
@@ -1101,7 +1101,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);
}
@@ -1118,16 +1118,16 @@ namespace System.Reflection.Emit
}
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);
}
@@ -1145,11 +1145,11 @@ namespace System.Reflection.Emit
}
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 +1164,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 +1182,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,
@@ -1231,10 +1231,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 +1258,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 +1280,7 @@ namespace System.Reflection.Emit
internal MethodToken GetMethodTokenInternal(MethodInfo method)
{
- lock(SyncRoot)
+ lock (SyncRoot)
{
return GetMethodTokenNoLock(method, false);
}
@@ -1300,11 +1300,11 @@ 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))
@@ -1343,15 +1343,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 +1372,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 +1464,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)
@@ -1487,7 +1487,7 @@ namespace System.Reflection.Emit
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(methodName));
if (arrayClass.IsArray == false)
- throw new ArgumentException(Environment.GetResourceString("Argument_HasToBeArrayClass"));
+ throw new ArgumentException(Environment.GetResourceString("Argument_HasToBeArrayClass"));
Contract.EndContractBlock();
CheckContext(returnType, arrayClass);
@@ -1509,7 +1509,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 +1531,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;
@@ -1578,16 +1579,16 @@ namespace System.Reflection.Emit
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"));
}
-
+
if (field.DeclaringType != null && field.DeclaringType.IsGenericType)
{
int length;
@@ -1597,11 +1598,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 +1624,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 +1640,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 +1654,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 +1670,7 @@ namespace System.Reflection.Emit
return new SignatureToken(TypeBuilder.GetTokenFromSig(GetNativeHandle(), localSigBytes, sigLength), this);
}
-
+
#endregion
#region Other
@@ -1681,7 +1682,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 +1743,7 @@ namespace System.Reflection.Emit
throw new ArgumentNullException(nameof(url));
Contract.EndContractBlock();
- lock(SyncRoot)
+ lock (SyncRoot)
{
return DefineDocumentNoLock(url, language, languageVendor, documentType);
}
@@ -1758,7 +1759,7 @@ namespace System.Reflection.Emit
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..c0af6ba7db 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.
@@ -52,19 +52,19 @@ namespace System.Reflection.Emit
}
}
- 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..da087dcea7 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,21 +26,20 @@ 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));
@@ -48,7 +48,7 @@ namespace System.Reflection.Emit {
if (name[0] == '\0')
throw new ArgumentException(Environment.GetResourceString("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,22 +151,22 @@ 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"));
}
- 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"));
}
- 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"));
}
- 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"));
}
@@ -201,18 +201,23 @@ namespace System.Reflection.Emit {
throw new NotSupportedException(Environment.GetResourceString("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; }
}
@@ -226,33 +231,36 @@ namespace System.Reflection.Emit {
throw new NotSupportedException(Environment.GetResourceString("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"));
}
- 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..6e1429beda 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(Environment.GetResourceString("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)
+ if (callingConvention == MdSigCallingConvention.Field)
throw new ArgumentException(Environment.GetResourceString("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,7 +244,7 @@ namespace System.Reflection.Emit
m_sigDone = false;
m_sizeLoc = NO_SIZE_IN_SIG;
- if (m_module == null && mod != null)
+ if (m_module == null && mod != null)
throw new ArgumentException(Environment.GetResourceString("NotSupported_MustBeModuleBuilder"));
}
@@ -252,23 +252,23 @@ namespace System.Reflection.Emit
{
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++;
}
}
@@ -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"));
- }
-
+ }
}
-
+
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"));
}
-
- 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"));
// 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,7 +780,7 @@ 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))
@@ -792,10 +791,10 @@ namespace System.Reflection.Emit
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]);
}
}
@@ -805,12 +804,12 @@ namespace System.Reflection.Emit
{
if (m_sigDone)
throw new ArgumentException(Environment.GetResourceString("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..d82e271672 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 = EmptyArray<Type>.Value;
}
-
+
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
@@ -101,23 +101,23 @@ namespace System.Reflection.Emit
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_SymbolMethod"));
}
-
+
public override MethodImplAttributes GetMethodImplementationFlags()
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_SymbolMethod"));
}
-
- public override MethodAttributes Attributes
+
+ public override MethodAttributes Attributes
{
get { throw new NotSupportedException(Environment.GetResourceString("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")); }
}
@@ -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"));
}
-
+
public override MethodInfo GetBaseDefinition()
{
return this;
@@ -154,7 +154,7 @@ namespace System.Reflection.Emit
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_SymbolMethod"));
}
-
+
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_SymbolMethod"));
@@ -164,7 +164,7 @@ namespace System.Reflection.Emit
{
throw new NotSupportedException(Environment.GetResourceString("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..470d69fa55 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,7 +63,7 @@ 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"));
@@ -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 ".."
@@ -179,7 +179,7 @@ namespace System.Reflection.Emit
throw new ArgumentException(Environment.GetResourceString("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,36 @@ namespace System.Reflection.Emit
m_format = format.Substring(curIndex, length);
}
#endregion
-
+
#region Type Overrides
- internal override bool IsSzArray
- {
- get
- {
+ internal override bool IsSzArray
+ {
+ get
+ {
if (m_cRank > 1)
return false;
-
+
return 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 +308,9 @@ namespace System.Reflection.Emit
{
szrank = "*";
}
- else
+ else
{
- for(int i = 1; i < rank; i++)
+ for (int i = 1; i < rank; i++)
szrank += ",";
}
@@ -327,50 +327,50 @@ namespace System.Reflection.Emit
return m_cRank;
}
-
- public override Guid GUID
+
+ public override Guid GUID
{
get { throw new NotSupportedException(Environment.GetResourceString("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(Environment.GetResourceString("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(Environment.GetResourceString("NotSupported_NonReflectedType")); }
}
-
- public override String Name
+
+ public override String Name
{
- get
- {
+ get
+ {
Type baseType;
String sFormat = m_format;
@@ -380,140 +380,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(Environment.GetResourceString("NotSupported_NonReflectedType"));
}
-
+
public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
+ throw new NotSupportedException(Environment.GetResourceString("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(Environment.GetResourceString("NotSupported_NonReflectedType"));
}
-
+
public override MethodInfo[] GetMethods(BindingFlags bindingAttr)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
+ throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
}
-
+
public override FieldInfo GetField(String name, BindingFlags bindingAttr)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
+ throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
}
-
+
public override FieldInfo[] GetFields(BindingFlags bindingAttr)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
+ throw new NotSupportedException(Environment.GetResourceString("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(Environment.GetResourceString("NotSupported_NonReflectedType"));
}
-
+
public override Type[] GetInterfaces()
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
+ throw new NotSupportedException(Environment.GetResourceString("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(Environment.GetResourceString("NotSupported_NonReflectedType"));
}
-
+
public override EventInfo[] GetEvents()
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
+ throw new NotSupportedException(Environment.GetResourceString("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(Environment.GetResourceString("NotSupported_NonReflectedType"));
}
-
+
public override PropertyInfo[] GetProperties(BindingFlags bindingAttr)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
+ throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
}
public override Type[] GetNestedTypes(BindingFlags bindingAttr)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
+ throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
}
-
+
public override Type GetNestedType(String name, BindingFlags bindingAttr)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
+ throw new NotSupportedException(Environment.GetResourceString("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(Environment.GetResourceString("NotSupported_NonReflectedType"));
}
-
+
public override MemberInfo[] GetMembers(BindingFlags bindingAttr)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
+ throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
}
public override InterfaceMapping GetInterfaceMap(Type interfaceType)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
+ throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
}
public override EventInfo[] GetEvents(BindingFlags bindingAttr)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
+ throw new NotSupportedException(Environment.GetResourceString("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 +532,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 +555,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(Environment.GetResourceString("NotSupported_NonReflectedType"));
}
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
+ throw new NotSupportedException(Environment.GetResourceString("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(Environment.GetResourceString("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..ed821d8c90 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,7 +85,7 @@ namespace System.Reflection.Emit {
}
}
#endregion
-
+
#region Public Static Methods
public static MethodInfo GetMethod(Type type, MethodInfo method)
{
@@ -96,13 +98,13 @@ 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));
-
+
if (method.DeclaringType == null || !method.DeclaringType.IsGenericTypeDefinition)
throw new ArgumentException(Environment.GetResourceString("Argument_MethodNeedGenericDeclaringType"), nameof(method));
-
+
if (type.GetGenericTypeDefinition() != method.DeclaringType)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidMethodDeclaringType"), nameof(type));
Contract.EndContractBlock();
@@ -112,21 +114,21 @@ 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));
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"));
if (!constructor.DeclaringType.IsGenericTypeDefinition)
throw new ArgumentException(Environment.GetResourceString("Argument_ConstructorNeedGenericDeclaringType"), nameof(constructor));
Contract.EndContractBlock();
-
+
if (!(type is TypeBuilderInstantiation))
throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), nameof(type));
@@ -147,7 +149,7 @@ namespace System.Reflection.Emit {
if (!field.DeclaringType.IsGenericTypeDefinition)
throw new ArgumentException(Environment.GetResourceString("Argument_FieldNeedGenericDeclaringType"), nameof(field));
Contract.EndContractBlock();
-
+
if (!(type is TypeBuilderInstantiation))
throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), nameof(type));
@@ -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)
@@ -379,7 +381,7 @@ namespace System.Reflection.Emit {
if (!destType.IsAssignableFrom(type))
throw new ArgumentException(Environment.GetResourceString("Argument_ConstantDoesntMatch"));
}
-
+
CorElementType corType = RuntimeTypeHandle.GetCorElementType((RuntimeType)type);
switch (corType)
@@ -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);
@@ -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))
+ if (((attr & TypeAttributes.VisibilityMask) == TypeAttributes.Public) || ((attr & TypeAttributes.VisibilityMask) == TypeAttributes.NotPublic))
throw new ArgumentException(Environment.GetResourceString("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)
{
@@ -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,7 +668,7 @@ 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"));
}
@@ -674,14 +676,14 @@ namespace System.Reflection.Emit {
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"));
}
}
// 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"));
}
@@ -695,25 +697,25 @@ namespace System.Reflection.Emit {
[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
@@ -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,9 +820,9 @@ 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"));
@@ -840,21 +842,20 @@ namespace System.Reflection.Emit {
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")); }
}
- public override String FullName
+ public override String FullName
{
- get
- {
+ get
+ {
if (m_strFullQualName == null)
m_strFullQualName = TypeNameBuilder.ToString(this, TypeNameBuilder.Format.FullName);
@@ -862,26 +863,26 @@ 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"));
@@ -899,8 +900,8 @@ namespace System.Reflection.Emit {
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"));
@@ -943,12 +944,12 @@ namespace System.Reflection.Emit {
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"));
Contract.EndContractBlock();
-
+
return m_bakedRuntimeType.GetInterface(name, ignoreCase);
}
@@ -967,7 +968,7 @@ namespace System.Reflection.Emit {
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"));
@@ -1015,7 +1016,7 @@ namespace System.Reflection.Emit {
throw new NotSupportedException(Environment.GetResourceString("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)
@@ -1053,55 +1054,55 @@ namespace System.Reflection.Emit {
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()
{
@@ -1127,12 +1128,11 @@ 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"));
}
@@ -1165,9 +1165,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 +1177,10 @@ namespace System.Reflection.Emit {
return false;
}
-
- public override Type UnderlyingSystemType
+
+ public override Type UnderlyingSystemType
{
- get
+ get
{
if (m_bakedRuntimeType != null)
return m_bakedRuntimeType;
@@ -1189,8 +1189,8 @@ namespace System.Reflection.Emit {
{
if (m_enumUnderlyingType == null)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NoUnderlyingTypeOnEnum"));
-
- return m_enumUnderlyingType;
+
+ return m_enumUnderlyingType;
}
else
{
@@ -1199,22 +1199,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 +1225,9 @@ namespace System.Reflection.Emit {
{
szrank = "*";
}
- else
+ else
{
- for(int i = 1; i < rank; i++)
+ for (int i = 1; i < rank; i++)
szrank += ",";
}
@@ -1259,7 +1259,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(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType));
return CustomAttribute.GetCustomAttributes(m_bakedRuntimeType, attributeRuntimeType, inherit);
}
@@ -1276,7 +1276,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(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType));
return CustomAttribute.IsDefined(m_bakedRuntimeType, attributeRuntimeType, inherit);
}
@@ -1284,12 +1284,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 +1308,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 +1317,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 +1347,7 @@ namespace System.Reflection.Emit {
#region Define Method
public void DefineMethodOverride(MethodInfo methodInfoBody, MethodInfo methodInfoDeclaration)
{
- lock(SyncRoot)
+ lock (SyncRoot)
{
DefineMethodOverrideNoLock(methodInfoBody, methodInfoDeclaration);
}
@@ -1363,13 +1363,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;
+
+ MethodToken tkBody;
+ MethodToken tkDecl;
tkBody = m_module.GetMethodTokenInternal(methodInfoBody);
tkDecl = m_module.GetMethodTokenInternal(methodInfoDeclaration);
@@ -1405,21 +1405,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)
@@ -1451,21 +1451,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(Environment.GetResourceString("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 +1481,7 @@ namespace System.Reflection.Emit {
#region Define Constructor
public ConstructorBuilder DefineTypeInitializer()
{
- lock(SyncRoot)
+ lock (SyncRoot)
{
return DefineTypeInitializerNoLock();
}
@@ -1507,7 +1507,7 @@ namespace System.Reflection.Emit {
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ConstructorNotAllowedOnInterface"));
}
- lock(SyncRoot)
+ lock (SyncRoot)
{
return DefineDefaultConstructorNoLock(attributes);
}
@@ -1540,7 +1540,7 @@ namespace System.Reflection.Emit {
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);
}
@@ -1560,7 +1560,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,7 +1572,7 @@ 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)
@@ -1580,13 +1580,13 @@ namespace System.Reflection.Emit {
throw new InvalidOperationException(Environment.GetResourceString("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 +1608,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 +1622,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 +1630,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 +1642,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 +1650,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 +1658,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 +1666,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 +1688,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 +1715,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 +1723,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 +1744,7 @@ namespace System.Reflection.Emit {
public FieldBuilder DefineUninitializedData(String name, int size, FieldAttributes attributes)
{
- lock(SyncRoot)
+ lock (SyncRoot)
{
return DefineUninitializedDataNoLock(name, size, attributes);
}
@@ -1763,38 +1763,38 @@ 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)
@@ -1809,8 +1809,8 @@ namespace System.Reflection.Emit {
CheckContext(parameterTypeOptionalCustomModifiers);
SignatureHelper sigHelper;
- int sigLength;
- byte[] sigBytes;
+ int sigLength;
+ byte[] sigBytes;
ThrowIfCreated();
@@ -1844,7 +1844,7 @@ namespace System.Reflection.Emit {
public EventBuilder DefineEvent(String name, EventAttributes attributes, Type eventtype)
{
- lock(SyncRoot)
+ lock (SyncRoot)
{
return DefineEventNoLock(name, attributes, eventtype);
}
@@ -1861,13 +1861,13 @@ namespace System.Reflection.Emit {
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 +1909,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 +1927,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 +1976,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 +1998,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,17 +2009,17 @@ 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"));
}
@@ -2051,7 +2051,7 @@ namespace System.Reflection.Emit {
if ((body == null || body.Length == 0) && !meth.m_canBeRuntimeImpl)
throw new InvalidOperationException(
- Environment.GetResourceString("InvalidOperation_BadEmptyMethodBody", meth.Name) );
+ Environment.GetResourceString("InvalidOperation_BadEmptyMethodBody", meth.Name));
}
int maxStack = meth.GetMaxStack();
@@ -2059,7 +2059,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 +2086,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 +2104,8 @@ namespace System.Reflection.Emit {
{
get { return m_iTypeSize; }
}
-
- public PackingSize PackingSize
+
+ public PackingSize PackingSize
{
get { return m_iPackingSize; }
}
@@ -2149,7 +2149,7 @@ namespace System.Reflection.Emit {
Contract.EndContractBlock();
CheckContext(interfaceType);
-
+
ThrowIfCreated();
TypeToken tkInterface = m_module.GetTypeTokenInternal(interfaceType);
@@ -2158,14 +2158,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..f47f0af412 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(); }
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..6c9bc81323 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,7 +65,7 @@ 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; } }
@@ -79,7 +79,7 @@ namespace System.Reflection.Emit
}
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
index 4cc08f62d3..fcf14786c4 100644
--- a/src/mscorlib/src/System/Reflection/EventAttributes.cs
+++ b/src/mscorlib/src/System/Reflection/EventAttributes.cs
@@ -11,19 +11,22 @@
// bits and enums.
//
//
-namespace System.Reflection {
-
- using System;
+
+using System;
+
+namespace System.Reflection
+{
[Serializable]
[Flags]
- public enum EventAttributes {
- None = 0x0000,
-
+ public enum EventAttributes
+ {
+ None = 0x0000,
+
// This Enum matchs the CorEventAttr defined in CorHdr.h
- SpecialName = 0x0200, // event is special. Name describes how.
+ 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.
+ 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
index 9b529c2960..1e2691ae75 100644
--- a/src/mscorlib/src/System/Reflection/EventInfo.cs
+++ b/src/mscorlib/src/System/Reflection/EventInfo.cs
@@ -97,7 +97,7 @@ namespace System.Reflection
public MethodInfo[] GetOtherMethods() { return GetOtherMethods(false); }
public MethodInfo GetAddMethod() { return GetAddMethod(false); }
-
+
public MethodInfo GetRemoveMethod() { return GetRemoveMethod(false); }
public MethodInfo GetRaiseMethod() { return GetRaiseMethod(false); }
@@ -145,9 +145,9 @@ namespace System.Reflection
removeMethod.Invoke(target, new object[] { handler });
}
- public virtual Type EventHandlerType
+ public virtual Type EventHandlerType
{
- get
+ get
{
MethodInfo m = GetAddMethod(true);
@@ -165,17 +165,17 @@ namespace System.Reflection
return null;
}
}
- public bool IsSpecialName
+ public bool IsSpecialName
{
- get
+ get
{
- return(Attributes & EventAttributes.SpecialName) != 0;
+ return (Attributes & EventAttributes.SpecialName) != 0;
}
}
- public virtual bool IsMulticast
+ public virtual bool IsMulticast
{
- get
+ get
{
Type cl = EventHandlerType;
Type mc = typeof(MulticastDelegate);
@@ -197,7 +197,7 @@ namespace System.Reflection
private RuntimeMethodInfo m_addMethod;
private RuntimeMethodInfo m_removeMethod;
private RuntimeMethodInfo m_raiseMethod;
- private MethodInfo[] m_otherMethod;
+ private MethodInfo[] m_otherMethod;
private RuntimeType m_declaringType;
private BindingFlags m_bindingFlags;
#endregion
@@ -216,17 +216,17 @@ namespace System.Reflection
MetadataImport scope = declaredType.GetRuntimeModule().MetadataImport;
m_token = tkEvent;
- m_reflectedTypeCache = reflectedTypeCache;
+ 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,
+ 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
@@ -248,7 +248,7 @@ namespace System.Reflection
#endregion
#region Object Overrides
- public override String ToString()
+ public override String ToString()
{
if (m_addMethod == null || m_addMethod.GetParametersNoCopy().Length == 0)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NoPublicAddMethod"));
@@ -271,8 +271,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(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType));
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
}
@@ -285,8 +285,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(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType));
return CustomAttribute.IsDefined(this, attributeRuntimeType);
}
@@ -299,15 +299,15 @@ namespace System.Reflection
#region MemberInfo Overrides
public override MemberTypes MemberType { get { return MemberTypes.Event; } }
- public override String Name
+ public override String Name
{
- get
+ get
{
if (m_name == null)
m_name = new Utf8String(m_utf8name).ToString();
-
- return m_name;
- }
+
+ return m_name;
+ }
}
public override Type DeclaringType { get { return m_declaringType; } }
public override Type ReflectedType
@@ -348,19 +348,19 @@ namespace System.Reflection
#endregion
#region EventInfo Overrides
- public override MethodInfo[] GetOtherMethods(bool nonPublic)
+ 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 ++)
+ 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();
}
@@ -388,7 +388,7 @@ namespace System.Reflection
return m_raiseMethod;
}
- public override EventAttributes Attributes
+ public override EventAttributes Attributes
{
get
{
@@ -397,5 +397,4 @@ namespace System.Reflection
}
#endregion
}
-
}
diff --git a/src/mscorlib/src/System/Reflection/FieldAttributes.cs b/src/mscorlib/src/System/Reflection/FieldAttributes.cs
index e49a0a45b1..02bfbece2d 100644
--- a/src/mscorlib/src/System/Reflection/FieldAttributes.cs
+++ b/src/mscorlib/src/System/Reflection/FieldAttributes.cs
@@ -2,41 +2,42 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System;
+
namespace System.Reflection
{
- 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
-
+ 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.
-
+ 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.
+ 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.
+ 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.cs b/src/mscorlib/src/System/Reflection/FieldInfo.cs
index 7b6517c2bb..3ff0f7d204 100644
--- a/src/mscorlib/src/System/Reflection/FieldInfo.cs
+++ b/src/mscorlib/src/System/Reflection/FieldInfo.cs
@@ -27,29 +27,29 @@ namespace System.Reflection
{
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"),
+ CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_FieldDeclaringTypeGeneric"),
f.Name, declaringType.GetGenericTypeDefinition()));
- return f;
- }
-
+ 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() { }
+ protected FieldInfo() { }
#endregion
public static bool operator ==(FieldInfo left, FieldInfo right)
@@ -85,7 +85,7 @@ namespace System.Reflection
#endregion
#region Public Abstract\Virtual Members
-
+
public virtual Type[] GetRequiredCustomModifiers()
{
throw new NotImplementedException();
@@ -106,12 +106,12 @@ namespace System.Reflection
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 Type FieldType { get; }
+
public abstract Object GetValue(Object obj);
public virtual Object GetRawConstantValue() { throw new NotSupportedException(Environment.GetResourceString("NotSupported_AbstractNonCLS")); }
@@ -135,29 +135,29 @@ namespace System.Reflection
SetValue(obj, value, BindingFlags.Default, Type.DefaultBinder, null);
}
- public bool IsPublic { get { return(Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Public; } }
+ public bool IsPublic { get { return (Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Public; } }
- public bool IsPrivate { get { return(Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Private; } }
+ public bool IsPrivate { get { return (Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Private; } }
- public bool IsFamily { get { return(Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Family; } }
+ public bool IsFamily { get { return (Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Family; } }
- public bool IsAssembly { get { return(Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Assembly; } }
+ public bool IsAssembly { get { return (Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Assembly; } }
- public bool IsFamilyAndAssembly { get { return(Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.FamANDAssem; } }
+ public bool IsFamilyAndAssembly { get { return (Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.FamANDAssem; } }
- public bool IsFamilyOrAssembly { get { return(Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.FamORAssem; } }
+ public bool IsFamilyOrAssembly { get { return (Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.FamORAssem; } }
- public bool IsStatic { get { return(Attributes & FieldAttributes.Static) != 0; } }
+ public bool IsStatic { get { return (Attributes & FieldAttributes.Static) != 0; } }
- public bool IsInitOnly { get { return(Attributes & FieldAttributes.InitOnly) != 0; } }
+ public bool IsInitOnly { get { return (Attributes & FieldAttributes.InitOnly) != 0; } }
- public bool IsLiteral { get { return(Attributes & FieldAttributes.Literal) != 0; } }
+ public bool IsLiteral { get { return (Attributes & FieldAttributes.Literal) != 0; } }
- public bool IsNotSerialized { get { return(Attributes & FieldAttributes.NotSerialized) != 0; } }
+ public bool IsNotSerialized { get { return (Attributes & FieldAttributes.NotSerialized) != 0; } }
- public bool IsSpecialName { get { return(Attributes & FieldAttributes.SpecialName) != 0; } }
+ public bool IsSpecialName { get { return (Attributes & FieldAttributes.SpecialName) != 0; } }
- public bool IsPinvokeImpl { get { return(Attributes & FieldAttributes.PinvokeImpl) != 0; } }
+ public bool IsPinvokeImpl { get { return (Attributes & FieldAttributes.PinvokeImpl) != 0; } }
public virtual bool IsSecurityCritical
{
@@ -183,7 +183,7 @@ namespace System.Reflection
#region Private Data Members
private BindingFlags m_bindingFlags;
protected RuntimeTypeCache m_reflectedTypeCache;
- protected RuntimeType m_declaringType;
+ protected RuntimeType m_declaringType;
#endregion
#region Constructor
@@ -202,11 +202,11 @@ namespace System.Reflection
#region NonPublic Members
internal BindingFlags BindingFlags { get { return m_bindingFlags; } }
private RuntimeType ReflectedTypeInternal
- {
- get
- {
- return m_reflectedTypeCache.GetRuntimeType();
- }
+ {
+ get
+ {
+ return m_reflectedTypeCache.GetRuntimeType();
+ }
}
internal RuntimeType GetDeclaringTypeInternal()
@@ -227,20 +227,20 @@ namespace System.Reflection
return m_reflectedTypeCache.IsGlobal ? null : ReflectedTypeInternal;
}
}
-
- public override Type DeclaringType
- {
- get
- {
- return m_reflectedTypeCache.IsGlobal ? null : m_declaringType;
- }
+
+ 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()
+ public unsafe override String ToString()
{
return FieldType.FormatTypeName() + " " + Name;
}
@@ -260,8 +260,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(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType));
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
}
@@ -274,8 +274,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(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType));
return CustomAttribute.IsDefined(this, attributeRuntimeType);
}
@@ -408,7 +408,7 @@ namespace System.Reflection
#region Constructor
internal RtFieldInfo(
- RuntimeFieldHandleInternal handle, RuntimeType declaringType, RuntimeTypeCache reflectedTypeCache, BindingFlags bindingFlags)
+ RuntimeFieldHandleInternal handle, RuntimeType declaringType, RuntimeTypeCache reflectedTypeCache, BindingFlags bindingFlags)
: base(reflectedTypeCache, declaringType, bindingFlags)
{
m_fieldHandle = handle.Value;
@@ -428,10 +428,10 @@ namespace System.Reflection
#endregion
#region Internal Members
- internal void CheckConsistency(Object target)
+ internal void CheckConsistency(Object target)
{
// only test instance fields
- if ((m_fieldAttributes & FieldAttributes.Static) != FieldAttributes.Static)
+ if ((m_fieldAttributes & FieldAttributes.Static) != FieldAttributes.Static)
{
if (!m_declaringType.IsInstanceOfType(target))
{
@@ -492,7 +492,7 @@ namespace System.Reflection
}
#endif
- if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_SPECIAL_FIELD | INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY)) != 0)
+ 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
@@ -597,13 +597,13 @@ namespace System.Reflection
object retVal = RuntimeFieldHandle.GetValue(this, obj, fieldType, declaringType, ref domainInitialized);
declaringType.DomainInitialized = domainInitialized;
return retVal;
- }
- }
+ }
+ }
#endregion
#region MemberInfo Overrides
- public override String Name
+ public override String Name
{
get
{
@@ -639,8 +639,8 @@ namespace System.Reflection
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return InternalGetValue(obj, ref stackMark);
- }
-
+ }
+
public override object GetRawConstantValue() { throw new InvalidOperationException(); }
[DebuggerStepThroughAttribute]
@@ -681,7 +681,7 @@ namespace System.Reflection
}
}
- public override RuntimeFieldHandle FieldHandle
+ public override RuntimeFieldHandle FieldHandle
{
get
{
@@ -692,12 +692,12 @@ namespace System.Reflection
}
}
- internal IntPtr GetFieldHandle()
+ internal IntPtr GetFieldHandle()
{
return m_fieldHandle;
}
- public override FieldAttributes Attributes
+ public override FieldAttributes Attributes
{
get
{
@@ -705,7 +705,7 @@ namespace System.Reflection
}
}
- public override Type FieldType
+ public override Type FieldType
{
get
{
@@ -714,8 +714,8 @@ namespace System.Reflection
return m_fieldType;
}
- }
-
+ }
+
public override Type[] GetRequiredCustomModifiers()
{
return new Signature(this, m_declaringType).GetCustomModifiers(1, true);
@@ -745,7 +745,7 @@ namespace System.Reflection
: base(reflectedTypeCache, declaringTypeHandle.GetRuntimeType(), bindingFlags)
{
m_tkField = tkField;
- m_name = null;
+ m_name = null;
m_fieldAttributes = fieldAttributes;
}
#endregion
@@ -758,14 +758,14 @@ namespace System.Reflection
if ((object)m == null)
return false;
- return m.m_tkField == m_tkField &&
+ return m.m_tkField == m_tkField &&
m_declaringType.GetTypeHandleInternal().GetModuleHandle().Equals(
m.m_declaringType.GetTypeHandleInternal().GetModuleHandle());
}
#endregion
#region MemberInfo Overrides
- public override String Name
+ public override String Name
{
get
{
@@ -797,7 +797,7 @@ namespace System.Reflection
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
- public override void SetValueDirect(TypedReference obj,Object value)
+ public override void SetValueDirect(TypedReference obj, Object value)
{
throw new FieldAccessException(Environment.GetResourceString("Acc_ReadOnly"));
}
@@ -810,7 +810,7 @@ namespace System.Reflection
}
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
@@ -821,7 +821,7 @@ namespace System.Reflection
throw new NotSupportedException(Environment.GetResourceString("Arg_EnumLitValueNotFound"));
return value;
- }
+ }
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
@@ -830,7 +830,7 @@ namespace System.Reflection
throw new FieldAccessException(Environment.GetResourceString("Acc_ReadOnly"));
}
- public override Type FieldType
+ public override Type FieldType
{
get
{
@@ -838,14 +838,14 @@ namespace System.Reflection
{
ConstArray fieldMarshal = GetRuntimeModule().MetadataImport.GetSigOfFieldDef(m_tkField);
- m_fieldType = new Signature(fieldMarshal.Signature.ToPointer(),
+ m_fieldType = new Signature(fieldMarshal.Signature.ToPointer(),
(int)fieldMarshal.Length, m_declaringType).FieldType;
}
return m_fieldType;
}
- }
-
+ }
+
public override Type[] GetRequiredCustomModifiers()
{
return EmptyArray<Type>.Value;
@@ -858,5 +858,4 @@ namespace System.Reflection
#endregion
}
-
}
diff --git a/src/mscorlib/src/System/Reflection/GenericParameterAttributes.cs b/src/mscorlib/src/System/Reflection/GenericParameterAttributes.cs
index d954b2e0f2..0dfc4b676d 100644
--- a/src/mscorlib/src/System/Reflection/GenericParameterAttributes.cs
+++ b/src/mscorlib/src/System/Reflection/GenericParameterAttributes.cs
@@ -4,7 +4,7 @@
//
-namespace System.Reflection
+namespace System.Reflection
{
[Flags()]
public enum GenericParameterAttributes
diff --git a/src/mscorlib/src/System/Reflection/ICustomAttributeProvider.cs b/src/mscorlib/src/System/Reflection/ICustomAttributeProvider.cs
index faea91a81e..1e3f675126 100644
--- a/src/mscorlib/src/System/Reflection/ICustomAttributeProvider.cs
+++ b/src/mscorlib/src/System/Reflection/ICustomAttributeProvider.cs
@@ -10,14 +10,14 @@
// objects which support custom attributes.
//
//
-namespace System.Reflection {
-
- using System;
+using System;
+
+namespace System.Reflection
+{
// 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);
@@ -25,9 +25,8 @@ namespace System.Reflection {
// 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);
-
+ bool IsDefined(Type attributeType, bool inherit);
}
}
diff --git a/src/mscorlib/src/System/Reflection/IReflect.cs b/src/mscorlib/src/System/Reflection/IReflect.cs
index 1c3c57613b..7f023e04d7 100644
--- a/src/mscorlib/src/System/Reflection/IReflect.cs
+++ b/src/mscorlib/src/System/Reflection/IReflect.cs
@@ -13,11 +13,13 @@
// the interop layer.
//
//
-namespace System.Reflection {
+
+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
@@ -25,16 +27,16 @@ namespace System.Reflection {
// 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);
+ 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 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.
@@ -51,17 +53,17 @@ namespace System.Reflection {
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,
+ Binder binder,
Type returnType,
Type[] types,
ParameterModifier[] modifiers);
-
+
// Returns an array of PropertyInfos for all the properties defined on
// the Reflection object.
PropertyInfo[] GetProperties(
@@ -75,7 +77,7 @@ namespace System.Reflection {
// 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
@@ -109,8 +111,9 @@ namespace System.Reflection {
// 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 {
+ Type UnderlyingSystemType
+ {
get;
- }
+ }
}
}
diff --git a/src/mscorlib/src/System/Reflection/IReflectableType.cs b/src/mscorlib/src/System/Reflection/IReflectableType.cs
index 7d4936868b..72b1b871fc 100644
--- a/src/mscorlib/src/System/Reflection/IReflectableType.cs
+++ b/src/mscorlib/src/System/Reflection/IReflectableType.cs
@@ -10,11 +10,13 @@
//
//
-namespace System.Reflection {
-
- using System;
-
- public interface IReflectableType {
+
+using System;
+
+namespace System.Reflection
+{
+ public interface IReflectableType
+ {
TypeInfo GetTypeInfo();
}
}
diff --git a/src/mscorlib/src/System/Reflection/InterfaceMapping.cs b/src/mscorlib/src/System/Reflection/InterfaceMapping.cs
index bf994f7b47..a1fdbde8f6 100644
--- a/src/mscorlib/src/System/Reflection/InterfaceMapping.cs
+++ b/src/mscorlib/src/System/Reflection/InterfaceMapping.cs
@@ -10,13 +10,16 @@
// 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
+using System;
+
+namespace System.Reflection
+{
+ 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
index 49819a942f..79316bcadc 100644
--- a/src/mscorlib/src/System/Reflection/IntrospectionExtensions.cs
+++ b/src/mscorlib/src/System/Reflection/IntrospectionExtensions.cs
@@ -12,16 +12,17 @@
**
**
=============================================================================*/
+
namespace System.Reflection
{
public static class IntrospectionExtensions
{
- public static TypeInfo GetTypeInfo(this Type type)
+ public static TypeInfo GetTypeInfo(this Type type)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
-
- var rcType=(IReflectableType)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
index 8b8c06d9cf..d3333df8e1 100644
--- a/src/mscorlib/src/System/Reflection/InvalidFilterCriteriaException.cs
+++ b/src/mscorlib/src/System/Reflection/InvalidFilterCriteriaException.cs
@@ -12,28 +12,33 @@
//
//
//
-namespace System.Reflection {
+namespace System.Reflection
+{
using System;
using System.Runtime.Serialization;
using ApplicationException = System.ApplicationException;
[Serializable]
- public class InvalidFilterCriteriaException : ApplicationException {
+ public class InvalidFilterCriteriaException : ApplicationException
+ {
public InvalidFilterCriteriaException()
- : base(Environment.GetResourceString("Arg_InvalidFilterCriteriaException")) {
+ : base(Environment.GetResourceString("Arg_InvalidFilterCriteriaException"))
+ {
SetErrorCode(__HResults.COR_E_INVALIDFILTERCRITERIA);
}
-
- public InvalidFilterCriteriaException(String message) : base(message) {
+
+ public InvalidFilterCriteriaException(String message) : base(message)
+ {
SetErrorCode(__HResults.COR_E_INVALIDFILTERCRITERIA);
}
-
- public InvalidFilterCriteriaException(String message, Exception inner) : base(message, inner) {
+
+ public InvalidFilterCriteriaException(String message, Exception inner) : base(message, inner)
+ {
SetErrorCode(__HResults.COR_E_INVALIDFILTERCRITERIA);
}
- protected InvalidFilterCriteriaException(SerializationInfo info, StreamingContext context) : base(info, context) {
+ 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/ManifestResourceInfo.cs b/src/mscorlib/src/System/Reflection/ManifestResourceInfo.cs
index 91c7ceb2ea..792d054d44 100644
--- a/src/mscorlib/src/System/Reflection/ManifestResourceInfo.cs
+++ b/src/mscorlib/src/System/Reflection/ManifestResourceInfo.cs
@@ -13,10 +13,12 @@
**
=============================================================================*/
-namespace System.Reflection {
- using System;
-
- public class ManifestResourceInfo {
+using System;
+
+namespace System.Reflection
+{
+ public class ManifestResourceInfo
+ {
private Assembly _containingAssembly;
private String _containingFileName;
private ResourceLocation _resourceLocation;
@@ -32,21 +34,24 @@ namespace System.Reflection {
public virtual Assembly ReferencedAssembly
{
- get {
+ get
+ {
return _containingAssembly;
}
}
public virtual String FileName
{
- get {
+ get
+ {
return _containingFileName;
}
}
public virtual ResourceLocation ResourceLocation
{
- get {
+ get
+ {
return _resourceLocation;
}
}
@@ -54,7 +59,7 @@ namespace System.Reflection {
// The ResourceLocation is a combination of these flags, set or not.
// Linked means not Embedded.
-[Serializable]
+ [Serializable]
[Flags]
public enum ResourceLocation
{
diff --git a/src/mscorlib/src/System/Reflection/MdConstant.cs b/src/mscorlib/src/System/Reflection/MdConstant.cs
index e59244f109..43c5556ed8 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
+ #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
+ #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
+ #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
index 56fc9c0804..707ce9b584 100644
--- a/src/mscorlib/src/System/Reflection/MemberFilter.cs
+++ b/src/mscorlib/src/System/Reflection/MemberFilter.cs
@@ -10,8 +10,9 @@
// as a callback from Type.FindMembers.
//
//
-namespace System.Reflection {
+namespace System.Reflection
+{
// Define the delegate
[Serializable]
public delegate bool MemberFilter(MemberInfo m, Object filterCriteria);
diff --git a/src/mscorlib/src/System/Reflection/MemberInfo.cs b/src/mscorlib/src/System/Reflection/MemberInfo.cs
index 5ecbfe06a1..dd9d20e59e 100644
--- a/src/mscorlib/src/System/Reflection/MemberInfo.cs
+++ b/src/mscorlib/src/System/Reflection/MemberInfo.cs
@@ -4,14 +4,14 @@
//
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.Contracts;
+using System.Runtime;
+using System.Runtime.InteropServices;
+
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
{
@@ -20,7 +20,7 @@ namespace System.Reflection
#endregion
#region Internal Methods
- internal virtual bool CacheEquals(object o) { throw new NotImplementedException(); }
+ internal virtual bool CacheEquals(object o) { throw new NotImplementedException(); }
#endregion
#region Public Abstract\Virtual Members
@@ -53,18 +53,18 @@ namespace System.Reflection
public virtual int MetadataToken { get { throw new InvalidOperationException(); } }
public virtual Module Module
- {
+ {
get
{
if (this is Type)
return ((Type)this).Module;
- throw new NotImplementedException();
- }
+ throw new NotImplementedException();
+ }
}
-
-
-
+
+
+
#endregion
public static bool operator ==(MemberInfo left, MemberInfo right)
diff --git a/src/mscorlib/src/System/Reflection/MemberInfoSerializationHolder.cs b/src/mscorlib/src/System/Reflection/MemberInfoSerializationHolder.cs
index 20ff37650c..d59205d707 100644
--- a/src/mscorlib/src/System/Reflection/MemberInfoSerializationHolder.cs
+++ b/src/mscorlib/src/System/Reflection/MemberInfoSerializationHolder.cs
@@ -10,10 +10,10 @@ using System.Runtime.Serialization;
using System.Globalization;
using System.Diagnostics.Contracts;
-namespace System.Reflection
+namespace System.Reflection
{
[Serializable]
- internal class MemberInfoSerializationHolder : ISerializable, IObjectReference
+ internal class MemberInfoSerializationHolder : ISerializable, IObjectReference
{
#region Staitc Public Members
public static void GetSerializationInfo(SerializationInfo info, String name, RuntimeType reflectedClass, String signature, MemberTypes type)
@@ -60,9 +60,9 @@ namespace System.Reflection
private MemberTypes m_memberType;
private SerializationInfo m_info;
#endregion
-
+
#region Constructor
- internal MemberInfoSerializationHolder(SerializationInfo info, StreamingContext context)
+ internal MemberInfoSerializationHolder(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException(nameof(info));
@@ -70,7 +70,7 @@ namespace System.Reflection
String assemblyName = info.GetString("AssemblyName");
String typeName = info.GetString("ClassName");
-
+
if (assemblyName == null || typeName == null)
throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientState"));
@@ -86,200 +86,197 @@ namespace System.Reflection
#endregion
#region ISerializable
- public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
+ 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)
+ 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 bindingFlags =
+ BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Static | BindingFlags.OptionalParamBinding;
-
- switch (m_memberType)
+
+ switch (m_memberType)
{
#region case MemberTypes.Field:
case MemberTypes.Field:
- {
- FieldInfo[] fields = m_reflectedType.GetMember(m_memberName, MemberTypes.Field, bindingFlags) as FieldInfo[];
+ {
+ 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));
+ if (fields.Length == 0)
+ throw new SerializationException(Environment.GetResourceString("Serialization_UnknownMember", m_memberName));
- return fields[0];
- }
+ return fields[0];
+ }
#endregion
#region case MemberTypes.Event:
case MemberTypes.Event:
- {
- EventInfo[] events = m_reflectedType.GetMember(m_memberName, MemberTypes.Event, bindingFlags) as EventInfo[];
+ {
+ 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));
+ if (events.Length == 0)
+ throw new SerializationException(Environment.GetResourceString("Serialization_UnknownMember", m_memberName));
- return events[0];
- }
+ return events[0];
+ }
#endregion
#region case MemberTypes.Property:
case MemberTypes.Property:
- {
- PropertyInfo[] properties = m_reflectedType.GetMember(m_memberName, MemberTypes.Property, bindingFlags) as PropertyInfo[];
+ {
+ 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 == 0)
+ throw new SerializationException(Environment.GetResourceString("Serialization_UnknownMember", m_memberName));
- if (properties.Length == 1)
- return properties[0];
+ if (properties.Length == 1)
+ return properties[0];
- if (properties.Length > 1)
- {
- for (int i = 0; i < properties.Length; i++)
+ if (properties.Length > 1)
{
- if (m_signature2 != null)
- {
- if (((RuntimePropertyInfo)properties[i]).SerializationToString().Equals(m_signature2))
- return properties[i];
- }
- else
+ for (int i = 0; i < properties.Length; i++)
{
- if ((properties[i]).ToString().Equals(m_signature))
- return properties[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));
- }
+ 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));
+ {
+ if (m_signature == null)
+ throw new SerializationException(Environment.GetResourceString(ResId.Serialization_NullSignature));
- ConstructorInfo[] constructors = m_reflectedType.GetMember(m_memberName, MemberTypes.Constructor, bindingFlags) as ConstructorInfo[];
+ ConstructorInfo[] constructors = m_reflectedType.GetMember(m_memberName, MemberTypes.Constructor, bindingFlags) as ConstructorInfo[];
- if (constructors.Length == 1)
- return constructors[0];
+ if (constructors.Length == 1)
+ return constructors[0];
- if (constructors.Length > 1)
- {
- for (int i = 0; i < constructors.Length; i++)
+ if (constructors.Length > 1)
{
- if (m_signature2 != null)
+ for (int i = 0; i < constructors.Length; i++)
{
- if (((RuntimeConstructorInfo)constructors[i]).SerializationToString().Equals(m_signature2))
- return constructors[i];
- }
- else
- {
- if (constructors[i].ToString().Equals(m_signature))
- return constructors[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));
- }
+ throw new SerializationException(Environment.GetResourceString(ResId.Serialization_UnknownMember, m_memberName));
+ }
#endregion
#region case MemberTypes.Method:
case MemberTypes.Method:
- {
- MethodInfo methodInfo = null;
+ {
+ MethodInfo methodInfo = null;
- if (m_signature == null)
- throw new SerializationException(Environment.GetResourceString(ResId.Serialization_NullSignature));
+ if (m_signature == null)
+ throw new SerializationException(Environment.GetResourceString(ResId.Serialization_NullSignature));
- Type[] genericArguments = m_info.GetValueNoThrow("GenericArguments", typeof(Type[])) as Type[];
+ Type[] genericArguments = m_info.GetValueNoThrow("GenericArguments", typeof(Type[])) as Type[];
- MethodInfo[] methods = m_reflectedType.GetMember(m_memberName, MemberTypes.Method, bindingFlags) as MethodInfo[];
+ MethodInfo[] methods = m_reflectedType.GetMember(m_memberName, MemberTypes.Method, bindingFlags) as MethodInfo[];
- if (methods.Length == 1)
- methodInfo = methods[0];
+ if (methods.Length == 1)
+ methodInfo = methods[0];
- else if (methods.Length > 1)
- {
- for (int i = 0; i < methods.Length; i++)
+ else if (methods.Length > 1)
{
- if (m_signature2 != null)
+ for (int i = 0; i < methods.Length; i++)
{
- if (((RuntimeMethodInfo)methods[i]).SerializationToString().Equals(m_signature2))
+ if (m_signature2 != null)
{
- methodInfo = methods[i];
- break;
+ if (((RuntimeMethodInfo)methods[i]).SerializationToString().Equals(m_signature2))
+ {
+ methodInfo = methods[i];
+ break;
+ }
}
- }
- else
- {
-
- if (methods[i].ToString().Equals(m_signature))
+ else
{
- methodInfo = methods[i];
- break;
+ 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)
+ // 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)
{
- MethodInfo candidateMethod = methods[i].MakeGenericMethod(genericArguments);
-
- if (m_signature2 != null)
+ if (methods[i].GetGenericArguments().Length == genericArguments.Length)
{
- if (((RuntimeMethodInfo)candidateMethod).SerializationToString().Equals(m_signature2))
+ MethodInfo candidateMethod = methods[i].MakeGenericMethod(genericArguments);
+
+ if (m_signature2 != null)
{
- methodInfo = candidateMethod;
- break;
+ if (((RuntimeMethodInfo)candidateMethod).SerializationToString().Equals(m_signature2))
+ {
+ methodInfo = candidateMethod;
+ break;
+ }
}
- }
- else
- {
- if (candidateMethod.ToString().Equals(m_signature))
+ else
{
- methodInfo = candidateMethod;
- break;
+ if (candidateMethod.ToString().Equals(m_signature))
+ {
+ methodInfo = candidateMethod;
+ break;
+ }
}
}
}
}
}
- }
- if (methodInfo == null)
- throw new SerializationException(Environment.GetResourceString(ResId.Serialization_UnknownMember, m_memberName));
+ if (methodInfo == null)
+ throw new SerializationException(Environment.GetResourceString(ResId.Serialization_UnknownMember, m_memberName));
- if (!methodInfo.IsGenericMethodDefinition)
- return methodInfo;
+ if (!methodInfo.IsGenericMethodDefinition)
+ return methodInfo;
- if (genericArguments == null)
- return methodInfo;
+ if (genericArguments == null)
+ return methodInfo;
- if (genericArguments[0] == null)
- return null;
+ if (genericArguments[0] == null)
+ return null;
- return methodInfo.MakeGenericMethod(genericArguments);
- }
+ return methodInfo.MakeGenericMethod(genericArguments);
+ }
#endregion
default:
throw new ArgumentException(Environment.GetResourceString("Serialization_MemberTypeNotRecognized"));
- }
+ }
}
#endregion
}
-
-
}
diff --git a/src/mscorlib/src/System/Reflection/MemberTypes.cs b/src/mscorlib/src/System/Reflection/MemberTypes.cs
index 95c41022f1..aac59ecf35 100644
--- a/src/mscorlib/src/System/Reflection/MemberTypes.cs
+++ b/src/mscorlib/src/System/Reflection/MemberTypes.cs
@@ -11,23 +11,25 @@
// are useful in switch statements.
//
//
-namespace System.Reflection {
-
- using System;
+
+using System;
+
+namespace System.Reflection
+{
// 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,
+ 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
index 7e4391cccd..38b35ff151 100644
--- a/src/mscorlib/src/System/Reflection/MethodAttributes.cs
+++ b/src/mscorlib/src/System/Reflection/MethodAttributes.cs
@@ -5,9 +5,10 @@
////////////////////////////////////////////////////////////////////////////////
//
-namespace System.Reflection
+using System;
+
+namespace System.Reflection
{
- using System;
[Serializable]
[Flags]
public enum MethodAttributes
@@ -15,41 +16,41 @@ namespace System.Reflection
// 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
-
+ 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,
-
+ 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
-
+ 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.
-
+ 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.
+ 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.
+ 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.cs b/src/mscorlib/src/System/Reflection/MethodBase.cs
index 0d3de972a4..f80c1701ad 100644
--- a/src/mscorlib/src/System/Reflection/MethodBase.cs
+++ b/src/mscorlib/src/System/Reflection/MethodBase.cs
@@ -60,9 +60,9 @@ namespace System.Reflection
Type declaringType = m.DeclaringType;
if (declaringType != null && declaringType.IsGenericType)
throw new ArgumentException(String.Format(
- CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_MethodDeclaringTypeGeneric"),
+ CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_MethodDeclaringTypeGeneric"),
m, declaringType.GetGenericTypeDefinition()));
-
+
return m;
}
@@ -129,7 +129,7 @@ namespace System.Reflection
#endregion
#region Public Abstract\Virtual Members
- internal virtual ParameterInfo[] GetParametersNoCopy() { return GetParameters (); }
+ internal virtual ParameterInfo[] GetParametersNoCopy() { return GetParameters(); }
[System.Diagnostics.Contracts.Pure]
public abstract ParameterInfo[] GetParameters();
@@ -144,16 +144,16 @@ namespace System.Reflection
public abstract MethodImplAttributes GetMethodImplementationFlags();
- public abstract RuntimeMethodHandle MethodHandle { get; }
+ public abstract RuntimeMethodHandle MethodHandle { get; }
- public abstract MethodAttributes Attributes { 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; } }
@@ -182,33 +182,37 @@ namespace System.Reflection
return Invoke(obj, BindingFlags.Default, null, parameters, null);
}
- public bool IsPublic { get { return(Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Public; } }
+ public bool IsPublic { get { return (Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Public; } }
- public bool IsPrivate { get { return(Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Private; } }
+ public bool IsPrivate { get { return (Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Private; } }
- public bool IsFamily { get { return(Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Family; } }
+ public bool IsFamily { get { return (Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Family; } }
- public bool IsAssembly { get { return(Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Assembly; } }
+ public bool IsAssembly { get { return (Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Assembly; } }
- public bool IsFamilyAndAssembly { get { return(Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.FamANDAssem; } }
+ public bool IsFamilyAndAssembly { get { return (Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.FamANDAssem; } }
- public bool IsFamilyOrAssembly { get {return(Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.FamORAssem; } }
+ public bool IsFamilyOrAssembly { get { return (Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.FamORAssem; } }
- public bool IsStatic { get { return(Attributes & MethodAttributes.Static) != 0; } }
+ public bool IsStatic { get { return (Attributes & MethodAttributes.Static) != 0; } }
- public bool IsFinal { get { return(Attributes & MethodAttributes.Final) != 0; }
+ public bool IsFinal
+ {
+ get { return (Attributes & MethodAttributes.Final) != 0; }
+ }
+ public bool IsVirtual
+ {
+ get { return (Attributes & MethodAttributes.Virtual) != 0; }
}
- public bool IsVirtual { get { return(Attributes & MethodAttributes.Virtual) != 0; }
- }
- public bool IsHideBySig { get { return(Attributes & MethodAttributes.HideBySig) != 0; } }
+ public bool IsHideBySig { get { return (Attributes & MethodAttributes.HideBySig) != 0; } }
- public bool IsAbstract { get { return(Attributes & MethodAttributes.Abstract) != 0; } }
+ public bool IsAbstract { get { return (Attributes & MethodAttributes.Abstract) != 0; } }
- public bool IsSpecialName { get { return(Attributes & MethodAttributes.SpecialName) != 0; } }
+ public bool IsSpecialName { get { return (Attributes & MethodAttributes.SpecialName) != 0; } }
- public bool IsConstructor
+ public bool IsConstructor
{
- get
+ get
{
// To be backward compatible we only return true for instance RTSpecialName ctors.
return (this is ConstructorInfo &&
@@ -220,9 +224,9 @@ namespace System.Reflection
public virtual MethodBody GetMethodBody()
{
throw new InvalidOperationException();
- }
+ }
#endregion
-
+
#region Internal Methods
// helper method to construct the string representation of the parameter list
@@ -299,24 +303,24 @@ namespace System.Reflection
return parameterTypes;
}
- internal Object[] CheckArguments(Object[] parameters, Binder binder,
+ 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)
+ if (p == null)
p = GetParametersNoCopy();
if (p[i].DefaultValue == System.DBNull.Value)
- throw new ArgumentException(Environment.GetResourceString("Arg_VarMissNull"),nameof(parameters));
+ throw new ArgumentException(Environment.GetResourceString("Arg_VarMissNull"), nameof(parameters));
arg = p[i].DefaultValue;
}
copyOfParameters[i] = argRT.CheckValue(arg, binder, culture, invokeAttr);
diff --git a/src/mscorlib/src/System/Reflection/MethodBody.cs b/src/mscorlib/src/System/Reflection/MethodBody.cs
index 7cbaeaf9b9..b245b5406b 100644
--- a/src/mscorlib/src/System/Reflection/MethodBody.cs
+++ b/src/mscorlib/src/System/Reflection/MethodBody.cs
@@ -11,23 +11,23 @@ using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Reflection
-{
+{
[Flags()]
- public enum ExceptionHandlingClauseOptions: int
+ 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")]
@@ -78,40 +78,39 @@ namespace System.Reflection
return type;
}
}
- #endregion
-
+ #endregion
+
#region Object Overrides
public override string ToString()
{
if (Flags == ExceptionHandlingClauseOptions.Clause)
{
- return String.Format(CultureInfo.CurrentUICulture,
+ 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,
+ 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,
+
+ 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 +118,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,7 +129,7 @@ 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
{
@@ -148,7 +147,7 @@ namespace System.Reflection
public override string ToString()
{
string toString = LocalType.ToString() + " (" + LocalIndex + ")";
-
+
if (IsPinned)
toString += " (pinned)";
diff --git a/src/mscorlib/src/System/Reflection/MethodImplAttributes.cs b/src/mscorlib/src/System/Reflection/MethodImplAttributes.cs
index 1bd6b9dbd1..a22735725b 100644
--- a/src/mscorlib/src/System/Reflection/MethodImplAttributes.cs
+++ b/src/mscorlib/src/System/Reflection/MethodImplAttributes.cs
@@ -4,40 +4,41 @@
//
-namespace System.Reflection
+
+using System;
+
+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.
+ 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
-
+ 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
-
+ 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.
+ 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...
- 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.
+ 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
+ MaxMethodImplVal = 0xFFFF, // Range check value
}
}
diff --git a/src/mscorlib/src/System/Reflection/MethodInfo.cs b/src/mscorlib/src/System/Reflection/MethodInfo.cs
index 06c661a157..89c608b542 100644
--- a/src/mscorlib/src/System/Reflection/MethodInfo.cs
+++ b/src/mscorlib/src/System/Reflection/MethodInfo.cs
@@ -60,13 +60,13 @@ namespace System.Reflection
#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 ICustomAttributeProvider ReturnTypeCustomAttributes { get; }
public abstract MethodInfo GetBaseDefinition();
@@ -85,7 +85,7 @@ namespace System.Reflection
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;
@@ -157,8 +157,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;
@@ -194,13 +194,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 +221,11 @@ namespace System.Reflection
}
private RuntimeType ReflectedTypeInternal
- {
- get
- {
- return m_reflectedTypeCache.GetRuntimeType();
- }
+ {
+ get
+ {
+ return m_reflectedTypeCache.GetRuntimeType();
+ }
}
private ParameterInfo[] FetchNonReturnParameters()
@@ -265,15 +265,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 +315,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 +389,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(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType));
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType, inherit);
}
@@ -403,8 +403,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(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType));
return CustomAttribute.IsDefined(this, attributeRuntimeType, inherit);
}
@@ -416,7 +416,7 @@ namespace System.Reflection
#endregion
#region MemberInfo Overrides
- public override String Name
+ public override String Name
{
get
{
@@ -427,7 +427,7 @@ namespace System.Reflection
}
}
- public override Type DeclaringType
+ public override Type DeclaringType
{
get
{
@@ -438,7 +438,7 @@ namespace System.Reflection
}
}
- public override Type ReflectedType
+ public override Type ReflectedType
{
get
{
@@ -453,13 +453,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 +471,9 @@ namespace System.Reflection
{
get { return false; }
}
-#endregion
+ #endregion
-#region MethodBase Overrides
+ #region MethodBase Overrides
internal override ParameterInfo[] GetParametersNoCopy()
{
FetchNonReturnParameters();
@@ -501,45 +501,45 @@ 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);
- }
+ 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)
+ if (target == null)
throw new TargetException(Environment.GetResourceString("RFLCT.Targ_StatMethReqTarg"));
else
throw new TargetException(Environment.GetResourceString("RFLCT.Targ_ITargMismatch"));
@@ -583,7 +583,7 @@ namespace System.Reflection
throw new TargetException();
}
-
+
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
@@ -591,7 +591,7 @@ namespace System.Reflection
{
object[] arguments = InvokeArgumentsCheck(obj, invokeAttr, binder, parameters, culture);
-#region Security Check
+ #region Security Check
INVOCATION_FLAGS invocationFlags = InvocationFlags;
#if FEATURE_APPX
@@ -603,7 +603,7 @@ namespace System.Reflection
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", FullName));
}
#endif
-#endregion
+ #endregion
return UnsafeInvokeInternal(obj, parameters, arguments);
}
@@ -665,20 +665,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 +699,8 @@ namespace System.Reflection
RuntimeType baseDeclaringType = declaringType;
RuntimeMethodHandleInternal baseMethodHandle = new RuntimeMethodHandleInternal();
- do {
+ do
+ {
int cVtblSlots = RuntimeTypeHandle.GetNumVirtuals(declaringType);
if (cVtblSlots <= slot)
@@ -711,7 +712,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)
@@ -772,14 +773,14 @@ namespace System.Reflection
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];
@@ -813,18 +814,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,7 +834,7 @@ namespace System.Reflection
return RuntimeMethodHandle.GetMethodInstantiationInternal(this);
}
- public override Type[] GetGenericArguments()
+ public override Type[] GetGenericArguments()
{
Type[] types = RuntimeMethodHandle.GetMethodInstantiationPublic(this);
@@ -844,12 +845,12 @@ namespace System.Reflection
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 +862,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 +874,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 +882,11 @@ namespace System.Reflection
}
return false;
- }
+ }
}
-#endregion
+ #endregion
-#region ISerializable Implementation
+ #region ISerializable Implementation
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
@@ -909,18 +910,18 @@ namespace System.Reflection
{
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/Missing.cs b/src/mscorlib/src/System/Reflection/Missing.cs
index f62c5b538c..1a8a641765 100644
--- a/src/mscorlib/src/System/Reflection/Missing.cs
+++ b/src/mscorlib/src/System/Reflection/Missing.cs
@@ -4,13 +4,13 @@
//
-namespace System.Reflection
-{
- using System;
- using System.Runtime.Remoting;
- using System.Runtime.Serialization;
- using System.Diagnostics.Contracts;
+using System;
+using System.Runtime.Remoting;
+using System.Runtime.Serialization;
+using System.Diagnostics.Contracts;
+namespace System.Reflection
+{
// This is not serializable because it is a reflection command.
[Serializable]
public sealed class Missing : ISerializable
diff --git a/src/mscorlib/src/System/Reflection/Module.cs b/src/mscorlib/src/System/Reflection/Module.cs
index bdf95fca26..79ab705b9a 100644
--- a/src/mscorlib/src/System/Reflection/Module.cs
+++ b/src/mscorlib/src/System/Reflection/Module.cs
@@ -5,7 +5,7 @@
////////////////////////////////////////////////////////////////////////////////
//
-namespace System.Reflection
+namespace System.Reflection
{
using System;
using System.Diagnostics.SymbolStore;
@@ -23,37 +23,37 @@ namespace System.Reflection
using System.Diagnostics.Contracts;
[Serializable]
- [Flags]
- public enum PortableExecutableKinds
+ [Flags]
+ public enum PortableExecutableKinds
{
NotAPortableExecutableImage = 0x0,
- ILOnly = 0x1,
-
- Required32Bit = 0x2,
+ ILOnly = 0x1,
- PE32Plus = 0x4,
-
- Unmanaged32Bit = 0x8,
+ Required32Bit = 0x2,
- Preferred32Bit = 0x10,
+ PE32Plus = 0x4,
+
+ Unmanaged32Bit = 0x8,
+
+ Preferred32Bit = 0x10,
}
-
- [Serializable]
- public enum ImageFileMachine
+
+ [Serializable]
+ public enum ImageFileMachine
{
- I386 = 0x014c,
-
- IA64 = 0x0200,
-
- AMD64 = 0x8664,
+ I386 = 0x014c,
+
+ IA64 = 0x0200,
+
+ AMD64 = 0x8664,
- ARM = 0x01c4,
+ ARM = 0x01c4,
}
[Serializable]
public abstract class Module : ISerializable, ICustomAttributeProvider
- {
+ {
#region Static Constructor
static Module()
{
@@ -61,11 +61,11 @@ namespace System.Reflection
_fltObj = new __Filters();
FilterTypeName = new TypeFilter(_fltObj.FilterTypeName);
FilterTypeNameIgnoreCase = new TypeFilter(_fltObj.FilterTypeNameIgnoreCase);
- }
+ }
#endregion
#region Constructor
- protected Module()
+ protected Module()
{
}
#endregion
@@ -274,7 +274,8 @@ namespace System.Reflection
return GetType(className, false, ignoreCase);
}
- public virtual Type GetType(String className) {
+ public virtual Type GetType(String className)
+ {
return GetType(className, false, false);
}
@@ -283,7 +284,7 @@ namespace System.Reflection
throw new NotImplementedException();
}
- public virtual String FullyQualifiedName
+ public virtual String FullyQualifiedName
{
get
{
@@ -291,22 +292,24 @@ namespace System.Reflection
}
}
- public virtual Type[] FindTypes(TypeFilter filter,Object filterCriteria)
+ 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))
+ 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++) {
+ cnt = 0;
+ for (int i = 0; i < c.Length; i++)
+ {
if (c[i] != null)
ret[cnt++] = c[i];
}
@@ -379,7 +382,7 @@ namespace System.Reflection
public FieldInfo GetField(String name)
{
- return GetField(name,Module.DefaultLookup);
+ return GetField(name, Module.DefaultLookup);
}
public virtual FieldInfo GetField(String name, BindingFlags bindingAttr)
@@ -398,7 +401,7 @@ namespace System.Reflection
{
return GetMethods(Module.DefaultLookup);
}
-
+
public virtual MethodInfo[] GetMethods(BindingFlags bindingFlags)
{
// This API was made virtual in V4. Code compiled against V2 might use
@@ -479,9 +482,9 @@ namespace System.Reflection
}
}
- public virtual String Name
+ public virtual String Name
{
- get
+ get
{
// This API was made virtual in V4. Code compiled against V2 might use
// "call" rather than "callvirt" to call it.
@@ -494,8 +497,8 @@ namespace System.Reflection
}
}
- public virtual Assembly Assembly
- {
+ public virtual Assembly Assembly
+ {
[Pure]
get
{
@@ -514,7 +517,7 @@ namespace System.Reflection
// a valid handle for reflection only modules.
public ModuleHandle ModuleHandle
{
- get
+ get
{
return GetModuleHandle();
}
@@ -536,7 +539,7 @@ namespace System.Reflection
#region FCalls
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
+ [SuppressUnmanagedCodeSecurity]
private extern static void GetType(RuntimeModule module, String className, bool ignoreCase, bool throwOnError, ObjectHandleOnStack type, ObjectHandleOnStack keepAlive);
[DllImport(JitHelpers.QCall)]
@@ -566,20 +569,20 @@ namespace System.Reflection
#region Module overrides
private static RuntimeTypeHandle[] ConvertToTypeHandleArray(Type[] genericArguments)
{
- if (genericArguments == null)
+ if (genericArguments == null)
return null;
int size = genericArguments.Length;
RuntimeTypeHandle[] typeHandleArgs = new RuntimeTypeHandle[size];
- for (int i = 0; i < size; i++)
+ for (int i = 0; i < size; i++)
{
Type typeArg = genericArguments[i];
- if (typeArg == null)
+ if (typeArg == null)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidGenericInstArray"));
typeArg = typeArg.UnderlyingSystemType;
- if (typeArg == null)
+ if (typeArg == null)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidGenericInstArray"));
- if (!(typeArg is RuntimeType))
+ if (!(typeArg is RuntimeType))
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidGenericInstArray"));
typeHandleArgs[i] = typeArg.GetTypeHandleInternal();
}
@@ -623,7 +626,7 @@ namespace System.Reflection
RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray(genericTypeArguments);
RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray(genericMethodArguments);
- try
+ try
{
if (!tk.IsMethodDef && !tk.IsMethodSpec)
{
@@ -634,7 +637,7 @@ namespace System.Reflection
unsafe
{
ConstArray sig = MetadataImport.GetMemberRefProps(tk);
-
+
if (*(MdSigCallingConvention*)sig.Signature.ToPointer() == MdSigCallingConvention.Field)
throw new ArgumentException(Environment.GetResourceString("Argument_ResolveMethod", tk, this),
nameof(metadataToken));
@@ -643,20 +646,20 @@ namespace System.Reflection
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)
+ return System.RuntimeType.GetMethodBase(declaringType as RuntimeType, methodHandle);
+ }
+ catch (BadImageFormatException e)
{
throw new ArgumentException(Environment.GetResourceString("Argument_BadImageFormatExceptionResolve"), e);
}
@@ -682,9 +685,9 @@ namespace System.Reflection
try
{
- return declaringType.GetField(fieldName,
- BindingFlags.Static | BindingFlags.Instance |
- BindingFlags.Public | BindingFlags.NonPublic |
+ return declaringType.GetField(fieldName,
+ BindingFlags.Static | BindingFlags.Instance |
+ BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.DeclaredOnly);
}
catch
@@ -704,23 +707,23 @@ namespace System.Reflection
RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray(genericTypeArguments);
RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray(genericMethodArguments);
- try
+ try
{
IRuntimeFieldInfo fieldHandle = null;
-
+
if (!tk.IsFieldDef)
{
if (!tk.IsMemberRef)
throw new ArgumentException(Environment.GetResourceString("Argument_ResolveField", tk, this),
nameof(metadataToken));
- unsafe
+ unsafe
{
ConstArray sig = MetadataImport.GetMemberRefProps(tk);
-
+
if (*(MdSigCallingConvention*)sig.Signature.ToPointer() != MdSigCallingConvention.Field)
throw new ArgumentException(Environment.GetResourceString("Argument_ResolveField", tk, this),
- nameof(metadataToken));
+ nameof(metadataToken));
}
fieldHandle = ModuleHandle.ResolveFieldHandleInternal(GetNativeHandle(), tk, typeArgs, methodArgs);
@@ -728,7 +731,7 @@ namespace System.Reflection
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);
@@ -737,14 +740,14 @@ namespace System.Reflection
return System.RuntimeType.GetFieldInfo(declaringType, fieldHandle);
}
- catch(MissingFieldException)
+ catch (MissingFieldException)
{
return ResolveLiteralField(tk, genericTypeArguments, genericMethodArguments);
}
- catch (BadImageFormatException e)
+ catch (BadImageFormatException e)
{
throw new ArgumentException(Environment.GetResourceString("Argument_BadImageFormatExceptionResolve"), e);
- }
+ }
}
public override Type ResolveType(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
@@ -753,7 +756,7 @@ namespace System.Reflection
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));
@@ -764,16 +767,16 @@ namespace System.Reflection
RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray(genericTypeArguments);
RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray(genericMethodArguments);
- try
+ 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)
+ }
+ catch (BadImageFormatException e)
{
throw new ArgumentException(Environment.GetResourceString("Argument_BadImageFormatExceptionResolve"), e);
}
@@ -806,7 +809,7 @@ namespace System.Reflection
ConstArray sig = MetadataImport.GetMemberRefProps(tk);
- unsafe
+ unsafe
{
if (*(MdSigCallingConvention*)sig.Signature.ToPointer() == MdSigCallingConvention.Field)
{
@@ -816,7 +819,7 @@ namespace System.Reflection
{
return ResolveMethod(tk, genericTypeArguments, genericMethodArguments);
}
- }
+ }
}
throw new ArgumentException(Environment.GetResourceString("Argument_ResolveMember", tk, this),
@@ -835,8 +838,8 @@ namespace System.Reflection
String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Argument_InvalidToken", tk, this)));
string str = MetadataImport.GetUserString(metadataToken);
-
- if (str == null)
+
+ if (str == null)
throw new ArgumentException(
String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Argument_ResolveString"), metadataToken, ToString()));
@@ -858,7 +861,7 @@ namespace System.Reflection
#endregion
#region Data Members
- #pragma warning disable 169
+#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;
@@ -909,7 +912,7 @@ namespace System.Reflection
{
return RuntimeModule.nIsTransientInternal(this.GetNativeHandle());
}
-
+
internal MetadataImport MetadataImport
{
get
@@ -936,12 +939,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(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType));
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
}
-
+
public override bool IsDefined(Type attributeType, bool inherit)
{
if (attributeType == null)
@@ -950,8 +953,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(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType));
return CustomAttribute.IsDefined(this, attributeRuntimeType);
}
@@ -1059,8 +1062,8 @@ namespace System.Reflection
{
if (RuntimeType == null)
return new MethodInfo[0];
-
- return RuntimeType.GetMethods(bindingFlags);
+
+ return RuntimeType.GetMethods(bindingFlags);
}
public override String ScopeName
@@ -1094,12 +1097,12 @@ namespace System.Reflection
public override Assembly Assembly
{
[Pure]
- get
+ get
{
return GetRuntimeAssembly();
}
}
-
+
internal RuntimeAssembly GetRuntimeAssembly()
{
return m_runtimeAssembly;
diff --git a/src/mscorlib/src/System/Reflection/ObfuscateAssemblyAttribute.cs b/src/mscorlib/src/System/Reflection/ObfuscateAssemblyAttribute.cs
index 787f37bced..99b2891235 100644
--- a/src/mscorlib/src/System/Reflection/ObfuscateAssemblyAttribute.cs
+++ b/src/mscorlib/src/System/Reflection/ObfuscateAssemblyAttribute.cs
@@ -10,7 +10,7 @@ using System.Reflection;
namespace System.Reflection
{
- [AttributeUsage (AttributeTargets.Assembly, AllowMultiple=false, Inherited=false)]
+ [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)]
public sealed class ObfuscateAssemblyAttribute : Attribute
{
private bool m_assemblyIsPrivate;
diff --git a/src/mscorlib/src/System/Reflection/ObfuscationAttribute.cs b/src/mscorlib/src/System/Reflection/ObfuscationAttribute.cs
index c7c7c18550..1dfadf1f09 100644
--- a/src/mscorlib/src/System/Reflection/ObfuscationAttribute.cs
+++ b/src/mscorlib/src/System/Reflection/ObfuscationAttribute.cs
@@ -11,7 +11,7 @@ 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
+ public sealed class ObfuscationAttribute : Attribute
{
private bool m_strip = true;
private bool m_exclude = true;
diff --git a/src/mscorlib/src/System/Reflection/ParameterAttributes.cs b/src/mscorlib/src/System/Reflection/ParameterAttributes.cs
index acae3a6ec1..e4f3476d59 100644
--- a/src/mscorlib/src/System/Reflection/ParameterAttributes.cs
+++ b/src/mscorlib/src/System/Reflection/ParameterAttributes.cs
@@ -10,26 +10,28 @@
// associated with a Parameter. These are defined in CorHdr.h.
//
//
-namespace System.Reflection {
-
- using System;
+
+using System;
+
+namespace System.Reflection
+{
// This Enum matchs the CorParamAttr defined in CorHdr.h
-[Serializable]
+ [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
+ 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
+ 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/ParameterInfo.cs b/src/mscorlib/src/System/Reflection/ParameterInfo.cs
index fad4402aff..373201f634 100644
--- a/src/mscorlib/src/System/Reflection/ParameterInfo.cs
+++ b/src/mscorlib/src/System/Reflection/ParameterInfo.cs
@@ -20,10 +20,10 @@ namespace System.Reflection
public class ParameterInfo : ICustomAttributeProvider, IObjectReference
{
#region Legacy Protected Members
- protected String NameImpl;
- protected Type ClassImpl;
- protected int PositionImpl;
- protected ParameterAttributes AttrsImpl;
+ 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
@@ -43,63 +43,65 @@ namespace System.Reflection
#endregion
#region Constructor
- protected ParameterInfo()
- {
- }
+ 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)
+ internal void SetName(String name)
{
NameImpl = name;
}
-
- internal void SetAttributes(ParameterAttributes attributes)
+
+ internal void SetAttributes(ParameterAttributes attributes)
{
AttrsImpl = attributes;
}
#endregion
#region Public Methods
- public virtual Type ParameterType
- {
- get
+ public virtual Type ParameterType
+ {
+ get
{
return ClassImpl;
- }
- }
-
- public virtual String Name
- {
- get
+ }
+ }
+
+ public virtual String Name
+ {
+ get
{
return NameImpl;
- }
+ }
}
- public virtual bool HasDefaultValue { get { throw new NotImplementedException(); } }
+ 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 Object RawDefaultValue { get { throw new NotImplementedException(); } }
- public virtual int Position { get { return PositionImpl; } }
+ public virtual int Position { get { return PositionImpl; } }
public virtual ParameterAttributes Attributes { get { return AttrsImpl; } }
- public virtual MemberInfo Member {
- get {
+ 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 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
{
@@ -117,12 +119,12 @@ namespace System.Reflection
}
}
- public virtual Type[] GetRequiredCustomModifiers()
+ public virtual Type[] GetRequiredCustomModifiers()
{
return EmptyArray<Type>.Value;
}
- public virtual Type[] GetOptionalCustomModifiers()
+ public virtual Type[] GetOptionalCustomModifiers()
{
return EmptyArray<Type>.Value;
}
@@ -413,7 +415,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 +667,7 @@ namespace System.Reflection
{
get
{
- return m_tkParamDef;
+ return m_tkParamDef;
}
}
diff --git a/src/mscorlib/src/System/Reflection/ParameterModifier.cs b/src/mscorlib/src/System/Reflection/ParameterModifier.cs
index a2bfeab934..652831c94e 100644
--- a/src/mscorlib/src/System/Reflection/ParameterModifier.cs
+++ b/src/mscorlib/src/System/Reflection/ParameterModifier.cs
@@ -1,20 +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.Diagnostics.Contracts;
-namespace System.Reflection
-{
- using System;
+using System;
+namespace System.Reflection
+{
[Serializable]
- public struct ParameterModifier
+ public struct ParameterModifier
{
#region Private Data Members
private bool[] _byRef;
#endregion
#region Constructor
- public ParameterModifier(int parameterCount)
+ public ParameterModifier(int parameterCount)
{
if (parameterCount <= 0)
throw new ArgumentException(Environment.GetResourceString("Arg_ParmArraySize"));
@@ -29,13 +30,13 @@ namespace System.Reflection
#endregion
#region Public Members
- public bool this[int index]
+ public bool this[int index]
{
- get
+ get
{
- return _byRef[index];
+ return _byRef[index];
}
- set
+ set
{
_byRef[index] = value;
}
diff --git a/src/mscorlib/src/System/Reflection/Pointer.cs b/src/mscorlib/src/System/Reflection/Pointer.cs
index 9f1a38366a..91e205e3a7 100644
--- a/src/mscorlib/src/System/Reflection/Pointer.cs
+++ b/src/mscorlib/src/System/Reflection/Pointer.cs
@@ -10,7 +10,9 @@
//
//
//
-namespace System.Reflection {
+
+namespace System.Reflection
+{
using System;
using CultureInfo = System.Globalization.CultureInfo;
using System.Runtime.Serialization;
@@ -24,7 +26,7 @@ namespace System.Reflection {
unsafe private void* _ptr;
private RuntimeType _ptrType;
- private Pointer() {}
+ private Pointer() { }
private unsafe Pointer(SerializationInfo info, StreamingContext context)
{
@@ -35,11 +37,12 @@ namespace System.Reflection {
// 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) {
+ 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));
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBePointer"), nameof(ptr));
Contract.EndContractBlock();
RuntimeType rt = type as RuntimeType;
@@ -53,21 +56,25 @@ namespace System.Reflection {
}
// Returned the stored pointer.
- public static unsafe void* Unbox(Object ptr) {
+ public static unsafe void* Unbox(Object ptr)
+ {
if (!(ptr is Pointer))
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBePointer"),nameof(ptr));
+ throw new ArgumentException(Environment.GetResourceString("Arg_MustBePointer"), nameof(ptr));
return ((Pointer)ptr)._ptr;
}
-
- internal RuntimeType GetPointerType() {
+
+ internal RuntimeType GetPointerType()
+ {
return _ptrType;
}
-
- internal unsafe Object GetPointerValue() {
+
+ internal unsafe Object GetPointerValue()
+ {
return (IntPtr)_ptr;
}
- unsafe void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
+ 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
index 4a5617ba5e..188bc0e87e 100644
--- a/src/mscorlib/src/System/Reflection/PropertyAttributes.cs
+++ b/src/mscorlib/src/System/Reflection/PropertyAttributes.cs
@@ -10,23 +10,25 @@
// with a property. The values here are defined in Corhdr.h.
//
//
-namespace System.Reflection {
-
- using System;
+
+using System;
+
+namespace System.Reflection
+{
// This Enum matchs the CorPropertyAttr defined in CorHdr.h
-[Serializable]
-[Flags]
+ [Serializable]
+ [Flags]
public enum PropertyAttributes
{
- None = 0x0000,
- SpecialName = 0x0200, // property is special. Name describes how.
+ 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
+ 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/PropertyInfo.cs b/src/mscorlib/src/System/Reflection/PropertyInfo.cs
index e8c2837785..3438b967f1 100644
--- a/src/mscorlib/src/System/Reflection/PropertyInfo.cs
+++ b/src/mscorlib/src/System/Reflection/PropertyInfo.cs
@@ -71,19 +71,19 @@ namespace System.Reflection
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]
@@ -95,7 +95,7 @@ namespace System.Reflection
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
- public virtual Object GetValue(Object obj,Object[] index)
+ public virtual Object GetValue(Object obj, Object[] index)
{
return GetValue(obj, BindingFlags.Default, null, index, null);
}
@@ -144,7 +144,7 @@ namespace System.Reflection
public MethodInfo GetSetMethod() { return GetSetMethod(false); }
- public bool IsSpecialName { get { return(Attributes & PropertyAttributes.SpecialName) != 0; } }
+ public bool IsSpecialName { get { return (Attributes & PropertyAttributes.SpecialName) != 0; } }
#endregion
}
@@ -177,14 +177,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 +297,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(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType));
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
}
@@ -311,8 +311,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(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType));
return CustomAttribute.IsDefined(this, attributeRuntimeType);
}
@@ -325,21 +325,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 +358,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 +373,7 @@ namespace System.Reflection
{
return Signature.GetCustomModifiers(0, true);
}
-
+
public override Type[] GetOptionalCustomModifiers()
{
return Signature.GetCustomModifiers(0, false);
@@ -382,19 +382,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"));
-
+
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 +406,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 +415,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 +428,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 +436,7 @@ namespace System.Reflection
return m_setterMethod;
}
- public override ParameterInfo[] GetIndexParameters()
+ public override ParameterInfo[] GetIndexParameters()
{
ParameterInfo[] indexParams = GetIndexParametersNoCopy();
@@ -496,7 +496,7 @@ namespace System.Reflection
return m_parameters;
}
- public override PropertyAttributes Attributes
+ public override PropertyAttributes Attributes
{
get
{
@@ -504,7 +504,7 @@ namespace System.Reflection
}
}
- public override bool CanRead
+ public override bool CanRead
{
get
{
@@ -512,7 +512,7 @@ namespace System.Reflection
}
}
- public override bool CanWrite
+ public override bool CanWrite
{
get
{
@@ -524,21 +524,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);
+ return m.Invoke(obj, invokeAttr, binder, index, null);
}
[DebuggerStepThroughAttribute]
@@ -547,9 +546,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,7 +556,6 @@ 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)
@@ -565,16 +563,16 @@ namespace System.Reflection
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;
@@ -609,5 +607,4 @@ namespace System.Reflection
}
#endregion
}
-
}
diff --git a/src/mscorlib/src/System/Reflection/ReflectionContext.cs b/src/mscorlib/src/System/Reflection/ReflectionContext.cs
index 34f692166c..e11480d6cf 100644
--- a/src/mscorlib/src/System/Reflection/ReflectionContext.cs
+++ b/src/mscorlib/src/System/Reflection/ReflectionContext.cs
@@ -13,10 +13,10 @@
**
=============================================================================*/
+using System;
+
namespace System.Reflection
{
- using System;
-
public abstract class ReflectionContext
{
protected ReflectionContext() { }
diff --git a/src/mscorlib/src/System/Reflection/ReflectionTypeLoadException.cs b/src/mscorlib/src/System/Reflection/ReflectionTypeLoadException.cs
index cccf060645..908b79513d 100644
--- a/src/mscorlib/src/System/Reflection/ReflectionTypeLoadException.cs
+++ b/src/mscorlib/src/System/Reflection/ReflectionTypeLoadException.cs
@@ -15,19 +15,23 @@
//
//
//
-namespace System.Reflection {
-
- using System;
- using System.Runtime.Serialization;
- using System.Diagnostics.Contracts;
+
+using System;
+using System.Runtime.Serialization;
+using System.Diagnostics.Contracts;
+
+namespace System.Reflection
+{
[Serializable]
- public sealed class ReflectionTypeLoadException : SystemException, ISerializable {
+ 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")) {
+ : base(Environment.GetResourceString("ReflectionTypeLoad_LoadFailed"))
+ {
SetErrorCode(__HResults.COR_E_REFLECTIONTYPELOAD);
}
@@ -45,21 +49,26 @@ namespace System.Reflection {
SetErrorCode(__HResults.COR_E_REFLECTIONTYPELOAD);
}
- internal ReflectionTypeLoadException(SerializationInfo info, StreamingContext context) : base (info, context) {
+ 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 Type[] Types
+ {
+ get { return _classes; }
}
-
- public Exception[] LoaderExceptions {
- get {return _exceptions;}
- }
- public override void GetObjectData(SerializationInfo info, StreamingContext context) {
- if (info==null) {
+ public Exception[] LoaderExceptions
+ {
+ get { return _exceptions; }
+ }
+
+ public override void GetObjectData(SerializationInfo info, StreamingContext context)
+ {
+ if (info == null)
+ {
throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
@@ -67,6 +76,5 @@ namespace System.Reflection {
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
index 5c419ebb2d..d751a54278 100644
--- a/src/mscorlib/src/System/Reflection/ResourceAttributes.cs
+++ b/src/mscorlib/src/System/Reflection/ResourceAttributes.cs
@@ -10,14 +10,16 @@
// with a manifest resource. The values here are defined in Corhdr.h.
//
//
-namespace System.Reflection {
-
- using System;
-[Serializable]
-[Flags]
+
+using System;
+
+namespace System.Reflection
+{
+ [Serializable]
+ [Flags]
public enum ResourceAttributes
{
- Public = 0x0001,
- Private = 0x0002,
+ Public = 0x0001,
+ Private = 0x0002,
}
}
diff --git a/src/mscorlib/src/System/Reflection/RuntimeReflectionExtensions.cs b/src/mscorlib/src/System/Reflection/RuntimeReflectionExtensions.cs
index 49262634e3..9423ee2dc8 100644
--- a/src/mscorlib/src/System/Reflection/RuntimeReflectionExtensions.cs
+++ b/src/mscorlib/src/System/Reflection/RuntimeReflectionExtensions.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.Collections.Generic;
@@ -47,8 +48,8 @@ namespace System.Reflection
public static PropertyInfo GetRuntimeProperty(this Type type, string name)
{
- CheckAndThrow(type);
- return type.GetProperty(name);
+ CheckAndThrow(type);
+ return type.GetProperty(name);
}
public static EventInfo GetRuntimeEvent(this Type type, string name)
{
@@ -65,7 +66,8 @@ namespace System.Reflection
CheckAndThrow(type);
return type.GetField(name);
}
- public static MethodInfo GetRuntimeBaseDefinition(this MethodInfo method){
+ public static MethodInfo GetRuntimeBaseDefinition(this MethodInfo method)
+ {
CheckAndThrow(method);
return method.GetBaseDefinition();
}
diff --git a/src/mscorlib/src/System/Reflection/StrongNameKeyPair.cs b/src/mscorlib/src/System/Reflection/StrongNameKeyPair.cs
index 0121982489..280e1c04f4 100644
--- a/src/mscorlib/src/System/Reflection/StrongNameKeyPair.cs
+++ b/src/mscorlib/src/System/Reflection/StrongNameKeyPair.cs
@@ -13,26 +13,27 @@
**
**
===========================================================*/
+
+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;
+
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
+ public class StrongNameKeyPair : IDeserializationCallback, ISerializable
{
- private bool _keyPairExported;
- private byte[] _keyPairArray;
- private String _keyPairContainer;
- private byte[] _publicKey;
+ private bool _keyPairExported;
+ private byte[] _keyPairArray;
+ private String _keyPairContainer;
+ private byte[] _publicKey;
// Build key pair from file.
public StrongNameKeyPair(FileStream keyPairFile)
@@ -60,19 +61,20 @@ namespace System.Reflection
_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[]));
+
+ 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
@@ -82,7 +84,8 @@ namespace System.Reflection
}
/// <internalonly/>
- void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context) {
+ void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
+ {
info.AddValue("_keyPairExported", _keyPairExported);
info.AddValue("_keyPairArray", _keyPairArray);
info.AddValue("_keyPairContainer", _keyPairContainer);
@@ -90,6 +93,6 @@ namespace System.Reflection
}
/// <internalonly/>
- void IDeserializationCallback.OnDeserialization (Object sender) {}
+ void IDeserializationCallback.OnDeserialization(Object sender) { }
}
}
diff --git a/src/mscorlib/src/System/Reflection/TargetException.cs b/src/mscorlib/src/System/Reflection/TargetException.cs
index dcbb38833e..537d1680f4 100644
--- a/src/mscorlib/src/System/Reflection/TargetException.cs
+++ b/src/mscorlib/src/System/Reflection/TargetException.cs
@@ -13,25 +13,32 @@
//
//
//
-namespace System.Reflection {
-
- using System;
- using System.Runtime.Serialization;
+
+using System;
+using System.Runtime.Serialization;
+
+namespace System.Reflection
+{
[Serializable]
- public class TargetException : ApplicationException {
- public TargetException() : base() {
+ public class TargetException : ApplicationException
+ {
+ public TargetException() : base()
+ {
SetErrorCode(__HResults.COR_E_TARGET);
}
-
- public TargetException(String message) : base(message) {
+
+ public TargetException(String message) : base(message)
+ {
SetErrorCode(__HResults.COR_E_TARGET);
}
-
- public TargetException(String message, Exception inner) : base(message, inner) {
+
+ public TargetException(String message, Exception inner) : base(message, inner)
+ {
SetErrorCode(__HResults.COR_E_TARGET);
}
- protected TargetException(SerializationInfo info, StreamingContext context) : base (info, context) {
+ 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
index 7bbc93df2a..326b571e18 100644
--- a/src/mscorlib/src/System/Reflection/TargetInvocationException.cs
+++ b/src/mscorlib/src/System/Reflection/TargetInvocationException.cs
@@ -12,35 +12,43 @@
//
//
//
-namespace System.Reflection {
-
-
- using System;
- using System.Runtime.Serialization;
+
+
+using System;
+using System.Runtime.Serialization;
+
+namespace System.Reflection
+{
[Serializable]
- public sealed class TargetInvocationException : ApplicationException {
+ public sealed class TargetInvocationException : ApplicationException
+ {
// This exception is not creatable without specifying the
// inner exception.
private TargetInvocationException()
- : base(Environment.GetResourceString("Arg_TargetInvocationException")) {
+ : base(Environment.GetResourceString("Arg_TargetInvocationException"))
+ {
SetErrorCode(__HResults.COR_E_TARGETINVOCATION);
}
// This is called from within the runtime.
- private TargetInvocationException(String message) : base(message) {
+ private TargetInvocationException(String message) : base(message)
+ {
SetErrorCode(__HResults.COR_E_TARGETINVOCATION);
- }
-
- public TargetInvocationException(System.Exception inner)
- : base(Environment.GetResourceString("Arg_TargetInvocationException"), inner) {
+ }
+
+ 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) {
+
+ public TargetInvocationException(String message, Exception inner) : base(message, inner)
+ {
SetErrorCode(__HResults.COR_E_TARGETINVOCATION);
}
- internal TargetInvocationException(SerializationInfo info, StreamingContext context) : base (info, context) {
+ 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
index 7a07b20acd..3e2bce4b26 100644
--- a/src/mscorlib/src/System/Reflection/TargetParameterCountException.cs
+++ b/src/mscorlib/src/System/Reflection/TargetParameterCountException.cs
@@ -12,29 +12,35 @@
//
//
//
-namespace System.Reflection {
+namespace System.Reflection
+{
using System;
using SystemException = System.SystemException;
using System.Runtime.Serialization;
[Serializable]
- public sealed class TargetParameterCountException : ApplicationException {
+ public sealed class TargetParameterCountException : ApplicationException
+ {
public TargetParameterCountException()
- : base(Environment.GetResourceString("Arg_TargetParameterCountException")) {
+ : base(Environment.GetResourceString("Arg_TargetParameterCountException"))
+ {
SetErrorCode(__HResults.COR_E_TARGETPARAMCOUNT);
}
-
- public TargetParameterCountException(String message)
- : base(message) {
+
+ public TargetParameterCountException(String message)
+ : base(message)
+ {
SetErrorCode(__HResults.COR_E_TARGETPARAMCOUNT);
}
-
- public TargetParameterCountException(String message, Exception inner)
- : base(message, inner) {
+
+ public TargetParameterCountException(String message, Exception inner)
+ : base(message, inner)
+ {
SetErrorCode(__HResults.COR_E_TARGETPARAMCOUNT);
}
- internal TargetParameterCountException(SerializationInfo info, StreamingContext context) : base (info, context) {
+ 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
index 25aa113d2e..ad7d29dd1f 100644
--- a/src/mscorlib/src/System/Reflection/TypeAttributes.cs
+++ b/src/mscorlib/src/System/Reflection/TypeAttributes.cs
@@ -2,63 +2,65 @@
// 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;
+using System.Runtime.InteropServices;
+using System;
+
+namespace System.Reflection
+{
// This Enum matchs the CorTypeAttr defined in CorHdr.h
-[Serializable]
-[Flags]
+ [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.
-
+ 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
-
+ 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.
-
+ 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.
-
+ 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.
+ Import = 0x00001000, // Class / interface is imported
+ Serializable = 0x00002000, // The class is Serializable.
- WindowsRuntime = 0x00004000, // Type is a Windows Runtime type.
+ 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.
+ 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.
+ 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.
- }
+ 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
index 6a77a95853..748293a697 100644
--- a/src/mscorlib/src/System/Reflection/TypeDelegator.cs
+++ b/src/mscorlib/src/System/Reflection/TypeDelegator.cs
@@ -6,8 +6,8 @@
//
// This class wraps a Type object and delegates all methods to that Type.
-namespace System.Reflection {
-
+namespace System.Reflection
+{
using System;
using System.Runtime.InteropServices;
using System.Diagnostics.Contracts;
@@ -16,135 +16,147 @@ namespace System.Reflection {
[Serializable]
public class TypeDelegator : 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());
}
protected Type typeImpl;
-
- protected TypeDelegator() {}
-
- public TypeDelegator(Type delegatingType) {
+
+ 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 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)
+
+ 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);
+ return typeImpl.InvokeMember(name, invokeAttr, binder, target, args, modifiers, culture, namedParameters);
}
-
- public override Module Module {
- get {return typeImpl.Module;}
+
+ public override Module Module
+ {
+ get { return typeImpl.Module; }
}
-
- public override Assembly Assembly {
- get {return typeImpl.Assembly;}
+
+ public override Assembly Assembly
+ {
+ get { return typeImpl.Assembly; }
}
- public override RuntimeTypeHandle TypeHandle {
- get{return typeImpl.TypeHandle;}
+ public override RuntimeTypeHandle TypeHandle
+ {
+ get { return typeImpl.TypeHandle; }
}
-
- public override String Name {
- get{return typeImpl.Name;}
+
+ public override String Name
+ {
+ get { return typeImpl.Name; }
}
-
- public override String FullName {
- get{return typeImpl.FullName;}
+
+ public override String FullName
+ {
+ get { return typeImpl.FullName; }
}
-
- public override String Namespace {
- get{return typeImpl.Namespace;}
+
+ public override String Namespace
+ {
+ get { return typeImpl.Namespace; }
}
-
- public override String AssemblyQualifiedName {
- get {
+
+ public override String AssemblyQualifiedName
+ {
+ get
+ {
return typeImpl.AssemblyQualifiedName;
}
}
-
- public override Type BaseType {
- get{return typeImpl.BaseType;}
+
+ public override Type BaseType
+ {
+ get { return typeImpl.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 typeImpl.GetConstructor(bindingAttr,binder,callConvention,types,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)
+
+ 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);
+ return typeImpl.GetMethod(name, bindingAttr);
else
- return typeImpl.GetMethod(name,bindingAttr,binder,callConvention,types,modifiers);
+ 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);
+ 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);
+ return typeImpl.GetInterface(name, ignoreCase);
}
-
+
public override Type[] GetInterfaces()
{
return typeImpl.GetInterfaces();
}
-
- public override EventInfo GetEvent(String name,BindingFlags bindingAttr)
+
+ public override EventInfo GetEvent(String name, BindingFlags bindingAttr)
{
- return typeImpl.GetEvent(name,bindingAttr);
+ return typeImpl.GetEvent(name, bindingAttr);
}
-
+
public override EventInfo[] GetEvents()
{
return typeImpl.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)
{
if (returnType == null && types == null)
- return typeImpl.GetProperty(name,bindingAttr);
+ return typeImpl.GetProperty(name, bindingAttr);
else
- return typeImpl.GetProperty(name,bindingAttr,binder,returnType,types,modifiers);
+ return typeImpl.GetProperty(name, bindingAttr, binder, returnType, types, modifiers);
}
-
+
public override PropertyInfo[] GetProperties(BindingFlags bindingAttr)
{
return typeImpl.GetProperties(bindingAttr);
@@ -154,7 +166,7 @@ namespace System.Reflection {
{
return typeImpl.GetEvents(bindingAttr);
}
-
+
public override Type[] GetNestedTypes(BindingFlags bindingAttr)
{
return typeImpl.GetNestedTypes(bindingAttr);
@@ -162,29 +174,29 @@ namespace System.Reflection {
public override Type GetNestedType(String name, BindingFlags bindingAttr)
{
- return typeImpl.GetNestedType(name,bindingAttr);
+ return typeImpl.GetNestedType(name, bindingAttr);
}
- public override MemberInfo[] GetMember(String name, MemberTypes type, BindingFlags bindingAttr)
+ public override MemberInfo[] GetMember(String name, MemberTypes type, BindingFlags bindingAttr)
{
- return typeImpl.GetMember(name,type,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;
@@ -199,12 +211,12 @@ namespace System.Reflection {
{
return typeImpl.IsPointer;
}
-
- protected override bool IsValueTypeImpl()
+
+ protected override bool IsValueTypeImpl()
{
return typeImpl.IsValueType;
}
-
+
protected override bool IsCOMObjectImpl()
{
return typeImpl.IsCOMObject;
@@ -227,12 +239,12 @@ namespace System.Reflection {
{
return typeImpl.HasElementType;
}
-
- public override Type UnderlyingSystemType
+
+ public override Type UnderlyingSystemType
{
- get {return typeImpl.UnderlyingSystemType;}
+ get { return typeImpl.UnderlyingSystemType; }
}
-
+
// ICustomAttributeProvider
public override Object[] GetCustomAttributes(bool inherit)
{
diff --git a/src/mscorlib/src/System/Reflection/TypeFilter.cs b/src/mscorlib/src/System/Reflection/TypeFilter.cs
index 4837a303a1..97a089978a 100644
--- a/src/mscorlib/src/System/Reflection/TypeFilter.cs
+++ b/src/mscorlib/src/System/Reflection/TypeFilter.cs
@@ -10,8 +10,9 @@
// a list of Types.
//
//
-namespace System.Reflection {
+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
index 61d7bb27a9..aaf5c731b3 100644
--- a/src/mscorlib/src/System/Reflection/TypeInfo.cs
+++ b/src/mscorlib/src/System/Reflection/TypeInfo.cs
@@ -13,37 +13,42 @@
**
=============================================================================*/
+using System;
+using System.Runtime.CompilerServices;
+using System.Collections.Generic;
+using System.Diagnostics.Contracts;
+
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
+ public abstract class TypeInfo : Type, IReflectableType
{
[FriendAccessAllowed]
internal TypeInfo() { }
- TypeInfo IReflectableType.GetTypeInfo(){
+ TypeInfo IReflectableType.GetTypeInfo()
+ {
return this;
}
- public virtual Type AsType(){
+ public virtual Type AsType()
+ {
return (Type)this;
}
- public virtual Type[] GenericTypeParameters{
- get{
- if(IsGenericTypeDefinition){
+ public virtual Type[] GenericTypeParameters
+ {
+ get
+ {
+ if (IsGenericTypeDefinition)
+ {
return GetGenericArguments();
}
- else{
+ else
+ {
return Type.EmptyTypes;
}
-
}
}
//a re-implementation of ISAF from Type, skipping the use of UnderlyingType
@@ -76,8 +81,8 @@ namespace System.Reflection
return false;
}
-#region moved over from Type
- // Fields
+ #region moved over from Type
+ // Fields
public virtual EventInfo GetDeclaredEvent(String name)
{
@@ -102,10 +107,13 @@ namespace System.Reflection
}
public virtual System.Reflection.TypeInfo GetDeclaredNestedType(String name)
{
- var nt=GetNestedType(name, Type.DeclaredOnlyLookup);
- if(nt == null){
+ var nt = GetNestedType(name, Type.DeclaredOnlyLookup);
+ if (nt == null)
+ {
return null; //the extension method GetTypeInfo throws for null
- }else{
+ }
+ else
+ {
return nt.GetTypeInfo();
}
}
@@ -118,7 +126,7 @@ namespace System.Reflection
- // Properties
+ // Properties
public virtual IEnumerable<ConstructorInfo> DeclaredConstructors
{
@@ -163,9 +171,10 @@ namespace System.Reflection
{
get
{
- foreach (var t in GetNestedTypes(Type.DeclaredOnlyLookup)){
- yield return t.GetTypeInfo();
- }
+ foreach (var t in GetNestedTypes(Type.DeclaredOnlyLookup))
+ {
+ yield return t.GetTypeInfo();
+ }
}
}
@@ -186,9 +195,7 @@ namespace System.Reflection
}
}
-
-#endregion
-
+ #endregion
}
}
diff --git a/src/mscorlib/src/System/Reflection/__Filters.cs b/src/mscorlib/src/System/Reflection/__Filters.cs
index 8edcd0d7cb..582fb5a873 100644
--- a/src/mscorlib/src/System/Reflection/__Filters.cs
+++ b/src/mscorlib/src/System/Reflection/__Filters.cs
@@ -13,55 +13,59 @@
//
//
//
-namespace System.Reflection {
- using System;
- using System.Globalization;
+using System;
+using System.Globalization;
+
+namespace System.Reflection
+{
[Serializable]
- internal class __Filters {
-
+ 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)
+ 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;
+
+ 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] == '*') {
+ 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))
+ if (filterCriteria == null || !(filterCriteria is String))
throw new InvalidFilterCriteriaException(System.Environment.GetResourceString("RFLCT.FltCritString"));
-
- String str = (String) filterCriteria;
+
+ 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] == '*') {
+ 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);
+ return (String.Compare(name, 0, str, 0, str.Length, StringComparison.OrdinalIgnoreCase) == 0);
else
return false;
}
- return (String.Compare(str,cls.Name, StringComparison.OrdinalIgnoreCase) == 0);
+ 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..da4ee812a6 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");
@@ -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 .
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
index de8f9db18e..f18e5baa8d 100644
--- a/src/mscorlib/src/System/Resources/IResourceReader.cs
+++ b/src/mscorlib/src/System/Resources/IResourceReader.cs
@@ -12,11 +12,13 @@
**
**
===========================================================*/
-namespace System.Resources {
- using System;
- using System.IO;
- using System.Collections;
-
+
+using System;
+using System.IO;
+using System.Collections;
+
+namespace System.Resources
+{
public interface IResourceReader : IEnumerable, IDisposable
{
// Interface does not need to be marked with the serializable attribute
diff --git a/src/mscorlib/src/System/Resources/ManifestBasedResourceGroveler.cs b/src/mscorlib/src/System/Resources/ManifestBasedResourceGroveler.cs
index 39bd5062e4..3ef0066e7e 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)
@@ -131,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
@@ -154,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) {
+ 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));
}
fallbackLocation = (UltimateResourceFallbackLocation)fallback;
}
- else {
+ else
+ {
fallbackLocation = UltimateResourceFallbackLocation.MainAssembly;
return CultureInfo.InvariantCulture;
}
@@ -179,7 +181,7 @@ 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;
}
@@ -201,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)
@@ -293,7 +295,6 @@ namespace System.Resources {
{
store.Position = startPos;
}
-
}
if (_mediator.UserResourceSet == null)
@@ -491,7 +492,7 @@ namespace System.Resources {
private String GetSatelliteAssemblyName()
{
String satAssemblyName = _mediator.MainAssembly.GetSimpleName();
- satAssemblyName += ".resources";
+ satAssemblyName += ".resources";
return satAssemblyName;
}
@@ -529,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);
@@ -544,9 +545,9 @@ namespace System.Resources {
throw new MissingManifestResourceException(Environment.GetResourceString("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
index 2e82f19c7b..9401806134 100644
--- a/src/mscorlib/src/System/Resources/MissingManifestResourceException.cs
+++ b/src/mscorlib/src/System/Resources/MissingManifestResourceException.cs
@@ -16,26 +16,31 @@
using System;
using System.Runtime.Serialization;
-namespace System.Resources {
+namespace System.Resources
+{
[Serializable]
public class MissingManifestResourceException : SystemException
{
- public MissingManifestResourceException()
- : base(Environment.GetResourceString("Arg_MissingManifestResourceException")) {
+ public MissingManifestResourceException()
+ : base(Environment.GetResourceString("Arg_MissingManifestResourceException"))
+ {
SetErrorCode(System.__HResults.COR_E_MISSINGMANIFESTRESOURCE);
}
-
- public MissingManifestResourceException(String message)
- : base(message) {
+
+ public MissingManifestResourceException(String message)
+ : base(message)
+ {
SetErrorCode(System.__HResults.COR_E_MISSINGMANIFESTRESOURCE);
}
-
- public MissingManifestResourceException(String message, Exception inner)
- : base(message, inner) {
+
+ public MissingManifestResourceException(String message, Exception inner)
+ : base(message, inner)
+ {
SetErrorCode(System.__HResults.COR_E_MISSINGMANIFESTRESOURCE);
}
- protected MissingManifestResourceException(SerializationInfo info, StreamingContext context) : base (info, context) {
+ 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
index fc676a8dd5..f1f1494290 100644
--- a/src/mscorlib/src/System/Resources/MissingSatelliteAssemblyException.cs
+++ b/src/mscorlib/src/System/Resources/MissingSatelliteAssemblyException.cs
@@ -18,37 +18,44 @@
using System;
using System.Runtime.Serialization;
-namespace System.Resources {
+namespace System.Resources
+{
[Serializable]
public class MissingSatelliteAssemblyException : SystemException
{
private String _cultureName;
- public MissingSatelliteAssemblyException()
- : base(Environment.GetResourceString("MissingSatelliteAssembly_Default")) {
+ public MissingSatelliteAssemblyException()
+ : base(Environment.GetResourceString("MissingSatelliteAssembly_Default"))
+ {
SetErrorCode(System.__HResults.COR_E_MISSINGSATELLITEASSEMBLY);
}
-
- public MissingSatelliteAssemblyException(String message)
- : base(message) {
+
+ public MissingSatelliteAssemblyException(String message)
+ : base(message)
+ {
SetErrorCode(System.__HResults.COR_E_MISSINGSATELLITEASSEMBLY);
}
-
- public MissingSatelliteAssemblyException(String message, String cultureName)
- : base(message) {
+
+ 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) {
+ public MissingSatelliteAssemblyException(String message, Exception inner)
+ : base(message, inner)
+ {
SetErrorCode(System.__HResults.COR_E_MISSINGSATELLITEASSEMBLY);
}
- protected MissingSatelliteAssemblyException(SerializationInfo info, StreamingContext context) : base (info, context) {
+ protected MissingSatelliteAssemblyException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
}
- public String CultureName {
+ public String CultureName
+ {
get { return _cultureName; }
}
}
diff --git a/src/mscorlib/src/System/Resources/NeutralResourcesLanguageAttribute.cs b/src/mscorlib/src/System/Resources/NeutralResourcesLanguageAttribute.cs
index a2ed6fbd57..83fb51d139 100644
--- a/src/mscorlib/src/System/Resources/NeutralResourcesLanguageAttribute.cs
+++ b/src/mscorlib/src/System/Resources/NeutralResourcesLanguageAttribute.cs
@@ -21,12 +21,13 @@
** through an internal runtime call.
===========================================================*/
-namespace System.Resources {
- using System;
- using System.Diagnostics.Contracts;
-
- [AttributeUsage(AttributeTargets.Assembly, AllowMultiple=false)]
- public sealed class NeutralResourcesLanguageAttribute : Attribute
+using System;
+using System.Diagnostics.Contracts;
+
+namespace System.Resources
+{
+ [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)]
+ public sealed class NeutralResourcesLanguageAttribute : Attribute
{
private String _culture;
private UltimateResourceFallbackLocation _fallbackLoc;
@@ -53,11 +54,13 @@ namespace System.Resources {
_fallbackLoc = location;
}
- public String CultureName {
+ public String CultureName
+ {
get { return _culture; }
}
- public UltimateResourceFallbackLocation Location {
+ 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 f57995c92d..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.
diff --git a/src/mscorlib/src/System/Resources/ResourceManager.cs b/src/mscorlib/src/System/Resources/ResourceManager.cs
index a672f45e22..8ac9ed0dbb 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;
@@ -44,14 +45,15 @@ namespace System.Resources {
[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;
-
+
[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();
@@ -299,10 +302,10 @@ namespace System.Resources {
[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();
@@ -330,9 +333,9 @@ namespace System.Resources {
[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();
@@ -341,7 +344,7 @@ namespace System.Resources {
MainAssembly = assembly;
BaseNameField = baseName;
-
+
if (usingResourceSet != null && (usingResourceSet != _minResourceSet) && !(usingResourceSet.IsSubclassOf(_minResourceSet)))
throw new ArgumentException(Environment.GetResourceString("Arg_ResMgrNotResSet"), nameof(usingResourceSet));
_userResourceSet = usingResourceSet;
@@ -355,11 +358,11 @@ namespace System.Resources {
if (assembly == typeof(Object).Assembly && m_callingAssembly != assembly)
m_callingAssembly = null;
}
-
+
[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();
@@ -369,7 +372,7 @@ namespace System.Resources {
_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;
}
@@ -584,15 +597,18 @@ namespace System.Resources {
// loaded as well for resource inheritance.
//
[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)
+ 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;
}
}
@@ -627,12 +645,12 @@ namespace System.Resources {
// threadsafe methods such as GetResourceSet, GetString, & GetObject.
// This will take a minimal number of locks.
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
- protected virtual ResourceSet InternalGetResourceSet(CultureInfo culture, bool createIfNotExists, bool tryParents)
+ 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,7 +756,8 @@ namespace System.Resources {
protected static Version GetSatelliteContractVersion(Assembly a)
{
// Ensure that the assembly reference is not null
- if (a == null) {
+ if (a == null)
+ {
throw new ArgumentNullException(nameof(a), Environment.GetResourceString("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))
{
@@ -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)
@@ -1091,7 +1124,7 @@ namespace System.Resources {
throw new MissingManifestResourceException(Environment.GetResourceString("MissingManifestResource_NoPRIresources"));
}
-
+
// Throws WinRT hresults.
return GetStringFromPRI(name,
culture == null ? null : culture.Name,
@@ -1100,7 +1133,8 @@ namespace System.Resources {
else
#endif // FEATURE_APPX
{
- 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();
@@ -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,43 +1184,46 @@ 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();
@@ -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,11 +1289,13 @@ 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)
@@ -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..49795d8f6f 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,20 +115,22 @@ 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"));
@@ -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,18 +197,20 @@ 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) {
+ if (stringLength < 0)
+ {
throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_NegativeStringLength"));
}
_store.BaseStream.Seek(stringLength, SeekOrigin.Current);
@@ -208,8 +218,8 @@ namespace System.Resources {
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,15 +229,16 @@ 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) {
+ if (r < 0 || r > _dataSectionOffset - _nameSectionOffset)
+ {
throw new FormatException(Environment.GetResourceString("BadImageFormat_ResourcesNameInvalidOffset", r));
}
return r;
@@ -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) {
+ if (dataPos < 0 || dataPos >= _store.BaseStream.Length - _dataSectionOffset)
+ {
throw new FormatException(Environment.GetResourceString("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,14 +359,17 @@ namespace System.Resources {
{
Debug.Assert(_store != null, "ResourceReader is closed!");
int byteLen = _store.Read7BitEncodedInt();
- if (byteLen < 0) {
+ if (byteLen < 0)
+ {
throw new BadImageFormatException(Environment.GetResourceString("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) {
+ if (_ums.Position > _ums.Length)
+ {
throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourcesNameTooLong"));
}
@@ -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"));
numBytesToRead -= n;
}
- return FastResourceComparer.CompareOrdinal(bytes, byteLen/2, name) == 0;
+ return FastResourceComparer.CompareOrdinal(bytes, byteLen / 2, name) == 0;
}
}
@@ -378,15 +403,18 @@ 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) {
+ if (byteLen < 0)
+ {
throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_NegativeStringLength"));
}
- if (_ums != null) {
+ if (_ums != null)
+ {
if (_ums.Position > _ums.Length - byteLen)
throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourcesIndexTooLong", index));
@@ -402,13 +430,14 @@ 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) {
+ if (dataOffset < 0 || dataOffset >= _store.BaseStream.Length - _dataSectionOffset)
+ {
throw new FormatException(Environment.GetResourceString("BadImageFormat_ResourcesDataInvalidOffset", dataOffset));
}
return s;
@@ -419,14 +448,16 @@ 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));
count -= n;
}
dataOffset = _store.ReadInt32();
- if (dataOffset < 0 || dataOffset >= _store.BaseStream.Length - _dataSectionOffset) {
+ if (dataOffset < 0 || dataOffset >= _store.BaseStream.Length - _dataSectionOffset)
+ {
throw new FormatException(Environment.GetResourceString("BadImageFormat_ResourcesDataInvalidOffset", dataOffset));
}
}
@@ -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) {
+ if (dataPos < 0 || dataPos >= _store.BaseStream.Length - _dataSectionOffset)
+ {
throw new FormatException(Environment.GetResourceString("BadImageFormat_ResourcesDataInvalidOffset", dataPos));
}
- BCLDebug.Log("RESMGRFILEFORMAT", "GetValueForNameIndex: dataPos: "+dataPos);
+ BCLDebug.Log("RESMGRFILEFORMAT", "GetValueForNameIndex: dataPos: " + dataPos);
ResourceTypeCode junk;
if (_version == 1)
return LoadObjectV1(dataPos);
@@ -464,19 +497,22 @@ 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));
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();
@@ -487,7 +523,7 @@ namespace System.Resources {
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) {
+ catch (EndOfStreamException eof)
+ {
throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_TypeMismatch"), eof);
}
- catch (ArgumentOutOfRangeException e) {
+ catch (ArgumentOutOfRangeException e)
+ {
throw new BadImageFormatException(Environment.GetResourceString("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,20 +606,23 @@ 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 {
+ else
+ {
throw new NotSupportedException(Environment.GetResourceString("NotSupported_ResourceObjectSerialization"));
}
}
@@ -588,132 +632,148 @@ 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) {
+ catch (EndOfStreamException eof)
+ {
throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_TypeMismatch"), eof);
}
- catch (ArgumentOutOfRangeException e) {
+ catch (ArgumentOutOfRangeException e)
+ {
throw new BadImageFormatException(Environment.GetResourceString("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();
+
+ case ResourceTypeCode.DateTime:
+ // Use DateTime's ToBinary & FromBinary.
+ Int64 data = _store.ReadInt64();
+ return DateTime.FromBinary(data);
- if (_ums == null) {
- if (len > _store.BaseStream.Length) {
+ 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));
}
- 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(Environment.GetResourceString("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(Environment.GetResourceString("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(Environment.GetResourceString("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(Environment.GetResourceString("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(Environment.GetResourceString("BadImageFormat_TypeMismatch"));
}
- }
-
- default:
- if (typeCode < ResourceTypeCode.StartOfUserTypes) {
- throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_TypeMismatch"));
- }
- break;
+ break;
}
// Normal serialized objects
@@ -729,15 +789,18 @@ 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) {
+ catch (EndOfStreamException eof)
+ {
throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourcesHeaderCorrupted"), eof);
}
- catch (IndexOutOfRangeException e) {
+ catch (IndexOutOfRangeException e)
+ {
throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourcesHeaderCorrupted"), e);
}
}
@@ -755,14 +818,17 @@ namespace System.Resources {
// use this to skip to the end of the header
int resMgrHeaderVersion = _store.ReadInt32();
int numBytesToSkip = _store.ReadInt32();
- if (numBytesToSkip < 0 || resMgrHeaderVersion < 0) {
+ if (numBytesToSkip < 0 || resMgrHeaderVersion < 0)
+ {
throw new BadImageFormatException(Environment.GetResourceString("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
@@ -807,7 +873,8 @@ namespace System.Resources {
#endif
_numResources = _store.ReadInt32();
- if (_numResources < 0) {
+ if (_numResources < 0)
+ {
throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourcesHeaderCorrupted"));
}
BCLDebug.Log("RESMGRFILEFORMAT", "ReadResources: Expecting " + _numResources + " resources.");
@@ -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) {
+ if (numTypes < 0)
+ {
throw new BadImageFormatException(Environment.GetResourceString("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) {
+ if (seekPos < 0)
+ {
throw new BadImageFormatException(Environment.GetResourceString("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) {
+ if (namePosition < 0)
+ {
throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourcesHeaderCorrupted"));
}
_namePositions[i] = namePosition;
}
}
- else {
+ else
+ {
int seekPos = unchecked(4 * _numResources);
- if (seekPos < 0) {
+ if (seekPos < 0)
+ {
throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourcesHeaderCorrupted"));
}
- unsafe {
+ unsafe
+ {
_namePositionsPtr = (int*)_ums.PositionPointer;
// Skip over the array of namePositions.
_ums.Seek(seekPos, SeekOrigin.Current);
@@ -912,7 +994,8 @@ namespace System.Resources {
// Read location of data section.
_dataSectionOffset = _store.ReadInt32();
- if (_dataSectionOffset < 0) {
+ if (_dataSectionOffset < 0)
+ {
throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourcesHeaderCorrupted"));
}
@@ -920,7 +1003,8 @@ namespace System.Resources {
_nameSectionOffset = _store.BaseStream.Position;
// _nameSectionOffset should be <= _dataSectionOffset; if not, it's corrupt
- if (_dataSectionOffset < _nameSectionOffset) {
+ if (_dataSectionOffset < _nameSectionOffset)
+ {
throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourcesHeaderCorrupted"));
}
@@ -932,12 +1016,15 @@ namespace System.Resources {
// and initialize Reflection.
private RuntimeType FindType(int typeIndex)
{
- if (typeIndex < 0 || typeIndex >= _typeTable.Length) {
+ if (typeIndex < 0 || typeIndex >= _typeTable.Length)
+ {
throw new BadImageFormatException(Environment.GetResourceString("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);
@@ -956,7 +1043,8 @@ namespace System.Resources {
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_ResourceObjectSerialization"));
}
- finally {
+ finally
+ {
_store.BaseStream.Position = oldPos;
}
}
@@ -979,23 +1067,28 @@ namespace System.Resources {
// off the length of the type code).
int[] sortedDataPositions = new int[_numResources];
int dataPos = FindPosForResource(resourceName);
- if( dataPos == -1) {
+ if (dataPos == -1)
+ {
throw new ArgumentException(Environment.GetResourceString("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) {
+ if (numBytesToSkip < 0)
+ {
throw new FormatException(Environment.GetResourceString("BadImageFormat_ResourcesNameInvalidOffset", numBytesToSkip));
}
_store.BaseStream.Position += numBytesToSkip;
int dPos = _store.ReadInt32();
- if (dPos < 0 || dPos >= _store.BaseStream.Length - _dataSectionOffset) {
+ if (dPos < 0 || dPos >= _store.BaseStream.Length - _dataSectionOffset)
+ {
throw new FormatException(Environment.GetResourceString("BadImageFormat_ResourcesDataInvalidOffset", dPos));
}
sortedDataPositions[i] = dPos;
@@ -1005,20 +1098,21 @@ 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) {
+ ResourceTypeCode typeCode = (ResourceTypeCode)_store.Read7BitEncodedInt();
+ if (typeCode < 0 || typeCode >= ResourceTypeCode.StartOfUserTypes + _typeTable.Length)
+ {
throw new BadImageFormatException(Environment.GetResourceString("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"));
@@ -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,9 +1176,11 @@ namespace System.Resources {
_currentName++;
return true;
}
-
- public Object Key {
- get {
+
+ 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"));
@@ -1087,39 +1188,49 @@ namespace System.Resources {
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 {
+ 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"));
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,9 +1243,11 @@ namespace System.Resources {
return new DictionaryEntry(key, value);
}
}
-
- public Object Value {
- get {
+
+ 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"));
diff --git a/src/mscorlib/src/System/Resources/ResourceSet.cs b/src/mscorlib/src/System/Resources/ResourceSet.cs
index 8fd9346f91..0fac0a9abc 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.
@@ -202,10 +205,12 @@ namespace System.Resources {
public virtual String GetString(String name)
{
Object obj = GetObjectInternal(name);
- try {
+ try
+ {
return (String)obj;
}
- catch (InvalidCastException) {
+ catch (InvalidCastException)
+ {
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ResourceNotString_Name", name));
}
}
@@ -217,28 +222,33 @@ namespace System.Resources {
// Case-sensitive lookup
obj = GetObjectInternal(name);
- try {
+ try
+ {
s = (String)obj;
}
- catch (InvalidCastException) {
+ catch (InvalidCastException)
+ {
throw new InvalidOperationException(Environment.GetResourceString("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) {
+ catch (InvalidCastException)
+ {
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ResourceNotString_Name", name));
}
}
-
+
// Look up an object value for a resource given its name.
//
public virtual Object GetObject(String name)
@@ -249,17 +259,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) {
@@ -300,7 +311,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
index 64fb076eb5..f9a846124a 100644
--- a/src/mscorlib/src/System/Resources/ResourceTypeCode.cs
+++ b/src/mscorlib/src/System/Resources/ResourceTypeCode.cs
@@ -13,7 +13,8 @@
**
===========================================================*/
-namespace System.Resources {
+namespace System.Resources
+{
/* An internal implementation detail for .resources files, describing
what type an object is.
Ranges:
@@ -24,7 +25,8 @@ namespace System.Resources {
internals of .resources files.
*/
[Serializable]
- internal enum ResourceTypeCode {
+ internal enum ResourceTypeCode
+ {
// Primitives
Null = 0,
String = 1,
diff --git a/src/mscorlib/src/System/Resources/RuntimeResourceSet.cs b/src/mscorlib/src/System/Resources/RuntimeResourceSet.cs
index a94ac82781..202fe50637 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;
@@ -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,7 +289,7 @@ 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"));
@@ -291,26 +297,31 @@ namespace System.Resources {
Object value = null;
ResourceLocator resLocation;
-
- lock(Reader) {
+
+ lock (Reader)
+ {
if (Reader == null)
throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_ResourceSet"));
-
- if (_defaultReader != null) {
+
+ 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
index 86e972efdd..4f1885e8eb 100644
--- a/src/mscorlib/src/System/Resources/SatelliteContractVersionAttribute.cs
+++ b/src/mscorlib/src/System/Resources/SatelliteContractVersionAttribute.cs
@@ -14,12 +14,13 @@
**
===========================================================*/
-namespace System.Resources {
- using System;
- using System.Diagnostics.Contracts;
-
- [AttributeUsage(AttributeTargets.Assembly, AllowMultiple=false)]
- public sealed class SatelliteContractVersionAttribute : Attribute
+using System;
+using System.Diagnostics.Contracts;
+
+namespace System.Resources
+{
+ [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)]
+ public sealed class SatelliteContractVersionAttribute : Attribute
{
private String _version;
@@ -31,7 +32,8 @@ namespace System.Resources {
_version = version;
}
- public String 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
index aa4069a366..43f9b88485 100644
--- a/src/mscorlib/src/System/Resources/UltimateResourceFallbackLocation.cs
+++ b/src/mscorlib/src/System/Resources/UltimateResourceFallbackLocation.cs
@@ -17,9 +17,9 @@
using System;
-namespace System.Resources {
-
-[Serializable]
+namespace System.Resources
+{
+ [Serializable]
public enum UltimateResourceFallbackLocation
{
MainAssembly,
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..047e2e21ee 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)
{
@@ -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)];
@@ -735,7 +735,7 @@ namespace System
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,7 +1006,7 @@ namespace System
if (!filter.Match(RuntimeTypeHandle.GetUtf8Name(interfaceType)))
continue;
}
-
+
Debug.Assert(interfaceType.IsInterface);
list.Add(interfaceType);
}
@@ -1016,11 +1015,11 @@ namespace System
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);
@@ -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);
}
@@ -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);
}
@@ -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++)
@@ -1995,11 +1994,11 @@ 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]);
}
@@ -2007,17 +2006,17 @@ namespace System
throw new ArgumentException(
Environment.GetResourceString("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,7 +2041,7 @@ namespace System
typeContext, methodContext, genericArgument.GetTypeHandleInternal().GetTypeChecked()))
{
throw new ArgumentException(
- Environment.GetResourceString("Argument_GenConstraintViolation",
+ Environment.GetResourceString("Argument_GenConstraintViolation",
i.ToString(CultureInfo.CurrentCulture), genericArgument.ToString(), definition.ToString(), genericParameter.ToString()), e);
}
}
@@ -2058,7 +2057,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 +2071,6 @@ namespace System
{
name = fullname;
}
-
}
#endregion
@@ -2081,10 +2079,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 +2110,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 +2167,7 @@ namespace System
{
if (!memberInfo.Name.StartsWith(name, StringComparison.Ordinal))
return false;
- }
+ }
return true;
}
@@ -2206,7 +2204,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 +2235,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 +2308,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 +2328,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 +2343,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 +2351,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 +2373,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 +2406,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 +2418,7 @@ namespace System
}
}
#endregion
-
+
return true;
}
@@ -2525,16 +2523,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;
}
@@ -2595,7 +2593,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 +2608,7 @@ namespace System
RuntimeConstructorInfo constructorInfo = cache[i];
if (FilterApplyConstructorInfo(constructorInfo, bindingAttr, callConv, types) &&
(!prefixLookup || RuntimeType.FilterApplyPrefixLookup(constructorInfo, name, ignoreCase)))
- {
+ {
candidates.Add(constructorInfo);
}
}
@@ -2621,7 +2619,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 +2681,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 +2697,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 +2744,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)
@@ -2793,7 +2791,7 @@ namespace System
{
if (IsGenericParameter)
throw new InvalidOperationException(Environment.GetResourceString("Arg_GenericParameter"));
-
+
if ((object)ifaceType == null)
throw new ArgumentNullException(nameof(ifaceType));
Contract.EndContractBlock();
@@ -2851,15 +2849,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,8 +2865,8 @@ namespace System
{
return firstCandidate;
}
- else if (types == null)
- {
+ else if (types == null)
+ {
for (int j = 1; j < candidates.Count; j++)
{
MethodInfo methodInfo = candidates[j];
@@ -2881,30 +2879,30 @@ namespace System
// 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 +2919,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 +2928,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 +2941,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"));
}
}
-
+
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 +2967,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;
@@ -2990,7 +2988,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();
@@ -3018,7 +3016,7 @@ namespace System
if ((match.DeclaringType.IsInterface == true) && (fieldInfo.DeclaringType.IsInterface == true))
multipleStaticFieldMatches = true;
}
-
+
if (match == null || fieldInfo.DeclaringType.IsSubclassOf(match.DeclaringType) || match.DeclaringType.IsInterface)
match = fieldInfo;
}
@@ -3030,13 +3028,13 @@ namespace System
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 +3042,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;
@@ -3066,7 +3064,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 +3073,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);
@@ -3097,7 +3095,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 +3104,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 +3193,9 @@ namespace System
return RuntimeTypeHandle.GetModule(this);
}
- public override Assembly Assembly
+ public override Assembly Assembly
{
- get
+ get
{
return GetRuntimeAssembly();
}
@@ -3208,9 +3206,9 @@ namespace System
return RuntimeTypeHandle.GetAssembly(this);
}
- public override RuntimeTypeHandle TypeHandle
+ public override RuntimeTypeHandle TypeHandle
{
- get
+ get
{
return new RuntimeTypeHandle(this);
}
@@ -3226,7 +3224,7 @@ namespace System
return RuntimeTypeHandle.IsCollectible(GetTypeHandleInternal());
}
- protected override TypeCode GetTypeCodeImpl()
+ protected override TypeCode GetTypeCodeImpl()
{
TypeCode typeCode = Cache.TypeCode;
@@ -3234,7 +3232,7 @@ namespace System
return typeCode;
CorElementType corElementType = RuntimeTypeHandle.GetCorElementType(this);
- switch (corElementType)
+ switch (corElementType)
{
case CorElementType.Boolean:
typeCode = TypeCode.Boolean; break;
@@ -3270,7 +3268,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])
@@ -3312,7 +3310,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 +3332,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 +3387,9 @@ namespace System
return false;
}
- public override Type BaseType
+ public override Type BaseType
{
- get
+ get
{
return GetBaseType();
}
@@ -3441,9 +3440,9 @@ namespace System
return RuntimeTypeHandle.GetBaseType(this);
}
- public override Type UnderlyingSystemType
+ public override Type UnderlyingSystemType
{
- get
+ get
{
return this;
}
@@ -3451,34 +3450,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 +3487,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 +3559,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);
}
@@ -3587,9 +3586,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
{
@@ -3604,18 +3603,18 @@ namespace System
#region Arrays
internal override bool IsSzArray
{
- get
+ get
{
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"));
@@ -3623,7 +3622,7 @@ namespace System
return RuntimeTypeHandle.GetArrayRank(this);
}
- public override Type GetElementType()
+ public override Type GetElementType()
{
return RuntimeTypeHandle.GetElementType(this);
}
@@ -3746,7 +3745,7 @@ namespace System
return GetRootElementType().GetTypeHandleInternal().GetInstantiationInternal();
}
- public override Type[] GetGenericArguments()
+ public override Type[] GetGenericArguments()
{
Type[] types = GetRootElementType().GetTypeHandleInternal().GetInstantiationPublic();
@@ -3771,7 +3770,7 @@ namespace System
if (GetGenericArguments().Length != instantiation.Length)
throw new ArgumentException(Environment.GetResourceString("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 +3795,7 @@ namespace System
SanityCheckGenericArguments(instantiationRuntimeType, genericParameters);
Type ret = null;
- try
+ try
{
ret = new RuntimeTypeHandle(this).Instantiate(instantiationRuntimeType);
}
@@ -3821,17 +3820,17 @@ namespace System
public override int GenericParameterPosition
{
- get
+ get
{
if (!IsGenericParameter)
throw new InvalidOperationException(Environment.GetResourceString("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"));
@@ -3852,7 +3851,7 @@ namespace System
public override bool ContainsGenericParameters
{
- get { return GetRootElementType().GetTypeHandleInternal().ContainsGenericVariables(); }
+ get { return GetRootElementType().GetTypeHandleInternal().ContainsGenericVariables(); }
}
public override Type[] GetGenericParameterConstraints()
@@ -3874,44 +3873,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 +3934,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,24 +3954,24 @@ 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)
+ if (pointer != null)
valueType = 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));
@@ -3982,32 +3981,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)
+ if (pointer != null)
valueType = 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;
@@ -4042,24 +4041,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"));
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(Environment.GetResourceString("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;
}
@@ -4111,7 +4110,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 +4120,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(Environment.GetResourceString("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(Environment.GetResourceString("Arg_CreatInstAccess"), nameof(bindingFlags));
return Activator.CreateInstance(this, bindingFlags, binder, providedArgs, culture);
}
@@ -4155,12 +4154,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 +4178,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(Environment.GetResourceString("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(Environment.GetResourceString("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(Environment.GetResourceString("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(Environment.GetResourceString("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 +4216,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,22 +4225,22 @@ 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);
}
@@ -4250,29 +4249,29 @@ namespace System
throw new ArgumentException(Environment.GetResourceString("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(Environment.GetResourceString("Arg_FldGetArgErr"), nameof(bindingFlags));
return selFld.GetValue(target);
#endregion
@@ -4281,9 +4280,9 @@ namespace System
{
#region Set the field Value
if (argCnt != 1)
- throw new ArgumentException(Environment.GetResourceString("Arg_FldSetArgErr"),nameof(bindingFlags));
+ throw new ArgumentException(Environment.GetResourceString("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 +4290,7 @@ namespace System
#endregion
}
- if ((bindingFlags & BinderNonFieldGetSet) == 0)
+ if ((bindingFlags & BinderNonFieldGetSet) == 0)
throw new MissingFieldException(FullName, name);
}
#endregion
@@ -4324,7 +4323,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)
@@ -4339,7 +4338,7 @@ namespace System
Debug.Assert(isSetProperty);
Debug.Assert(!IsGetField);
-
+
if ((bindingFlags & BindingFlags.InvokeMethod) != 0)
throw new ArgumentException(Environment.GetResourceString("Arg_PropSetInvoke"), nameof(bindingFlags));
}
@@ -4351,20 +4350,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 +4379,7 @@ namespace System
results.Add(semiFinalist);
}
}
-
+
if (results != null)
{
Debug.Assert(results.Count > 1);
@@ -4390,17 +4389,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 +4417,7 @@ namespace System
if (!FilterApplyMethodInfo((RuntimeMethodInfo)semiFinalist, bindingFlags, CallingConventions.Any, new Type[argCnt]))
continue;
-
+
if (finalist == null)
{
finalist = semiFinalist;
@@ -4445,12 +4444,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 +4457,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 = EmptyArray<Object>.Value;
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 +4486,9 @@ namespace System
return result;
#endregion
}
-
+
throw new MissingMethodException(FullName, name);
- }
+ }
#endregion
#endregion
@@ -4502,28 +4501,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 +4544,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(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType));
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType, inherit);
}
@@ -4559,8 +4558,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(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType));
return CustomAttribute.IsDefined(this, attributeRuntimeType, inherit);
}
@@ -4572,9 +4571,9 @@ namespace System
#endregion
#region MemberInfo Overrides
- public override String Name
+ public override String Name
{
- get
+ get
{
return GetCachedName(TypeNameKind.Name);
}
@@ -4623,9 +4622,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 +4633,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 +4651,7 @@ namespace System
public override int MetadataToken
{
- get
+ get
{
return RuntimeTypeHandle.GetToken(this);
}
@@ -4678,12 +4677,12 @@ namespace System
if (Object.ReferenceEquals(elementType, typeof(void)))
throw new NotSupportedException(Environment.GetResourceString("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)
@@ -4698,9 +4697,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 +4716,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]);
@@ -4751,10 +4750,9 @@ namespace System
{
if (args.Length != 0)
{
-
- Debug.Assert((invokeMethod.CallingConvention & CallingConventions.VarArgs) ==
- CallingConventions.VarArgs);
- throw new NotSupportedException(String.Format(CultureInfo.CurrentCulture,
+ Debug.Assert((invokeMethod.CallingConvention & CallingConventions.VarArgs) ==
+ CallingConventions.VarArgs);
+ throw new NotSupportedException(String.Format(CultureInfo.CurrentCulture,
Environment.GetResourceString("NotSupported_CallToVarArg")));
}
@@ -4773,7 +4771,7 @@ namespace System
}
// the cache entry
- class ActivatorCacheEntry
+ private class ActivatorCacheEntry
{
// the type to cache
internal readonly RuntimeType m_type;
@@ -4797,16 +4795,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 +4814,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 +4828,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 +4837,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 +4845,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);
}
@@ -4875,7 +4874,7 @@ namespace System
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;
@@ -4921,16 +4920,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"));
}
}
-
+
// 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 +5011,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"));
}
}
-
}
#region Library
@@ -5162,7 +5160,6 @@ namespace System.Reflection
internal void Insert(K key, V value)
{
-
int hashcode = GetHashCodeHelper(key);
if (hashcode < 0)
hashcode = ~hashcode;
@@ -5208,15 +5205,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
index 34e66beade..fa6003df1f 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/AccessedThroughPropertyAttribute.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/AccessedThroughPropertyAttribute.cs
@@ -4,10 +4,11 @@
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
-namespace System.Runtime.CompilerServices
-{
- using System;
+using System;
+
+namespace System.Runtime.CompilerServices
+{
[AttributeUsage(AttributeTargets.Field)]
public sealed class AccessedThroughPropertyAttribute : Attribute
{
@@ -18,9 +19,9 @@ namespace System.Runtime.CompilerServices
this.propertyName = propertyName;
}
- public string PropertyName
+ public string PropertyName
{
- get
+ get
{
return propertyName;
}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/AssemblySettingAttributes.cs b/src/mscorlib/src/System/Runtime/CompilerServices/AssemblySettingAttributes.cs
index 5251122629..37592a475d 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/AssemblySettingAttributes.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/AssemblySettingAttributes.cs
@@ -5,12 +5,12 @@
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
-namespace System.Runtime.CompilerServices
-{
- using System;
- using System.Runtime.InteropServices;
+using System;
+using System.Runtime.InteropServices;
+namespace System.Runtime.CompilerServices
+{
/*
NGenHint is not supported in Whidbey
@@ -28,59 +28,59 @@ namespace System.Runtime.CompilerServices
[Serializable]
public enum LoadHint
{
- Default = 0x0000, // No preference specified
-
- Always = 0x0001, // Dependency is always loaded
- Sometimes = 0x0002, // Dependency is sometimes loaded
+ 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
+ [AttributeUsage(AttributeTargets.Assembly)]
+ public sealed class DefaultDependencyAttribute : Attribute
{
private LoadHint loadHint;
-
- public DefaultDependencyAttribute (
+
+ public DefaultDependencyAttribute(
LoadHint loadHintArgument
)
{
loadHint = loadHintArgument;
- }
-
+ }
+
public LoadHint LoadHint
{
get
{
return loadHint;
}
- }
- }
+ }
+ }
-[Serializable]
-[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
- public sealed class DependencyAttribute : Attribute
+ [Serializable]
+ [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
+ public sealed class DependencyAttribute : Attribute
{
- private String dependentAssembly;
- private LoadHint loadHint;
+ private String dependentAssembly;
+ private LoadHint loadHint;
- public DependencyAttribute (
- String dependentAssemblyArgument,
+ public DependencyAttribute(
+ String dependentAssemblyArgument,
LoadHint loadHintArgument
)
{
- dependentAssembly = dependentAssemblyArgument;
- loadHint = loadHintArgument;
+ dependentAssembly = dependentAssemblyArgument;
+ loadHint = loadHintArgument;
}
-
+
public String DependentAssembly
{
get
{
return dependentAssembly;
}
- }
+ }
public LoadHint LoadHint
{
@@ -88,7 +88,7 @@ namespace System.Runtime.CompilerServices
{
return loadHint;
}
- }
+ }
}
}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs b/src/mscorlib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs
index 7915e19352..fc7a7f01a3 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs
@@ -1123,7 +1123,7 @@ namespace System.Runtime.CompilerServices
///</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/CompilationRelaxations.cs b/src/mscorlib/src/System/Runtime/CompilerServices/CompilationRelaxations.cs
index c3679b610c..05c43ac631 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/CompilationRelaxations.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/CompilationRelaxations.cs
@@ -5,46 +5,45 @@
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
-namespace System.Runtime.CompilerServices
-{
- using System;
+using System;
+namespace System.Runtime.CompilerServices
+{
/// IMPORTANT: Keep this in sync with corhdr.h
-[Serializable]
-[Flags]
+ [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.
+ {
+ 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
+
+ [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(
+ int relaxations)
+ {
+ m_relaxations = relaxations;
}
-
- public CompilationRelaxationsAttribute (
- CompilationRelaxations relaxations)
- {
- m_relaxations = (int) relaxations;
+
+ public CompilationRelaxationsAttribute(
+ CompilationRelaxations relaxations)
+ {
+ m_relaxations = (int)relaxations;
}
-
+
public int CompilationRelaxations
- {
- get
- {
- return m_relaxations;
- }
+ {
+ get
+ {
+ return m_relaxations;
+ }
}
}
-
}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/CompilerGeneratedAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/CompilerGeneratedAttribute.cs
index 1778506c7c..31e9ade0bf 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/CompilerGeneratedAttribute.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/CompilerGeneratedAttribute.cs
@@ -4,13 +4,14 @@
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
-namespace System.Runtime.CompilerServices {
-[Serializable]
-[AttributeUsage(AttributeTargets.All, Inherited = true)]
+namespace System.Runtime.CompilerServices
+{
+ [Serializable]
+ [AttributeUsage(AttributeTargets.All, Inherited = true)]
public sealed class CompilerGeneratedAttribute : Attribute
{
- public CompilerGeneratedAttribute () {}
+ public CompilerGeneratedAttribute() { }
}
}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/CompilerGlobalScopeAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/CompilerGlobalScopeAttribute.cs
index 1cd830cfca..7a390d1f53 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/CompilerGlobalScopeAttribute.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/CompilerGlobalScopeAttribute.cs
@@ -12,7 +12,7 @@
**
**
===========================================================*/
-
+
namespace System.Runtime.CompilerServices
{
@@ -20,7 +20,7 @@ namespace System.Runtime.CompilerServices
[AttributeUsage(AttributeTargets.Class)]
public class CompilerGlobalScopeAttribute : Attribute
{
- public CompilerGlobalScopeAttribute () {}
+ public CompilerGlobalScopeAttribute() { }
}
}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/ConditionalWeakTable.cs b/src/mscorlib/src/System/Runtime/CompilerServices/ConditionalWeakTable.cs
index 4b2648ba6f..eed21cf6fb 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/ConditionalWeakTable.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/ConditionalWeakTable.cs
@@ -164,7 +164,6 @@ namespace System.Runtime.CompilerServices
{
CreateEntry(key, value);
}
-
}
}
@@ -797,7 +796,7 @@ namespace System.Runtime.CompilerServices
}
return Resize(newSize);
- }
+ }
internal Container Resize(int newSize)
{
@@ -1114,7 +1113,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
index 46dae10fdd..9427e3d208 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/DisablePrivateReflectionAttribute.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/DisablePrivateReflectionAttribute.cs
@@ -5,14 +5,14 @@
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
+using System;
+
namespace System.Runtime.CompilerServices
{
- using System;
-
- [AttributeUsage(AttributeTargets.Assembly, AllowMultiple=false, Inherited=false)]
+ [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)]
public sealed class DisablePrivateReflectionAttribute : Attribute
{
- public DisablePrivateReflectionAttribute() {}
+ public DisablePrivateReflectionAttribute() { }
}
}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/DiscardableAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/DiscardableAttribute.cs
index 3fda4624d4..b6d05a21d3 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/DiscardableAttribute.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/DiscardableAttribute.cs
@@ -4,10 +4,11 @@
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
-namespace System.Runtime.CompilerServices {
- using System;
+using System;
+namespace System.Runtime.CompilerServices
+{
// Custom attribute to indicating a TypeDef is a discardable attribute
public class DiscardableAttribute : Attribute
{
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/ExtensionAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/ExtensionAttribute.cs
index 6ec8fa04f5..92170880f1 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/ExtensionAttribute.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/ExtensionAttribute.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;
namespace System.Runtime.CompilerServices
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/FixedAddressValueTypeAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/FixedAddressValueTypeAttribute.cs
index 679e304ad1..1d8b75b5c4 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/FixedAddressValueTypeAttribute.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/FixedAddressValueTypeAttribute.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.
-namespace System.Runtime.CompilerServices
-{
- using System;
-
-[Serializable]
-[AttributeUsage(AttributeTargets.Field)]
- sealed public class FixedAddressValueTypeAttribute : Attribute
- {
+using System;
+
+namespace System.Runtime.CompilerServices
+{
+ [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
index a7d01b12c4..e4008b86f0 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/FixedBufferAttribute.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/FixedBufferAttribute.cs
@@ -12,11 +12,12 @@
** Used by C# with this syntax: "fixed int buffer[10];"
**
===========================================================*/
+
using System;
namespace System.Runtime.CompilerServices
{
- [AttributeUsage(AttributeTargets.Field, Inherited=false)]
+ [AttributeUsage(AttributeTargets.Field, Inherited = false)]
public sealed class FixedBufferAttribute : Attribute
{
private Type elementType;
@@ -28,14 +29,18 @@ namespace System.Runtime.CompilerServices
this.length = length;
}
- public Type ElementType {
- get {
+ public Type ElementType
+ {
+ get
+ {
return elementType;
}
}
- public int Length {
- get {
+ 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
index 4b99a8a5d9..23d03860ed 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/FormattableStringFactory.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/FormattableStringFactory.cs
@@ -4,13 +4,13 @@
/*============================================================
**
-** Class: FormattableStringFactory
**
**
** Purpose: implementation of the FormattableStringFactory
** class.
**
===========================================================*/
+
namespace System.Runtime.CompilerServices
{
/// <summary>
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/IndexerNameAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/IndexerNameAttribute.cs
index c32be6f3a2..cc8cb59ffe 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/IndexerNameAttribute.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/IndexerNameAttribute.cs
@@ -2,15 +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;
+
namespace System.Runtime.CompilerServices
{
- using System;
-
-[Serializable]
-[AttributeUsage(AttributeTargets.Property, Inherited = true)]
- public sealed class IndexerNameAttribute: Attribute
+ [Serializable]
+ [AttributeUsage(AttributeTargets.Property, Inherited = true)]
+ public sealed class IndexerNameAttribute : Attribute
{
public IndexerNameAttribute(String indexerName)
- {}
+ { }
}
}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/InternalsVisibleToAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/InternalsVisibleToAttribute.cs
index ee7807a5dd..b103c84be7 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/InternalsVisibleToAttribute.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/InternalsVisibleToAttribute.cs
@@ -5,12 +5,11 @@
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
+using System;
+
namespace System.Runtime.CompilerServices
{
- using System;
-
-
- [AttributeUsage(AttributeTargets.Assembly, AllowMultiple=true, Inherited=false)]
+ [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true, Inherited = false)]
public sealed class InternalsVisibleToAttribute : Attribute
{
private string _assemblyName;
@@ -18,12 +17,12 @@ namespace System.Runtime.CompilerServices
public InternalsVisibleToAttribute(string assemblyName)
{
- this._assemblyName = assemblyName;
+ _assemblyName = assemblyName;
}
- public string AssemblyName
+ public string AssemblyName
{
- get
+ get
{
return _assemblyName;
}
@@ -52,7 +51,8 @@ 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/IsVolatile.cs b/src/mscorlib/src/System/Runtime/CompilerServices/IsVolatile.cs
index 5287e82b7b..fd1c6a1b12 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/IsVolatile.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/IsVolatile.cs
@@ -2,9 +2,9 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace System.Runtime.CompilerServices
+namespace System.Runtime.CompilerServices
{
- public static class IsVolatile
+ public static class IsVolatile
{
// no instantiation, please!
}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/MethodImplAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/MethodImplAttribute.cs
index b4991110f8..89bb5e6ee5 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/MethodImplAttribute.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/MethodImplAttribute.cs
@@ -2,72 +2,72 @@
// 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,
+ 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)! ****
}
[Serializable]
public enum MethodCodeType
{
- IL = System.Reflection.MethodImplAttributes.IL,
- Native = System.Reflection.MethodImplAttributes.Native,
+ IL = System.Reflection.MethodImplAttributes.IL,
+ Native = System.Reflection.MethodImplAttributes.Native,
/// <internalonly/>
- OPTIL = System.Reflection.MethodImplAttributes.OPTIL,
- Runtime = System.Reflection.MethodImplAttributes.Runtime
+ 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;
+ [Serializable]
+ [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)]
+ sealed public class MethodImplAttribute : Attribute
+ {
+ internal MethodImplOptions _val;
+ public MethodCodeType MethodCodeType;
internal MethodImplAttribute(MethodImplAttributes methodImplAttributes)
{
- MethodImplOptions all =
- MethodImplOptions.Unmanaged | MethodImplOptions.ForwardRef | MethodImplOptions.PreserveSig |
+ MethodImplOptions 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
index d5e64a1177..a007e382a8 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/ReferenceAssemblyAttribute.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/ReferenceAssemblyAttribute.cs
@@ -12,12 +12,13 @@
** should be loadable for introspection, but not execution.
**
============================================================*/
-namespace System.Runtime.CompilerServices
-{
- using System;
-
+
+using System;
+
+namespace System.Runtime.CompilerServices
+{
[Serializable]
- [AttributeUsage(AttributeTargets.Assembly, AllowMultiple=false)]
+ [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)]
public sealed class ReferenceAssemblyAttribute : Attribute
{
private String _description; // Maybe ".NET FX v4.0 SP1, partial trust"?
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeCompatibilityAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeCompatibilityAttribute.cs
index 40a9b7c568..42b2e519b1 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeCompatibilityAttribute.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeCompatibilityAttribute.cs
@@ -13,20 +13,21 @@
**
=============================================================================*/
-namespace System.Runtime.CompilerServices
-{
- using System;
+using System;
-[Serializable]
-[AttributeUsage(AttributeTargets.Assembly, Inherited=false, AllowMultiple=false)]
- public sealed class RuntimeCompatibilityAttribute : Attribute
+namespace System.Runtime.CompilerServices
+{
+ [Serializable]
+ [AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple = false)]
+ public sealed class RuntimeCompatibilityAttribute : Attribute
{
// fields
private bool m_wrapNonExceptionThrows;
// constructors
- public RuntimeCompatibilityAttribute() {
+ public RuntimeCompatibilityAttribute()
+ {
// legacy behavior is the default, and m_wrapNonExceptionThrows is implicitly
// false thanks to the CLR's guarantee of zeroed memory.
}
@@ -36,11 +37,14 @@ namespace System.Runtime.CompilerServices
// 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;
+ public bool WrapNonExceptionThrows
+ {
+ get
+ {
+ return m_wrapNonExceptionThrows;
}
- set {
+ 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 980c2fd469..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
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeWrappedException.cs b/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeWrappedException.cs
index e3b2d2ce62..abb5a8f656 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")) {
+ : base(Environment.GetResourceString("RuntimeWrappedException"))
+ {
SetErrorCode(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
index 38e5538b44..a6f3c01618 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/SpecialNameAttribute.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/SpecialNameAttribute.cs
@@ -7,16 +7,16 @@ using System;
using System.Reflection;
using System.Runtime.InteropServices;
-namespace System.Runtime.CompilerServices
+namespace System.Runtime.CompilerServices
{
- [AttributeUsage(AttributeTargets.Class |
+ [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/SuppressIldasmAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/SuppressIldasmAttribute.cs
index eb019eecbf..f5777e6819 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/SuppressIldasmAttribute.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/SuppressIldasmAttribute.cs
@@ -4,10 +4,11 @@
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
-namespace System.Runtime.CompilerServices
-{
- using System;
+using System;
+
+namespace System.Runtime.CompilerServices
+{
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module)]
public sealed class SuppressIldasmAttribute : Attribute
{
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/SuppressMergeCheckAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/SuppressMergeCheckAttribute.cs
index 6bb36c4bf5..828ca2e0eb 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/SuppressMergeCheckAttribute.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/SuppressMergeCheckAttribute.cs
@@ -5,10 +5,10 @@
using System.Runtime.InteropServices;
-namespace System.Runtime.CompilerServices
+namespace System.Runtime.CompilerServices
{
- [AttributeUsage(AttributeTargets.Class |
- AttributeTargets.Constructor |
+ [AttributeUsage(AttributeTargets.Class |
+ AttributeTargets.Constructor |
AttributeTargets.Method |
AttributeTargets.Field |
AttributeTargets.Event |
@@ -16,8 +16,8 @@ namespace System.Runtime.CompilerServices
internal sealed class SuppressMergeCheckAttribute : Attribute
{
- public SuppressMergeCheckAttribute()
- {}
+ 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/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
index 671d1f0071..47ce32fdeb 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/TypeForwardedFromAttribute.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/TypeForwardedFromAttribute.cs
@@ -8,7 +8,7 @@ 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 string assemblyFullName;
private TypeForwardedFromAttribute()
{
@@ -22,13 +22,14 @@ namespace System.Runtime.CompilerServices
{
throw new ArgumentNullException(nameof(assemblyFullName));
}
- this.assemblyFullName = assemblyFullName;
+ this.assemblyFullName = assemblyFullName;
}
public string AssemblyFullName
{
- get {
- return assemblyFullName;
+ get
+ {
+ return assemblyFullName;
}
}
}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/TypeForwardedToAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/TypeForwardedToAttribute.cs
index 147c103047..dca96c53b2 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/TypeForwardedToAttribute.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/TypeForwardedToAttribute.cs
@@ -8,8 +8,7 @@ using System.Reflection;
namespace System.Runtime.CompilerServices
{
- using System;
- [AttributeUsage(AttributeTargets.Assembly, AllowMultiple=true, Inherited=false)]
+ [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true, Inherited = false)]
public sealed class TypeForwardedToAttribute : Attribute
{
private Type _destination;
@@ -21,14 +20,14 @@ namespace System.Runtime.CompilerServices
public Type Destination
{
- get {
+ get
+ {
return _destination;
}
}
-
}
}
-
+
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/UnsafeValueTypeAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/UnsafeValueTypeAttribute.cs
index bc210ccb71..df71e7e10c 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/UnsafeValueTypeAttribute.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/UnsafeValueTypeAttribute.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.
-namespace System.Runtime.CompilerServices
-{
- using System;
-
-[Serializable]
-[AttributeUsage(AttributeTargets.Struct)]
- sealed public class UnsafeValueTypeAttribute : Attribute
- {
+using System;
+
+namespace System.Runtime.CompilerServices
+{
+ [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 8f847827aa..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)
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..70b9418263 100644
--- a/src/mscorlib/src/System/Runtime/ExceptionServices/ExceptionNotification.cs
+++ b/src/mscorlib/src/System/Runtime/ExceptionServices/ExceptionNotification.cs
@@ -3,20 +3,19 @@
// 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..4666611278 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
@@ -102,20 +103,19 @@ namespace System.Runtime.ExceptionServices {
{
throw new ArgumentNullException(nameof(source), Environment.GetResourceString("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,7 @@ namespace System.Runtime.ExceptionServices {
{
// Restore the exception dispatch details before throwing the exception.
m_Exception.RestoreExceptionDispatchInfo(this);
- throw m_Exception;
+ throw m_Exception;
}
}
}
diff --git a/src/mscorlib/src/System/Runtime/GcSettings.cs b/src/mscorlib/src/System/Runtime/GcSettings.cs
index 11143c5ee2..834307190b 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,30 +23,30 @@ 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))
{
@@ -60,15 +61,15 @@ 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"));
@@ -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..089e692cc3 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/Attributes.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/Attributes.cs
@@ -4,17 +4,18 @@
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
-namespace System.Runtime.InteropServices{
- using System;
- using System.Reflection;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
+using System;
+using System.Reflection;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+namespace System.Runtime.InteropServices
+{
[AttributeUsage(AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
public sealed class UnmanagedFunctionPointerAttribute : Attribute
{
- CallingConvention m_callingConvention;
+ private CallingConvention m_callingConvention;
public UnmanagedFunctionPointerAttribute(CallingConvention callingConvention) { m_callingConvention = callingConvention; }
@@ -118,7 +119,6 @@ namespace System.Runtime.InteropServices{
public ClassInterfaceAttribute(ClassInterfaceType classInterfaceType)
{
_val = classInterfaceType;
-
}
public ClassInterfaceAttribute(short classInterfaceType)
{
@@ -146,7 +146,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 +157,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,8 +184,8 @@ namespace System.Runtime.InteropServices{
{
_val = sourceInterface1.FullName + "\0" + sourceInterface2.FullName + "\0" + sourceInterface3.FullName + "\0" + sourceInterface4.FullName;
}
- public String Value { get {return _val;} }
- }
+ public String Value { get { return _val; } }
+ }
[Serializable]
public enum VarEnum
@@ -199,7 +199,7 @@ namespace System.Runtime.InteropServices{
VT_CY = 6,
VT_DATE = 7,
VT_BSTR = 8,
- VT_DISPATCH = 9,
+ VT_DISPATCH = 9,
VT_ERROR = 10,
VT_BOOL = 11,
VT_VARIANT = 12,
@@ -264,7 +264,7 @@ namespace System.Runtime.InteropServices{
Currency = 0xf, // A currency
- BStr = 0x13, // OLE Unicode BSTR
+ BStr = 0x13, // OLE Unicode BSTR
LPStr = 0x14, // Ptr to SBCS string
@@ -276,13 +276,13 @@ namespace System.Runtime.InteropServices{
IUnknown = 0x19, // COM IUnknown pointer.
- IDispatch = 0x1a, // COM IDispatch pointer
+ IDispatch = 0x1a, // COM IDispatch pointer
Struct = 0x1b, // Structure
- Interface = 0x1c, // COM interface
+ Interface = 0x1c, // COM interface
- SafeArray = 0x1d, // OLE SafeArray
+ SafeArray = 0x1d, // OLE SafeArray
ByValArray = 0x1e, // Array of fixed size (only valid in structs)
@@ -290,13 +290,13 @@ namespace System.Runtime.InteropServices{
SysUInt = 0x20,
- VBByRefStr = 0x22,
+ VBByRefStr = 0x22,
- AnsiBStr = 0x23, // OLE BSTR containing SBCS characters
+ AnsiBStr = 0x23, // OLE BSTR containing SBCS characters
- TBStr = 0x24, // Ptr to OS preferred (SBCS/Unicode) BSTR
+ TBStr = 0x24, // Ptr to OS preferred (SBCS/Unicode) BSTR
- VariantBool = 0x25, // OLE defined BOOLEAN (2 bytes, true == -1, false == 0)
+ VariantBool = 0x25, // OLE defined BOOLEAN (2 bytes, true == -1, false == 0)
FunctionPtr = 0x26, // Function pointer
@@ -306,15 +306,15 @@ namespace System.Runtime.InteropServices{
LPStruct = 0x2b, // Pointer to a structure
- CustomMarshaler = 0x2c,
+ CustomMarshaler = 0x2c,
Error = 0x2d,
- IInspectable = 0x2e,
-
- HString = 0x2f, // Windows Runtime HSTRING
+ IInspectable = 0x2e,
+
+ HString = 0x2f, // Windows Runtime HSTRING
- LPUTF8Str = 0x30, // UTF8 string
+ LPUTF8Str = 0x30, // UTF8 string
}
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.ReturnValue, Inherited = false)]
@@ -403,11 +403,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 +639,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..82a0f098a1 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()
+ public class COMException : ExternalException
+ {
+ public COMException()
: base(Environment.GetResourceString("Arg_COMException"))
{
SetErrorCode(__HResults.E_FAIL);
}
-
- public COMException(String message)
+
+ public COMException(String message)
: base(message)
{
SetErrorCode(__HResults.E_FAIL);
}
-
- public COMException(String message, Exception inner)
- : base(message, inner) {
+
+ public COMException(String message, Exception inner)
+ : base(message, inner)
+ {
SetErrorCode(__HResults.E_FAIL);
}
-
- public COMException(String message,int errorCode)
- : base(message) {
+
+ public COMException(String message, int errorCode)
+ : base(message)
+ {
SetErrorCode(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
index 2ef1cf496e..a4c12c1424 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/CallingConvention.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/CallingConvention.cs
@@ -4,18 +4,19 @@
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
-namespace System.Runtime.InteropServices {
- using System;
+using System;
+
+namespace System.Runtime.InteropServices
+{
// Used for the CallingConvention named argument to the DllImport attribute
[Serializable]
public enum CallingConvention
{
- Winapi = 1,
- Cdecl = 2,
- StdCall = 3,
- ThisCall = 4,
- FastCall = 5,
+ 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
index e60d676557..426296c5c0 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/CharSet.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/CharSet.cs
@@ -4,15 +4,18 @@
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
-namespace System.Runtime.InteropServices {
- using System;
+
+using System;
+
+namespace System.Runtime.InteropServices
+{
// 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]
+ [Serializable]
public enum CharSet
{
None = 1, // User didn't specify how to marshal strings.
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..51c379f369 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));
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..ff96aeff61 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
{
@@ -28,16 +29,16 @@ namespace System.Runtime.InteropServices {
if (!(errorCode is int))
throw new ArgumentException(Environment.GetResourceString("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
index 7e1f395e4e..8aea9b2a1b 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ExternalException.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ExternalException.cs
@@ -12,58 +12,71 @@
**
=============================================================================*/
-namespace System.Runtime.InteropServices {
- using System;
- using System.Globalization;
- using System.Runtime.Serialization;
+using System;
+using System.Globalization;
+using System.Runtime.Serialization;
+
+namespace System.Runtime.InteropServices
+{
// Base exception for COM Interop errors &; Structured Exception Handler
// exceptions.
//
[Serializable]
- public class ExternalException : SystemException {
- public ExternalException()
- : base(Environment.GetResourceString("Arg_ExternalException")) {
+ public class ExternalException : SystemException
+ {
+ public ExternalException()
+ : base(Environment.GetResourceString("Arg_ExternalException"))
+ {
SetErrorCode(__HResults.E_FAIL);
}
-
- public ExternalException(String message)
- : base(message) {
+
+ public ExternalException(String message)
+ : base(message)
+ {
SetErrorCode(__HResults.E_FAIL);
}
-
- public ExternalException(String message, Exception inner)
- : base(message, inner) {
+
+ public ExternalException(String message, Exception inner)
+ : base(message, inner)
+ {
SetErrorCode(__HResults.E_FAIL);
}
- public ExternalException(String message,int errorCode)
- : base(message) {
+ public ExternalException(String message, int errorCode)
+ : base(message)
+ {
SetErrorCode(errorCode);
}
- protected ExternalException(SerializationInfo info, StreamingContext context) : base(info, context) {
+ protected ExternalException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
}
- public virtual int ErrorCode {
- get {
+ public virtual int ErrorCode
+ {
+ get
+ {
return HResult;
}
}
- 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 (!(String.IsNullOrEmpty(message))) {
+ if (!(String.IsNullOrEmpty(message)))
+ {
s = s + ": " + message;
}
Exception _innerException = InnerException;
- if (_innerException!=null) {
+ if (_innerException != null)
+ {
s = s + " ---> " + _innerException.ToString();
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/GcHandle.cs b/src/mscorlib/src/System/Runtime/InteropServices/GcHandle.cs
index 598fee0618..4cf21401fd 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();
@@ -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..b7fb686a39 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")) {
+ public class InvalidComObjectException : SystemException
+ {
+ public InvalidComObjectException()
+ : base(Environment.GetResourceString("Arg_InvalidComObjectException"))
+ {
SetErrorCode(__HResults.COR_E_INVALIDCOMOBJECT);
}
-
- public InvalidComObjectException(String message)
- : base(message) {
+
+ public InvalidComObjectException(String message)
+ : base(message)
+ {
SetErrorCode(__HResults.COR_E_INVALIDCOMOBJECT);
}
-
- public InvalidComObjectException(String message, Exception inner)
- : base(message, inner) {
+
+ public InvalidComObjectException(String message, Exception inner)
+ : base(message, inner)
+ {
SetErrorCode(__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..8ce8bb2a06 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")) {
+ public class InvalidOleVariantTypeException : SystemException
+ {
+ public InvalidOleVariantTypeException()
+ : base(Environment.GetResourceString("Arg_InvalidOleVariantTypeException"))
+ {
SetErrorCode(__HResults.COR_E_INVALIDOLEVARIANTTYPE);
}
-
- public InvalidOleVariantTypeException(String message)
- : base(message) {
+
+ public InvalidOleVariantTypeException(String message)
+ : base(message)
+ {
SetErrorCode(__HResults.COR_E_INVALIDOLEVARIANTTYPE);
}
-
- public InvalidOleVariantTypeException(String message, Exception inner)
- : base(message, inner) {
+
+ public InvalidOleVariantTypeException(String message, Exception inner)
+ : base(message, inner)
+ {
SetErrorCode(__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
index f7def3a8e9..7a170d4213 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/LayoutKind.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/LayoutKind.cs
@@ -4,14 +4,17 @@
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
-namespace System.Runtime.InteropServices {
- using System;
+
+using System;
+
+namespace System.Runtime.InteropServices
+{
// Used in the StructLayoutAttribute class
[Serializable]
public enum LayoutKind
{
- Sequential = 0, // 0x00000008,
- Explicit = 2, // 0x00000010,
- Auto = 3, // 0x00000000,
+ 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 3ed5265931..142389e29d 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)
{
@@ -285,7 +293,7 @@ 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));
@@ -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);
}
@@ -407,7 +415,7 @@ namespace System.Runtime.InteropServices
{
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();
}
-
+
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();
}
-
+
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,40 +500,40 @@ 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();
}
@@ -534,17 +542,17 @@ namespace System.Runtime.InteropServices
{
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,7 +594,7 @@ 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();
}
@@ -595,21 +603,21 @@ namespace System.Runtime.InteropServices
{
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,7 +629,7 @@ 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();
}
@@ -629,37 +637,37 @@ namespace System.Runtime.InteropServices
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();
}
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,7 +749,7 @@ 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();
}
@@ -750,21 +758,21 @@ namespace System.Runtime.InteropServices
{
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,7 +792,7 @@ namespace System.Runtime.InteropServices
//====================================================================
public static void Prelink(MethodInfo m)
{
- if (m == null)
+ if (m == null)
throw new ArgumentNullException(nameof(m));
Contract.EndContractBlock();
@@ -795,7 +803,7 @@ namespace System.Runtime.InteropServices
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,7 +852,7 @@ namespace System.Runtime.InteropServices
{
PtrToStructure(ptr, (object)structure);
}
-
+
//====================================================================
// Creates a new instance of "structuretype" and marshals data from a
// native memory block to it.
@@ -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), Environment.GetResourceString("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
{
@@ -1413,14 +1426,14 @@ namespace System.Runtime.InteropServices
{
throw new ArgumentException(Environment.GetResourceString("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
@@ -1442,11 +1455,11 @@ namespace System.Runtime.InteropServices
{
throw new ArgumentException(Environment.GetResourceString("Argument_ObjNotComObject"), nameof(o));
}
-
+
co.FinalReleaseSelf();
return 0;
- }
+ }
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void InternalFinalReleaseComObject(Object o);
@@ -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];
@@ -1614,22 +1627,22 @@ namespace System.Runtime.InteropServices
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,17 +1718,17 @@ 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(Environment.GetResourceString("Argument_MustBeRuntimeType"), nameof(t));
if (t.IsGenericType)
throw new ArgumentException(Environment.GetResourceString("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));
@@ -1748,12 +1761,14 @@ 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
@@ -1761,8 +1776,10 @@ namespace System.Runtime.InteropServices
#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..8240e299cb 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")) {
+ public class MarshalDirectiveException : SystemException
+ {
+ public MarshalDirectiveException()
+ : base(Environment.GetResourceString("Arg_MarshalDirectiveException"))
+ {
SetErrorCode(__HResults.COR_E_MARSHALDIRECTIVE);
}
-
- public MarshalDirectiveException(String message)
- : base(message) {
+
+ public MarshalDirectiveException(String message)
+ : base(message)
+ {
SetErrorCode(__HResults.COR_E_MARSHALDIRECTIVE);
}
-
- public MarshalDirectiveException(String message, Exception inner)
- : base(message, inner) {
+
+ public MarshalDirectiveException(String message, Exception inner)
+ : base(message, inner)
+ {
SetErrorCode(__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/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 4ad0957900..e11e3a437d 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/RuntimeEnvironment.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/RuntimeEnvironment.cs
@@ -24,8 +24,8 @@ 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();
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/SEHException.cs b/src/mscorlib/src/System/Runtime/InteropServices/SEHException.cs
index 72b98738ae..915a1942b0 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() {
+ public class SEHException : ExternalException
+ {
+ public SEHException()
+ : base()
+ {
SetErrorCode(__HResults.E_FAIL);
}
-
- public SEHException(String message)
- : base(message) {
+
+ public SEHException(String message)
+ : base(message)
+ {
SetErrorCode(__HResults.E_FAIL);
}
-
- public SEHException(String message, Exception inner)
- : base(message, inner) {
+
+ public SEHException(String message, Exception inner)
+ : base(message, inner)
+ {
SetErrorCode(__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..ad64e5e927 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")) {
+ public class SafeArrayRankMismatchException : SystemException
+ {
+ public SafeArrayRankMismatchException()
+ : base(Environment.GetResourceString("Arg_SafeArrayRankMismatchException"))
+ {
SetErrorCode(__HResults.COR_E_SAFEARRAYRANKMISMATCH);
}
-
- public SafeArrayRankMismatchException(String message)
- : base(message) {
+
+ public SafeArrayRankMismatchException(String message)
+ : base(message)
+ {
SetErrorCode(__HResults.COR_E_SAFEARRAYRANKMISMATCH);
}
-
- public SafeArrayRankMismatchException(String message, Exception inner)
- : base(message, inner) {
+
+ public SafeArrayRankMismatchException(String message, Exception inner)
+ : base(message, inner)
+ {
SetErrorCode(__HResults.COR_E_SAFEARRAYRANKMISMATCH);
}
- protected SafeArrayRankMismatchException(SerializationInfo info, StreamingContext context) : base(info, context) {
+ 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..d541cf41b5 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")) {
+ public class SafeArrayTypeMismatchException : SystemException
+ {
+ public SafeArrayTypeMismatchException()
+ : base(Environment.GetResourceString("Arg_SafeArrayTypeMismatchException"))
+ {
SetErrorCode(__HResults.COR_E_SAFEARRAYTYPEMISMATCH);
}
-
- public SafeArrayTypeMismatchException(String message)
- : base(message) {
+
+ public SafeArrayTypeMismatchException(String message)
+ : base(message)
+ {
SetErrorCode(__HResults.COR_E_SAFEARRAYTYPEMISMATCH);
}
-
- public SafeArrayTypeMismatchException(String message, Exception inner)
- : base(message, inner) {
+
+ public SafeArrayTypeMismatchException(String message, Exception inner)
+ : base(message, inner)
+ {
SetErrorCode(__HResults.COR_E_SAFEARRAYTYPEMISMATCH);
}
- protected SafeArrayTypeMismatchException(SerializationInfo info, StreamingContext context) : base(info, context) {
+ 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..7fb3e4e5e8 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;
@@ -108,7 +107,7 @@ using System.Diagnostics.Contracts;
if (numBytes >= (ulong)Uninitialized)
throw new ArgumentOutOfRangeException(nameof(numBytes), Environment.GetResourceString("ArgumentOutOfRange_UIntPtrMax-1"));
- _numBytes = (UIntPtr) numBytes;
+ _numBytes = (UIntPtr)numBytes;
}
/// <summary>
@@ -130,7 +129,7 @@ using System.Diagnostics.Contracts;
if (numElements * sizeOfEachElement >= (ulong)Uninitialized)
throw new ArgumentOutOfRangeException(nameof(numElements), Environment.GetResourceString("ArgumentOutOfRange_UIntPtrMax-1"));
- _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();
@@ -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();
@@ -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,23 +348,25 @@ 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();
}
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..2d0e9a799c 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToCollectionAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToCollectionAdapter.cs
@@ -87,10 +87,10 @@ 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)))
+ if (srcLen > (destLen - (arrayIndex - destLB)))
throw new ArgumentException(Environment.GetResourceString("Argument_InsufficientSpaceToCopyCollection"));
- if(arrayIndex - destLB > destLen)
+ if (arrayIndex - destLB > destLen)
throw new ArgumentException(Environment.GetResourceString("Argument_IndexOutOfArrayBounds"));
// We need to verify the index as we;
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..8fd30438ad 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);
}
}
@@ -190,7 +196,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
if (this.Type != PropertyType.Size)
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Size"), __HResults.TYPE_E_TYPEMISMATCH);
Contract.EndContractBlock();
-
+
return Unbox<Size>(IReferenceFactory.s_sizeType);
}
@@ -200,7 +206,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
if (this.Type != PropertyType.Rect)
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Rect"), __HResults.TYPE_E_TYPEMISMATCH);
Contract.EndContractBlock();
-
+
return Unbox<Rect>(IReferenceFactory.s_rectType);
}
@@ -321,7 +327,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
if (this.Type != PropertyType.PointArray)
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Point[]"), __HResults.TYPE_E_TYPEMISMATCH);
Contract.EndContractBlock();
-
+
return UnboxArray<Point>(IReferenceFactory.s_pointType);
}
@@ -346,15 +352,18 @@ namespace System.Runtime.InteropServices.WindowsRuntime
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) {
+ if (dataArray == null)
+ {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, typeof(T).MakeArrayType().Name), __HResults.TYPE_E_TYPEMISMATCH);
}
@@ -365,10 +374,14 @@ 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) {
+ }
+ catch (InvalidCastException elementCastException)
+ {
Exception e = new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueArrayCoersion", this.Type, typeof(T).MakeArrayType().Name, i, elementCastException.Message), elementCastException);
e.SetErrorCode(elementCastException._HResult);
throw e;
@@ -381,81 +394,104 @@ 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) {
+ if (!IsCoercable(type, value) && type != PropertyType.Inspectable)
+ {
throw new InvalidCastException(Environment.GetResourceString("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) {
+ catch (FormatException)
+ {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", type, typeof(T).Name), __HResults.TYPE_E_TYPEMISMATCH);
}
- catch (InvalidCastException) {
+ catch (InvalidCastException)
+ {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", type, typeof(T).Name), __HResults.TYPE_E_TYPEMISMATCH);
}
- catch (OverflowException) {
+ catch (OverflowException)
+ {
throw new InvalidCastException(Environment.GetResourceString("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");
}
}
@@ -464,9 +500,11 @@ namespace System.Runtime.InteropServices.WindowsRuntime
throw new InvalidCastException(Environment.GetResourceString("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) {
+ if (_data.GetType() != expectedBoxedType)
+ {
throw new InvalidCastException(Environment.GetResourceString("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) {
+ if (dataArray == null || _data.GetType().GetElementType() != expectedArrayElementType)
+ {
throw new InvalidCastException(Environment.GetResourceString("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..0e9140f41b 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);
}
}
@@ -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 {
+ 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));
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..fe1ecff161 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,7 +105,7 @@ 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"));
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryKeyCollection.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryKeyCollection.cs
index c33e002e0e..9f33b2f946 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryKeyCollection.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryKeyCollection.cs
@@ -41,11 +41,13 @@ 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; }
}
@@ -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..b1a4042419 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryToMapAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryToMapAdapter.cs
@@ -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)
{
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryValueCollection.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryValueCollection.cs
index fcc7755d67..d599d24aa3 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>
@@ -44,11 +45,13 @@ 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; }
}
@@ -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/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..55f8a1e862 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs
@@ -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; }
}
@@ -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..2fac36b23f 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyDictionaryToIMapViewAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyDictionaryToIMapViewAdapter.cs
@@ -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..b902ded9c0 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)
{
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..6010eec6c8 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
{
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorViewAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorViewAdapter.cs
index 2e2ea9b876..0503b726dd 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorViewAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorViewAdapter.cs
@@ -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..8373885284 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
{
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ManagedActivationFactory.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ManagedActivationFactory.cs
index 2d08cab0ee..cace2047d9 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ManagedActivationFactory.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ManagedActivationFactory.cs
@@ -42,7 +42,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// with at least one ActivatableAttribute or StaticAttribute.
if (!(type is RuntimeType) || !type.IsExportedToWindowsRuntime)
throw new ArgumentException(Environment.GetResourceString("Argument_TypeNotActivatableViaWindowsRuntime", type), nameof(type));
-
+
m_type = type;
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToDictionaryAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToDictionaryAdapter.cs
index 981972ca9f..a8a13c6912 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToDictionaryAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToDictionaryAdapter.cs
@@ -110,7 +110,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
{
_this.Remove(key);
return true;
-
}
catch (Exception ex)
{
@@ -158,7 +157,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
}
catch (Exception ex)
{
-
if (__HResults.E_BOUNDS == ex._HResult)
throw new KeyNotFoundException(Environment.GetResourceString("Arg_KeyNotFound"));
throw;
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/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..c9824af17e 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,11 +792,11 @@ 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
{
@@ -821,19 +820,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 +842,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 +868,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
internal void AcquireWriterLock(int millisecondsTimeout)
{
EnterMyLock();
- for (; ; )
+ for (;;)
{
if (owners == 0)
{
@@ -912,15 +911,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 +944,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
{
if (!waitEvent.WaitOne(millisecondsTimeout, false))
throw new ReaderWriterLockTimedOutException();
-
+
waitSuccessful = true;
}
finally
@@ -977,18 +977,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 +1001,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
Debug.Assert(myLock != 0, "Exiting spin lock that is not held");
myLock = 0;
}
- };
+ };
}
//
@@ -1008,27 +1009,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);
@@ -1109,7 +1109,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 +1183,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);
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMetadata.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMetadata.cs
index 429112c8b0..b772a2252b 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;
@@ -52,11 +52,11 @@ namespace System.Runtime.InteropServices.WindowsRuntime
}
}
}
-
+
return null;
}
}
-
+
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..d8935ffda0 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(Environment.GetResourceString("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,7 +110,7 @@ namespace System.Runtime.Loader
if (PathInternal.IsPartiallyQualified(nativeImagePath))
{
- throw new ArgumentException( Environment.GetResourceString("Argument_AbsolutePathRequired"), nameof(nativeImagePath));
+ throw new ArgumentException(Environment.GetResourceString("Argument_AbsolutePathRequired"), nameof(nativeImagePath));
}
if (assemblyPath != null && PathInternal.IsPartiallyQualified(assemblyPath))
@@ -125,74 +124,74 @@ 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));
}
-
+
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 +201,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 +211,7 @@ namespace System.Runtime.Loader
}
}
}
-
+
return resolvedAssembly;
}
@@ -220,7 +219,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 +228,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"));
-
+
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);
}
-
+
return assembly;
}
-
+
public Assembly LoadFromAssemblyName(AssemblyName assemblyName)
{
// Attempt to load the assembly, using the same ordering as static load, in the current load context.
@@ -303,14 +301,14 @@ namespace System.Runtime.Loader
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 +329,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 +338,16 @@ 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)
{
@@ -365,7 +363,7 @@ namespace System.Runtime.Loader
[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 +371,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 +395,7 @@ namespace System.Runtime.Loader
return loadContextForAssembly;
}
-
+
// Set the root directory path for profile optimization.
public void SetProfileOptimizationRoot(string directoryPath)
{
@@ -424,7 +422,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 +432,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..2785942712 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?
@@ -168,7 +168,7 @@ 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"));
@@ -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(Environment.GetResourceString("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(Environment.GetResourceString("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,7 +345,7 @@ 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)
@@ -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
index a889f1559c..7781d3a210 100644
--- a/src/mscorlib/src/System/Runtime/Reliability/ReliabilityContractAttribute.cs
+++ b/src/mscorlib/src/System/Runtime/Reliability/ReliabilityContractAttribute.cs
@@ -16,25 +16,26 @@
**
===========================================================*/
-namespace System.Runtime.ConstrainedExecution {
- using System.Runtime.InteropServices;
- using System;
+using System.Runtime.InteropServices;
+using System;
+namespace System.Runtime.ConstrainedExecution
+{
[Serializable]
public enum Consistency : int
{
- MayCorruptProcess = 0,
+ MayCorruptProcess = 0,
MayCorruptAppDomain = 1,
- MayCorruptInstance = 2,
+ MayCorruptInstance = 2,
WillNotCorruptState = 3,
}
[Serializable]
public enum Cer : int
{
- None = 0,
- MayFail = 1, // Might fail, but the method will say it failed
- Success = 2,
+ 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)]
@@ -49,11 +50,13 @@ namespace System.Runtime.ConstrainedExecution {
_cer = cer;
}
- public Consistency ConsistencyGuarantee {
+ public Consistency ConsistencyGuarantee
+ {
get { return _consistency; }
}
- public Cer Cer {
+ 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/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..d1669b976f 100644
--- a/src/mscorlib/src/System/Runtime/Serialization/FormatterServices.cs
+++ b/src/mscorlib/src/System/Runtime/Serialization/FormatterServices.cs
@@ -11,25 +11,26 @@
**
**
============================================================*/
-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
+{
+ public 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,23 +38,26 @@ 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)) {
+
+ if (!(type is RuntimeType))
+ {
throw new SerializationException(Environment.GetResourceString("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
@@ -65,7 +69,8 @@ namespace System.Runtime.Serialization {
**Arguments: assemblyName -- The stringized assembly name.
**Exceptions: None
==============================================================================*/
- internal static Assembly LoadAssemblyFromString(String assemblyName) {
+ internal static Assembly LoadAssemblyFromString(String assemblyName)
+ {
//
// Try using the stringized assembly name to load from the fusion cache.
//
diff --git a/src/mscorlib/src/System/Runtime/Serialization/IDeserializationCallback.cs b/src/mscorlib/src/System/Runtime/Serialization/IDeserializationCallback.cs
index 2911a4016e..2b07ce9c38 100644
--- a/src/mscorlib/src/System/Runtime/Serialization/IDeserializationCallback.cs
+++ b/src/mscorlib/src/System/Runtime/Serialization/IDeserializationCallback.cs
@@ -12,11 +12,14 @@
**
**
===========================================================*/
-namespace System.Runtime.Serialization {
- using System;
+using System;
+
+namespace System.Runtime.Serialization
+{
// Interface does not need to be marked with the serializable attribute
- public interface IDeserializationCallback {
+ 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
index 0be0db9acd..1f6f682ee2 100644
--- a/src/mscorlib/src/System/Runtime/Serialization/IFormatterConverter.cs
+++ b/src/mscorlib/src/System/Runtime/Serialization/IFormatterConverter.cs
@@ -13,27 +13,30 @@
**
**
============================================================*/
-namespace System.Runtime.Serialization {
- using System;
+using System;
+
+namespace System.Runtime.Serialization
+{
[CLSCompliant(false)]
- public interface IFormatterConverter {
+ 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);
+ 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);
+ 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);
+ String ToString(Object value);
}
}
diff --git a/src/mscorlib/src/System/Runtime/Serialization/IObjectReference.cs b/src/mscorlib/src/System/Runtime/Serialization/IObjectReference.cs
index ef5ee6ade0..b07f26fe09 100644
--- a/src/mscorlib/src/System/Runtime/Serialization/IObjectReference.cs
+++ b/src/mscorlib/src/System/Runtime/Serialization/IObjectReference.cs
@@ -15,11 +15,14 @@
**
**
===========================================================*/
-namespace System.Runtime.Serialization {
- using System;
+using System;
+
+namespace System.Runtime.Serialization
+{
// Interface does not need to be marked with the serializable attribute
- public interface IObjectReference {
+ 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
index 816aa0484b..4e5873b817 100644
--- a/src/mscorlib/src/System/Runtime/Serialization/ISerializable.cs
+++ b/src/mscorlib/src/System/Runtime/Serialization/ISerializable.cs
@@ -13,16 +13,17 @@
**
===========================================================*/
-namespace System.Runtime.Serialization {
- using System.Runtime.Remoting;
- using System.Runtime.Serialization;
- using System;
- using System.Reflection;
-
- public interface ISerializable {
+using System.Runtime.Remoting;
+using System.Runtime.Serialization;
+using System;
+using System.Reflection;
+
+namespace System.Runtime.Serialization
+{
+ 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
index 260e873bc7..45173db4f9 100644
--- a/src/mscorlib/src/System/Runtime/Serialization/SafeSerializationManager.cs
+++ b/src/mscorlib/src/System/Runtime/Serialization/SafeSerializationManager.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.Collections;
using System.Collections.Generic;
@@ -211,7 +212,7 @@ namespace System.Runtime.Serialization
private StreamingContext m_streamingContext;
private List<object> m_serializedStates = new List<object>();
- internal SafeSerializationEventArgs() {}
+ internal SafeSerializationEventArgs() { }
public void AddSerializedState(ISafeSerializationData serializedState)
{
diff --git a/src/mscorlib/src/System/Runtime/Serialization/SerializationAttributes.cs b/src/mscorlib/src/System/Runtime/Serialization/SerializationAttributes.cs
index 38abffa66e..435ca279e4 100644
--- a/src/mscorlib/src/System/Runtime/Serialization/SerializationAttributes.cs
+++ b/src/mscorlib/src/System/Runtime/Serialization/SerializationAttributes.cs
@@ -10,50 +10,52 @@
**
**
============================================================*/
+
+using System;
+using System.Diagnostics.Contracts;
+using System.Reflection;
+
namespace System.Runtime.Serialization
{
- using System;
- using System.Diagnostics.Contracts;
- using System.Reflection;
-
- [AttributeUsage(AttributeTargets.Field, Inherited=false)]
- public sealed class OptionalFieldAttribute : Attribute
+ [AttributeUsage(AttributeTargets.Field, Inherited = false)]
+ public sealed class OptionalFieldAttribute : Attribute
{
- int versionAdded = 1;
+ private int versionAdded = 1;
public OptionalFieldAttribute() { }
-
- public int VersionAdded
+
+ public int VersionAdded
{
- get {
- return this.versionAdded;
+ get
+ {
+ return versionAdded;
}
- set {
+ set
+ {
if (value < 1)
throw new ArgumentException(Environment.GetResourceString("Serialization_OptionalFieldVersionValue"));
Contract.EndContractBlock();
- this.versionAdded = value;
+ versionAdded = value;
}
}
}
- [AttributeUsage(AttributeTargets.Method, Inherited=false)]
- public sealed class OnSerializingAttribute : Attribute
+ [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 OnSerializedAttribute : Attribute
{
}
- [AttributeUsage(AttributeTargets.Method, Inherited=false)]
- public sealed class OnDeserializingAttribute : Attribute
+ [AttributeUsage(AttributeTargets.Method, Inherited = false)]
+ public sealed class OnDeserializingAttribute : Attribute
{
}
- [AttributeUsage(AttributeTargets.Method, Inherited=false)]
- public sealed class OnDeserializedAttribute : 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
index e9cb79b7af..65db0e930a 100644
--- a/src/mscorlib/src/System/Runtime/Serialization/SerializationException.cs
+++ b/src/mscorlib/src/System/Runtime/Serialization/SerializationException.cs
@@ -12,33 +12,38 @@
**
=============================================================================*/
-namespace System.Runtime.Serialization {
-
- using System;
- using System.Runtime.Serialization;
+using System;
+using System.Runtime.Serialization;
+
+namespace System.Runtime.Serialization
+{
[Serializable]
- public class SerializationException : SystemException {
-
+ 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) {
+ public SerializationException()
+ : base(_nullMessage)
+ {
SetErrorCode(__HResults.COR_E_SERIALIZATION);
}
-
- public SerializationException(String message)
- : base(message) {
+
+ public SerializationException(String message)
+ : base(message)
+ {
SetErrorCode(__HResults.COR_E_SERIALIZATION);
}
- public SerializationException(String message, Exception innerException) : base (message, innerException) {
+ public SerializationException(String message, Exception innerException) : base(message, innerException)
+ {
SetErrorCode(__HResults.COR_E_SERIALIZATION);
}
- protected SerializationException(SerializationInfo info, StreamingContext context) : base (info, context) {
+ 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..d024361985 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);
}
@@ -382,7 +382,6 @@ namespace System.Runtime.Serialization
m_data[index] = value;
m_types[index] = type;
}
-
}
private int FindElement(String name)
@@ -451,7 +450,6 @@ namespace System.Runtime.Serialization
public Object GetValue(String name, Type type)
{
-
if ((object)type == null)
{
throw new ArgumentNullException(nameof(type));
@@ -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
index 0858dfc19f..b7857dece2 100644
--- a/src/mscorlib/src/System/Runtime/Serialization/SerializationInfoEnumerator.cs
+++ b/src/mscorlib/src/System/Runtime/Serialization/SerializationInfoEnumerator.cs
@@ -12,39 +12,49 @@
**
**
============================================================*/
-namespace System.Runtime.Serialization {
- using System;
- using System.Diagnostics;
- using System.Collections;
- using System.Diagnostics.Contracts;
+using System;
+using System.Diagnostics;
+using System.Collections;
+using System.Diagnostics.Contracts;
+
+namespace System.Runtime.Serialization
+{
//
// The tuple returned by SerializationInfoEnumerator.Current.
//
- public struct SerializationEntry {
- private Type m_type;
+ public struct SerializationEntry
+ {
+ private Type m_type;
private Object m_value;
private String m_name;
- public Object Value {
- get {
+ public Object Value
+ {
+ get
+ {
return m_value;
}
}
- public String Name {
- get {
+ public String Name
+ {
+ get
+ {
return m_name;
}
}
- public Type ObjectType {
- get {
+ public Type ObjectType
+ {
+ get
+ {
return m_type;
}
}
- internal SerializationEntry(String entryName, Object entryValue, Type entryType) {
+ internal SerializationEntry(String entryName, Object entryValue, Type entryType)
+ {
m_value = entryValue;
m_name = entryName;
m_type = entryType;
@@ -56,86 +66,108 @@ namespace System.Runtime.Serialization {
// 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;
+ public sealed class SerializationInfoEnumerator : IEnumerator
+ {
+ private String[] m_members;
+ private Object[] m_data;
+ private Type[] m_types;
+ private int m_numItems;
+ private int m_currItem;
+ private 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");
+ 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_numItems = numItems - 1;
m_currItem = -1;
m_current = false;
}
- public bool MoveNext() {
- if (m_currItem<m_numItems) {
+ public bool MoveNext()
+ {
+ if (m_currItem < m_numItems)
+ {
m_currItem++;
m_current = true;
- } else {
+ }
+ else
+ {
m_current = false;
}
return m_current;
}
/// <internalonly/>
- Object IEnumerator.Current { //Actually returns a SerializationEntry
- get {
- if (m_current==false) {
+ 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) {
+ 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() {
+ public void Reset()
+ {
m_currItem = -1;
m_current = false;
}
- public String Name {
- get {
- if (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) {
+ 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) {
+ 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
index c01a3edc4f..12a7631714 100644
--- a/src/mscorlib/src/System/Runtime/Serialization/StreamingContext.cs
+++ b/src/mscorlib/src/System/Runtime/Serialization/StreamingContext.cs
@@ -11,62 +11,74 @@
**
**
===========================================================*/
-namespace System.Runtime.Serialization {
- using System.Runtime.Remoting;
- using System;
+using System.Runtime.Remoting;
+using System;
+
+namespace System.Runtime.Serialization
+{
[Serializable]
- public struct StreamingContext {
+ public struct StreamingContext
+ {
internal Object m_additionalContext;
internal StreamingContextStates m_state;
-
- public StreamingContext(StreamingContextStates state)
- : this (state, null) {
+
+ public StreamingContext(StreamingContextStates state)
+ : this(state, null)
+ {
}
-
- public StreamingContext(StreamingContextStates state, Object additional) {
+
+ public StreamingContext(StreamingContextStates state, Object additional)
+ {
m_state = state;
m_additionalContext = additional;
}
-
- public Object Context {
+
+ public Object Context
+ {
get { return m_additionalContext; }
}
-
- public override bool Equals(Object obj) {
- if (!(obj is StreamingContext)) {
+
+ 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) {
+ ((StreamingContext)obj).m_state == m_state)
+ {
return true;
- }
+ }
return false;
}
-
- public override int GetHashCode() {
+
+ public override int GetHashCode()
+ {
return (int)m_state;
}
-
- public StreamingContextStates State {
- get { return 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,
+ [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
index 9fafce4caa..216a48a370 100644
--- a/src/mscorlib/src/System/Runtime/Versioning/NonVersionableAttribute.cs
+++ b/src/mscorlib/src/System/Runtime/Versioning/NonVersionableAttribute.cs
@@ -4,7 +4,6 @@
/*============================================================
**
-** Class: NonVersionableAttribute
**
**
** The [NonVersionable] attribute is applied to indicate that the implementation
@@ -20,18 +19,19 @@
** extremely trivial low level methods where NonVersionable gets used, but if there is any plan to
** significantly extend its usage or allow 3rd parties to use it please discuss with the diagnostics team.
===========================================================*/
+
using System;
using System.Diagnostics;
-namespace System.Runtime.Versioning {
-
+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,
+ [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Constructor,
AllowMultiple = false, Inherited = false)]
- sealed class NonVersionableAttribute : Attribute {
-
+ internal 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
index 600ba3f154..59fc15aa37 100644
--- a/src/mscorlib/src/System/Runtime/Versioning/TargetFrameworkAttribute.cs
+++ b/src/mscorlib/src/System/Runtime/Versioning/TargetFrameworkAttribute.cs
@@ -12,13 +12,15 @@
** Emitted by VS, and can help catch deployment problems.
**
===========================================================*/
+
using System;
using System.Diagnostics.Contracts;
-namespace System.Runtime.Versioning {
-
+namespace System.Runtime.Versioning
+{
[AttributeUsageAttribute(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)]
- public sealed class TargetFrameworkAttribute : Attribute {
+ public sealed class TargetFrameworkAttribute : Attribute
+ {
private String _frameworkName; // A target framework moniker
private String _frameworkDisplayName;
@@ -33,11 +35,13 @@ namespace System.Runtime.Versioning {
// The target framework moniker that this assembly was compiled against.
// Use the FrameworkName class to interpret target framework monikers.
- public String FrameworkName {
+ public String FrameworkName
+ {
get { return _frameworkName; }
}
- public String FrameworkDisplayName {
+ 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..d343de4073 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;
@@ -48,7 +48,7 @@ namespace System
[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;
}
@@ -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);
@@ -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);
@@ -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();
@@ -666,14 +667,14 @@ namespace System
throw new SerializationException(Environment.GetResourceString("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(Environment.GetResourceString("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;
@@ -777,7 +778,7 @@ namespace System
}
private IRuntimeMethodInfo m_value;
-
+
internal RuntimeMethodHandle(IRuntimeMethodInfo method)
{
m_value = method;
@@ -793,15 +794,15 @@ 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;
@@ -809,15 +810,15 @@ namespace System
throw new SerializationException(Environment.GetResourceString("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"));
-
+
// 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
@@ -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,13 +1299,13 @@ 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)
+
+ FieldInfo f = (RuntimeFieldInfo)info.GetValue("FieldObj", typeof(RuntimeFieldInfo));
+
+ if (f == null)
throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientState"));
m_ptr = f.FieldHandle.m_ptr;
@@ -1315,53 +1314,53 @@ namespace System
throw new SerializationException(Environment.GetResourceString("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"));
- RuntimeFieldInfo fldInfo = (RuntimeFieldInfo)RuntimeType.GetFieldInfo(this.GetRuntimeFieldInfo());
-
- info.AddValue("FieldObj",fldInfo, typeof(RuntimeFieldInfo));
+ RuntimeFieldInfo fldInfo = (RuntimeFieldInfo)RuntimeType.GetFieldInfo(this.GetRuntimeFieldInfo());
+
+ 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;
}
@@ -1405,11 +1404,11 @@ namespace System
// 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));
}
@@ -1420,7 +1419,7 @@ namespace System
if (!ModuleHandle.GetMetadataImport(module).IsValidToken(typeToken))
throw new ArgumentOutOfRangeException(nameof(typeToken),
Environment.GetResourceString("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,
@@ -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,7 +1493,7 @@ 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)
{
@@ -1502,11 +1501,11 @@ namespace System
if (!ModuleHandle.GetMetadataImport(module.GetNativeHandle()).IsValidToken(fieldToken))
throw new ArgumentOutOfRangeException(nameof(fieldToken),
Environment.GetResourceString("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..b85093d72f 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(Environment.GetResourceString("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,241 @@ 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) {
+ catch (OverflowException e)
+ {
throw new OverflowException(Environment.GetResourceString("Overflow_SByte"), e);
}
- 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)
+ {
throw new OverflowException(Environment.GetResourceString("Overflow_SByte"));
}
return (sbyte)i;
}
-
+
if (i < MinValue || i > MaxValue) throw new OverflowException(Environment.GetResourceString("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) {
+ DateTime IConvertible.ToDateTime(IFormatProvider provider)
+ {
throw new InvalidCastException(Environment.GetResourceString("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
index 81a1147a4e..9e93bc1dda 100644
--- a/src/mscorlib/src/System/Security/Attributes.cs
+++ b/src/mscorlib/src/System/Security/Attributes.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.Runtime.InteropServices;
+using System.Runtime.InteropServices;
namespace System.Security
{
@@ -13,7 +13,7 @@ namespace System.Security
// 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 )]
+ [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, AllowMultiple = true, Inherited = false)]
sealed internal class DynamicSecurityMethodAttribute : System.Attribute
{
}
@@ -21,14 +21,14 @@ namespace System.Security
// 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 )]
+ [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 )]
+ [AttributeUsage(AttributeTargets.Module, AllowMultiple = true, Inherited = false)]
sealed public class UnverifiableCodeAttribute : System.Attribute
{
}
@@ -38,11 +38,11 @@ namespace System.Security
// 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 )]
+ [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)]
sealed public class AllowPartiallyTrustedCallersAttribute : System.Attribute
{
private PartialTrustVisibilityLevel _visibilityLevel;
- public AllowPartiallyTrustedCallersAttribute () { }
+ public AllowPartiallyTrustedCallersAttribute() { }
public PartialTrustVisibilityLevel PartialTrustVisibilityLevel
{
@@ -67,24 +67,24 @@ namespace System.Security
// 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 |
+ [AttributeUsage(AttributeTargets.Assembly |
AttributeTargets.Class |
AttributeTargets.Struct |
AttributeTargets.Enum |
AttributeTargets.Constructor |
AttributeTargets.Method |
AttributeTargets.Field |
- AttributeTargets.Interface |
+ AttributeTargets.Interface |
AttributeTargets.Delegate,
AllowMultiple = false,
- Inherited = false )]
- sealed public class SecurityCriticalAttribute : System.Attribute
+ Inherited = false)]
+ sealed public class SecurityCriticalAttribute : System.Attribute
{
#pragma warning disable 618 // We still use SecurityCriticalScope for v2 compat
- private SecurityCriticalScope _val;
+ private SecurityCriticalScope _val;
- public SecurityCriticalAttribute () {}
+ public SecurityCriticalAttribute() { }
public SecurityCriticalAttribute(SecurityCriticalScope scope)
{
@@ -92,8 +92,10 @@ namespace System.Security
}
[Obsolete("SecurityCriticalScope is only used for .NET 2.0 transparency compatibility.")]
- public SecurityCriticalScope Scope {
- get {
+ public SecurityCriticalScope Scope
+ {
+ get
+ {
return _val;
}
}
@@ -119,11 +121,11 @@ namespace System.Security
AttributeTargets.Interface |
AttributeTargets.Delegate,
AllowMultiple = false,
- Inherited = 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 () { }
+ public SecurityTreatAsSafeAttribute() { }
}
// SecuritySafeCriticalAttribute:
@@ -144,10 +146,10 @@ namespace System.Security
AttributeTargets.Interface |
AttributeTargets.Delegate,
AllowMultiple = false,
- Inherited = false )]
+ Inherited = false)]
sealed public class SecuritySafeCriticalAttribute : System.Attribute
{
- public SecuritySafeCriticalAttribute () { }
+ public SecuritySafeCriticalAttribute() { }
}
// SecurityTransparentAttribute:
@@ -156,17 +158,17 @@ namespace System.Security
// Assert will be restricted, SuppressUnmanagedCode, LinkDemand, unsafe, and unverifiable code will be converted
// into Full-Demands.
- [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false )]
+ [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)]
sealed public class SecurityTransparentAttribute : System.Attribute
{
- public SecurityTransparentAttribute () {}
+ public SecurityTransparentAttribute() { }
}
public enum SecurityRuleSet : byte
{
- None = 0,
- Level1 = 1, // v2.0 transparency model
- Level2 = 2, // v4.0 transparency model
+ None = 0,
+ Level1 = 1, // v2.0 transparency model
+ Level2 = 2, // v4.0 transparency model
}
// SecurityRulesAttribute
diff --git a/src/mscorlib/src/System/Security/SecurityException.cs b/src/mscorlib/src/System/Security/SecurityException.cs
index 8811be82ff..90fe053394 100644
--- a/src/mscorlib/src/System/Security/SecurityException.cs
+++ b/src/mscorlib/src/System/Security/SecurityException.cs
@@ -13,18 +13,18 @@
**
=============================================================================*/
+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;
+
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
{
diff --git a/src/mscorlib/src/System/Security/SecurityState.cs b/src/mscorlib/src/System/Security/SecurityState.cs
index 55dcce07c0..11c67d95f0 100644
--- a/src/mscorlib/src/System/Security/SecurityState.cs
+++ b/src/mscorlib/src/System/Security/SecurityState.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.Security;
@@ -8,8 +9,8 @@ namespace System.Security
{
public abstract class SecurityState
{
- protected SecurityState(){}
-
+ protected SecurityState() { }
+
public bool IsStateAvailable()
{
AppDomainManager domainManager = AppDomainManager.CurrentAppDomainManager;
@@ -21,5 +22,4 @@ namespace System.Security
// 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
index 4ec353876a..d694acbba8 100644
--- a/src/mscorlib/src/System/Security/Util/URLString.cs
+++ b/src/mscorlib/src/System/Security/Util/URLString.cs
@@ -8,8 +8,8 @@
// Implementation of membership condition for zones
//
-namespace System.Security.Util {
-
+namespace System.Security.Util
+{
using System;
using System.Collections;
using System.Collections.Generic;
diff --git a/src/mscorlib/src/System/Security/VerificationException.cs b/src/mscorlib/src/System/Security/VerificationException.cs
index 5defbd6603..d07b76f6ad 100644
--- a/src/mscorlib/src/System/Security/VerificationException.cs
+++ b/src/mscorlib/src/System/Security/VerificationException.cs
@@ -4,29 +4,35 @@
//
-namespace System.Security {
- using System.Security;
- using System;
- using System.Runtime.Serialization;
+using System.Security;
+using System;
+using System.Runtime.Serialization;
+namespace System.Security
+{
[Serializable]
- public class VerificationException : SystemException {
- public VerificationException()
- : base(Environment.GetResourceString("Verification_Exception")) {
+ public class VerificationException : SystemException
+ {
+ public VerificationException()
+ : base(Environment.GetResourceString("Verification_Exception"))
+ {
SetErrorCode(__HResults.COR_E_VERIFICATION);
}
- public VerificationException(String message)
- : base(message) {
+ public VerificationException(String message)
+ : base(message)
+ {
SetErrorCode(__HResults.COR_E_VERIFICATION);
}
- public VerificationException(String message, Exception innerException)
- : base(message, innerException) {
+ public VerificationException(String message, Exception innerException)
+ : base(message, innerException)
+ {
SetErrorCode(__HResults.COR_E_VERIFICATION);
}
- protected VerificationException(SerializationInfo info, StreamingContext context) : base(info, context) {
+ 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 0ba1d8a029..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()
@@ -42,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..f3ed5b8b06 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(Environment.GetResourceString("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,170 @@ 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) {
+ char IConvertible.ToChar(IFormatProvider provider)
+ {
throw new InvalidCastException(Environment.GetResourceString("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) {
+ DateTime IConvertible.ToDateTime(IFormatProvider provider)
+ {
throw new InvalidCastException(Environment.GetResourceString("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 b0d5771c10..7e93afe4f4 100644
--- a/src/mscorlib/src/System/Span.cs
+++ b/src/mscorlib/src/System/Span.cs
@@ -350,7 +350,7 @@ namespace System
{
ThrowHelper.ThrowNotSupportedException_CannotCallEqualsOnSpan();
// Prevent compiler error CS0161: 'Span<T>.Equals(object)': not all code paths return a value
- return default(bool);
+ return default(bool);
}
/// <summary>
@@ -365,7 +365,7 @@ namespace System
{
ThrowHelper.ThrowNotSupportedException_CannotCallGetHashCodeOnSpan();
// Prevent compiler error CS0161: 'Span<T>.GetHashCode()': not all code paths return a value
- return default(int);
+ return default(int);
}
/// <summary>
diff --git a/src/mscorlib/src/System/String.Comparison.cs b/src/mscorlib/src/System/String.Comparison.cs
index 970d107e1b..54b52df578 100644
--- a/src/mscorlib/src/System/String.Comparison.cs
+++ b/src/mscorlib/src/System/String.Comparison.cs
@@ -24,13 +24,13 @@ 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;
- while (length != 0)
+ while (length != 0)
{
int charA = *a;
int charB = *b;
@@ -61,14 +61,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 +120,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 +128,7 @@ namespace System
return true;
- ReturnFalse:
+ ReturnFalse:
return false;
}
}
@@ -170,7 +170,7 @@ namespace System
return true;
- ReturnFalse:
+ ReturnFalse:
return false;
}
}
@@ -225,7 +225,7 @@ namespace System
// this compare can include the zero terminator. Bitwise OR avoids a branch.
return length == 0 | *a == *b;
- ReturnFalse:
+ ReturnFalse:
return false;
}
}
@@ -256,7 +256,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
@@ -264,7 +264,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
@@ -273,7 +273,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
@@ -311,17 +311,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
@@ -331,8 +331,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)
@@ -341,7 +341,7 @@ namespace System
}
#endif // BIT64
- DiffNextInt:
+ DiffNextInt:
if (*a != *b) return *a - *b;
DiffOffset1:
@@ -349,7 +349,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.
@@ -359,7 +359,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
@@ -373,11 +373,11 @@ 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))
@@ -401,7 +401,8 @@ namespace System
return 1;
}
- switch (comparisonType) {
+ switch (comparisonType)
+ {
case StringComparison.CurrentCulture:
return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, CompareOptions.None);
@@ -426,7 +427,8 @@ 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));
}
@@ -448,7 +450,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));
@@ -508,7 +511,7 @@ namespace System
int lengthA = length;
int lengthB = length;
-
+
if (strA != null)
{
lengthA = Math.Min(lengthA, strA.Length - indexA);
@@ -561,17 +564,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) {
+ 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));
}
Contract.EndContractBlock();
-
+
if (strA == null || strB == null)
{
if (object.ReferenceEquals(strA, strB))
@@ -608,7 +613,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);
@@ -634,7 +640,6 @@ namespace System
default:
throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"));
}
-
}
// Compares strA and strB using an ordinal (code-point) comparison.
@@ -666,7 +671,7 @@ namespace System
return CompareOrdinalHelper(strA, strB);
}
-
+
// Compares strA and strB using an ordinal (code-point) comparison.
//
@@ -697,7 +702,7 @@ namespace System
string paramName = indexA < 0 ? nameof(indexA) : nameof(indexB);
throw new ArgumentOutOfRangeException(paramName, Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
-
+
int lengthA = Math.Min(length, strA.Length - indexA);
int lengthB = Math.Min(length, strB.Length - indexB);
@@ -736,7 +741,7 @@ namespace System
return CompareTo(other); // will call the string-based overload
}
-
+
// Determines the sorting relation of StrB to the current instance.
//
[Pure]
@@ -751,30 +756,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) {
+ if (comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase)
+ {
throw new ArgumentException(Environment.GetResourceString("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);
@@ -785,7 +797,7 @@ 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);
@@ -798,17 +810,20 @@ namespace System
#endif
default:
throw new ArgumentException(Environment.GetResourceString("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;
}
@@ -822,7 +837,8 @@ namespace System
}
[Pure]
- public bool EndsWith(char value) {
+ public bool EndsWith(char value)
+ {
int thisLen = Length;
return thisLen != 0 && this[thisLen - 1] == value;
}
@@ -862,7 +878,7 @@ namespace System
// instead of calling string.op_Equality.
if (value == null)
return false;
-
+
if (this.Length != value.Length)
return false;
@@ -870,20 +886,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));
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);
@@ -906,7 +926,8 @@ namespace System
return false;
// If both strings are ASCII strings, we can take the fast path.
- if (this.IsAscii() && value.IsAscii()) {
+ if (this.IsAscii() && value.IsAscii())
+ {
return EqualsIgnoreCaseAsciiHelper(this, value);
}
@@ -925,12 +946,15 @@ namespace System
// 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;
}
@@ -938,20 +962,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));
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);
@@ -973,9 +1001,11 @@ 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()) {
+ if (a.IsAscii() && b.IsAscii())
+ {
return EqualsIgnoreCaseAsciiHelper(a, b);
}
// Take the slow path.
@@ -992,12 +1022,14 @@ namespace System
}
}
- 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
@@ -1006,7 +1038,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();
}
@@ -1035,11 +1068,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)
@@ -1048,9 +1084,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)
@@ -1086,12 +1123,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();
@@ -1099,25 +1138,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) {
+ if (comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase)
+ {
throw new ArgumentException(Environment.GetResourceString("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);
@@ -1128,10 +1173,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) ?
@@ -1139,10 +1185,11 @@ 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
@@ -1151,17 +1198,20 @@ namespace System
default:
throw new ArgumentException(Environment.GetResourceString("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;
}
diff --git a/src/mscorlib/src/System/String.Manipulation.cs b/src/mscorlib/src/System/String.Manipulation.cs
index 5a9be5c248..90ec773bf7 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;
@@ -748,7 +773,7 @@ namespace System
{
throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("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,16 +858,18 @@ 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"));
int oldLength = Length;
@@ -866,12 +893,14 @@ 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"));
int oldLength = Length;
@@ -897,24 +926,24 @@ namespace System
public String Remove(int startIndex, int count)
{
if (startIndex < 0)
- throw new ArgumentOutOfRangeException(nameof(startIndex),
+ throw new ArgumentOutOfRangeException(nameof(startIndex),
Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
if (count < 0)
- throw new ArgumentOutOfRangeException(nameof(count),
+ throw new ArgumentOutOfRangeException(nameof(count),
Environment.GetResourceString("ArgumentOutOfRange_NegativeCount"));
if (count > Length - startIndex)
- throw new ArgumentOutOfRangeException(nameof(count),
+ throw new ArgumentOutOfRangeException(nameof(count),
Environment.GetResourceString("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,17 +960,20 @@ namespace System
}
// a remove that just takes a startindex.
- public string Remove( int startIndex ) {
- if (startIndex < 0) {
- throw new ArgumentOutOfRangeException(nameof(startIndex),
+ public string Remove(int startIndex)
+ {
+ if (startIndex < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(startIndex),
Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
}
-
- if (startIndex >= Length) {
- throw new ArgumentOutOfRangeException(nameof(startIndex),
- Environment.GetResourceString("ArgumentOutOfRange_StartIndexLessThanLength"));
+
+ if (startIndex >= Length)
+ {
+ throw new ArgumentOutOfRangeException(nameof(startIndex),
+ Environment.GetResourceString("ArgumentOutOfRange_StartIndexLessThanLength"));
}
-
+
Contract.Ensures(Contract.Result<String>() != null);
Contract.EndContractBlock();
@@ -1122,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);
}
@@ -1141,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);
}
@@ -1157,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);
}
@@ -1195,7 +1232,7 @@ namespace System
bool omitEmptyEntries = (options == StringSplitOptions.RemoveEmptyEntries);
- if ((count == 0) || (omitEmptyEntries && this.Length == 0))
+ if ((count == 0) || (omitEmptyEntries && this.Length == 0))
{
return EmptyArray<String>.Value;
}
@@ -1204,53 +1241,60 @@ namespace System
{
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"));
}
- if (options < StringSplitOptions.None || options > StringSplitOptions.RemoveEmptyEntries) {
+ if (options < StringSplitOptions.None || options > StringSplitOptions.RemoveEmptyEntries)
+ {
throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)options));
}
Contract.EndContractBlock();
@@ -1259,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)) {
+
+ if ((count == 0) || (omitEmptyEntries && this.Length == 0))
+ {
return EmptyArray<String>.Value;
}
- if (count == 1 || (singleSeparator && separator.Length == 0)) {
+ if (count == 1 || (singleSeparator && separator.Length == 0))
+ {
return new String[] { this };
}
@@ -1276,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;
@@ -1318,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);
@@ -1350,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;
@@ -1374,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
@@ -1394,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;
@@ -1461,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++;
@@ -1491,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) {
+ if (startIndex < 0)
+ {
throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
}
- if (startIndex > Length) {
+ if (startIndex > Length)
+ {
throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_StartIndexLargerThanLength"));
}
- if (length < 0) {
+ if (length < 0)
+ {
throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_NegativeLength"));
}
- if (startIndex > Length - length) {
+ if (startIndex > Length - length)
+ {
throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("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));
@@ -1567,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));
@@ -1597,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..426bf21bec 100644
--- a/src/mscorlib/src/System/String.Searching.cs
+++ b/src/mscorlib/src/System/String.Searching.cs
@@ -11,25 +11,29 @@ 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"));
@@ -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,31 +120,37 @@ 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) {
+ public int IndexOf(String value, int startIndex, int count)
+ {
+ if (startIndex < 0 || startIndex > this.Length)
+ {
throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
- if (count < 0 || count > this.Length - startIndex) {
+ if (count < 0 || count > this.Length - startIndex)
+ {
throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("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));
@@ -148,7 +162,8 @@ namespace System
throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_Count"));
Contract.EndContractBlock();
- switch (comparisonType) {
+ switch (comparisonType)
+ {
case StringComparison.CurrentCulture:
return CultureInfo.CurrentCulture.CompareInfo.IndexOf(this, value, startIndex, count, CompareOptions.None);
@@ -172,7 +187,7 @@ namespace System
default:
throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), nameof(comparisonType));
- }
+ }
}
// Returns the index of the last occurrence of a specified character in the current instance.
@@ -181,17 +196,20 @@ 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;
@@ -228,54 +246,60 @@ 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) {
+ public int LastIndexOf(String value, int startIndex, int count)
+ {
+ if (count < 0)
+ {
throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("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();
@@ -306,7 +333,7 @@ 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"));
-
+
// Make sure that we allow startIndex == this.Length
if (startIndex == this.Length)
{
@@ -324,7 +351,8 @@ namespace System
throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_Count"));
- switch (comparisonType) {
+ switch (comparisonType)
+ {
case StringComparison.CurrentCulture:
return CultureInfo.CurrentCulture.CompareInfo.LastIndexOf(this, value, startIndex, count, CompareOptions.None);
@@ -338,7 +366,7 @@ 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);
@@ -346,7 +374,7 @@ namespace System
return TextInfo.LastIndexOfStringOrdinalIgnoreCase(this, value, startIndex, count);
default:
throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), nameof(comparisonType));
- }
+ }
}
}
}
diff --git a/src/mscorlib/src/System/String.cs b/src/mscorlib/src/System/String.cs
index 175e396633..eb4d7921e5 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;
}
@@ -126,19 +130,20 @@ namespace System {
// 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,7 +152,7 @@ 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)
@@ -162,7 +167,7 @@ namespace System {
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,28 +204,30 @@ 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
@@ -225,26 +235,29 @@ namespace System {
throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (startIndex < 0)
throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
- if ((value + startIndex) < value) {
+ if ((value + startIndex) < value)
+ {
// overflow check
throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("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),
+ Environment.GetResourceString("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,
@@ -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,7 +422,7 @@ 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));
@@ -421,11 +437,14 @@ namespace System {
throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("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)
@@ -475,10 +501,10 @@ namespace System {
throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_MustBeNonNegNum", nameof(count)));
}
- private static unsafe int wcslen(char *ptr)
+ private 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,7 +595,7 @@ namespace System {
return count;
}
- private unsafe String CtorCharPtr(char *ptr)
+ private unsafe String CtorCharPtr(char* ptr)
{
if (ptr == null)
return String.Empty;
@@ -581,7 +607,8 @@ namespace System {
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,25 +618,29 @@ namespace System {
wstrcpy(dest, ptr, count);
return result;
}
- catch (NullReferenceException) {
+ catch (NullReferenceException)
+ {
throw new ArgumentOutOfRangeException(nameof(ptr), Environment.GetResourceString("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) {
+ if (length < 0)
+ {
throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_NegativeLength"));
}
- if (startIndex < 0) {
+ if (startIndex < 0)
+ {
throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("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"));
}
@@ -619,12 +650,14 @@ namespace System {
String result = FastAllocateString(length);
- try {
+ try
+ {
fixed (char* dest = &result.m_firstChar)
wstrcpy(dest, pFrom, length);
return result;
}
- catch (NullReferenceException) {
+ catch (NullReferenceException)
+ {
throw new ArgumentOutOfRangeException(nameof(ptr), Environment.GetResourceString("ArgumentOutOfRange_PartialWCHAR"));
}
}
@@ -632,30 +665,35 @@ namespace System {
[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,99 @@ 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,14 +854,16 @@ 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.");
@@ -810,26 +871,29 @@ namespace System {
}
/// <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
index cf65c48c2b..c50a19b9b5 100644
--- a/src/mscorlib/src/System/StringComparer.cs
+++ b/src/mscorlib/src/System/StringComparer.cs
@@ -3,9 +3,10 @@
// See the LICENSE file in the project root for more information.
-namespace System {
+namespace System
+{
using System.Collections;
- using System.Collections.Generic;
+ using System.Collections.Generic;
using System.Globalization;
using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
@@ -13,49 +14,62 @@ namespace System {
[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);
+ 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);
+ private static readonly StringComparer _ordinalIgnoreCase = new OrdinalComparer(true);
- public static StringComparer InvariantCulture {
- get {
+ public static StringComparer InvariantCulture
+ {
+ get
+ {
Contract.Ensures(Contract.Result<StringComparer>() != null);
return _invariantCulture;
}
}
-
- public static StringComparer InvariantCultureIgnoreCase {
- get {
+
+ public static StringComparer InvariantCultureIgnoreCase
+ {
+ get
+ {
Contract.Ensures(Contract.Result<StringComparer>() != null);
return _invariantCultureIgnoreCase;
}
}
- public static StringComparer CurrentCulture {
- get {
+ public static StringComparer CurrentCulture
+ {
+ get
+ {
Contract.Ensures(Contract.Result<StringComparer>() != null);
- return new CultureAwareComparer(CultureInfo.CurrentCulture, false);
+ return new CultureAwareComparer(CultureInfo.CurrentCulture, false);
}
}
-
- public static StringComparer CurrentCultureIgnoreCase {
- get {
+
+ public static StringComparer CurrentCultureIgnoreCase
+ {
+ get
+ {
Contract.Ensures(Contract.Result<StringComparer>() != null);
- return new CultureAwareComparer(CultureInfo.CurrentCulture, true);
+ return new CultureAwareComparer(CultureInfo.CurrentCulture, true);
}
}
- public static StringComparer Ordinal {
- get {
+ public static StringComparer Ordinal
+ {
+ get
+ {
Contract.Ensures(Contract.Result<StringComparer>() != null);
return _ordinal;
}
}
- public static StringComparer OrdinalIgnoreCase {
- get {
+ public static StringComparer OrdinalIgnoreCase
+ {
+ get
+ {
Contract.Ensures(Contract.Result<StringComparer>() != null);
return _ordinalIgnoreCase;
}
@@ -83,130 +97,152 @@ namespace System {
}
}
- public static StringComparer Create(CultureInfo culture, bool ignoreCase) {
- if( culture == null) {
+ 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) {
+ 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);
+ if (sa != null)
+ {
+ String sb = y as String;
+ if (sb != null)
+ {
+ return Compare(sa, sb);
}
}
IComparable ia = x as IComparable;
- if (ia != null) {
+ if (ia != null)
+ {
return ia.CompareTo(y);
}
- throw new ArgumentException(Environment.GetResourceString("Argument_ImplementIComparable"));
+ throw new ArgumentException(Environment.GetResourceString("Argument_ImplementIComparable"));
}
-
- public new bool Equals(Object x, Object y) {
+
+ 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) {
+ if (sa != null)
+ {
+ String sb = y as String;
+ if (sb != null)
+ {
return Equals(sa, sb);
}
}
- return x.Equals(y);
+ return x.Equals(y);
}
-
- public int GetHashCode(object obj) {
- if( obj == null) {
+
+ public int GetHashCode(object obj)
+ {
+ if (obj == null)
+ {
throw new ArgumentNullException(nameof(obj));
}
Contract.EndContractBlock();
string s = obj as string;
- if( s != null) {
+ if (s != null)
+ {
return GetHashCode(s);
}
- return obj.GetHashCode();
+ 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);
+ 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
+ , IWellKnownStringEqualityComparer
#endif
{
- private CompareInfo _compareInfo;
- private bool _ignoreCase;
+ private CompareInfo _compareInfo;
+ private bool _ignoreCase;
- internal CultureAwareComparer(CultureInfo culture, bool ignoreCase) {
- _compareInfo = culture.CompareInfo;
- _ignoreCase = ignoreCase;
+ internal CultureAwareComparer(CultureInfo culture, bool ignoreCase)
+ {
+ _compareInfo = culture.CompareInfo;
+ _ignoreCase = ignoreCase;
}
- public override int Compare(string x, string y) {
+ 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);
+ 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;
+
+ 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) {
+ 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) {
+ if (_ignoreCase)
+ {
options |= CompareOptions.IgnoreCase;
}
return _compareInfo.GetHashCodeOfString(obj, options);
- }
+ }
// Equals method for the comparer itself.
- public override bool Equals(Object obj){
+ public override bool Equals(Object obj)
+ {
CultureAwareComparer comparer = obj as CultureAwareComparer;
- if( comparer == null) {
+ if (comparer == null)
+ {
return false;
}
- return (this._ignoreCase == comparer._ignoreCase) && (this._compareInfo.Equals(comparer._compareInfo));
+ return (_ignoreCase == comparer._ignoreCase) && (_compareInfo.Equals(comparer._compareInfo));
}
- public override int GetHashCode() {
- int hashCode = _compareInfo.GetHashCode() ;
+ public override int GetHashCode()
+ {
+ int hashCode = _compareInfo.GetHashCode();
return _ignoreCase ? (~hashCode) : hashCode;
}
#if FEATURE_RANDOMIZED_STRING_HASHING
- IEqualityComparer IWellKnownStringEqualityComparer.GetEqualityComparerForSerialization() {
+ IEqualityComparer IWellKnownStringEqualityComparer.GetEqualityComparerForSerialization()
+ {
return this;
}
#endif
@@ -215,65 +251,77 @@ namespace System {
// Provide x more optimal implementation of ordinal comparison.
[Serializable]
- internal sealed class OrdinalComparer : StringComparer
-#if FEATURE_RANDOMIZED_STRING_HASHING
+ internal sealed class OrdinalComparer : StringComparer
+#if FEATURE_RANDOMIZED_STRING_HASHING
, IWellKnownStringEqualityComparer
#endif
{
- private bool _ignoreCase;
-
- internal OrdinalComparer(bool ignoreCase) {
- _ignoreCase = ignoreCase;
+ private bool _ignoreCase;
+
+ internal OrdinalComparer(bool ignoreCase)
+ {
+ _ignoreCase = ignoreCase;
}
- public override int Compare(string x, string y) {
+ 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) {
+
+ if (_ignoreCase)
+ {
return String.Compare(x, y, StringComparison.OrdinalIgnoreCase);
}
-
- return String.CompareOrdinal(x, y);
+
+ return String.CompareOrdinal(x, y);
}
-
- public override bool Equals(string x, string y) {
- if (Object.ReferenceEquals(x ,y)) return true;
+
+ 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) {
+ if (_ignoreCase)
+ {
+ if (x.Length != y.Length)
+ {
return false;
}
- return (String.Compare(x, y, StringComparison.OrdinalIgnoreCase) == 0);
+ return (String.Compare(x, y, StringComparison.OrdinalIgnoreCase) == 0);
}
return x.Equals(y);
- }
-
- public override int GetHashCode(string obj) {
- if( obj == null) {
+ }
+
+ public override int GetHashCode(string obj)
+ {
+ if (obj == null)
+ {
throw new ArgumentNullException(nameof(obj));
}
Contract.EndContractBlock();
- if( _ignoreCase) {
+ if (_ignoreCase)
+ {
return TextInfo.GetHashCodeOrdinalIgnoreCase(obj);
}
-
+
return obj.GetHashCode();
- }
+ }
// Equals method for the comparer itself.
- public override bool Equals(Object obj){
+ public override bool Equals(Object obj)
+ {
OrdinalComparer comparer = obj as OrdinalComparer;
- if( comparer == null) {
+ if (comparer == null)
+ {
return false;
}
- return (this._ignoreCase == comparer._ignoreCase);
+ return (_ignoreCase == comparer._ignoreCase);
}
- public override int GetHashCode() {
+ public override int GetHashCode()
+ {
string name = "OrdinalComparer";
int hashCode = name.GetHashCode();
return _ignoreCase ? (~hashCode) : hashCode;
@@ -281,18 +329,20 @@ namespace System {
#if FEATURE_RANDOMIZED_STRING_HASHING
- IEqualityComparer IWellKnownStringEqualityComparer.GetEqualityComparerForSerialization() {
+ 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 {
+ internal interface IWellKnownStringEqualityComparer
+ {
// Get an IEqaulityComparer that can be serailzied (e.g., it exists in older versions).
IEqualityComparer GetEqualityComparerForSerialization();
}
diff --git a/src/mscorlib/src/System/StringFreezingAttribute.cs b/src/mscorlib/src/System/StringFreezingAttribute.cs
index d488a88445..87fa165f52 100644
--- a/src/mscorlib/src/System/StringFreezingAttribute.cs
+++ b/src/mscorlib/src/System/StringFreezingAttribute.cs
@@ -13,8 +13,7 @@
namespace System.Runtime.CompilerServices
{
-
-[Serializable]
+ [Serializable]
[AttributeUsage(AttributeTargets.Assembly, Inherited = false)]
public sealed class StringFreezingAttribute : Attribute
{
diff --git a/src/mscorlib/src/System/StubHelpers.cs b/src/mscorlib/src/System/StubHelpers.cs
index b0763312ea..7497cbffbb 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);
@@ -549,7 +549,7 @@ 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"));
@@ -558,7 +558,7 @@ namespace System.StubHelpers {
// 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);
@@ -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,32 +975,32 @@ 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"));
@@ -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))
{
@@ -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,20 +1317,20 @@ 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"));
}
-
+
string typeName;
if (managedType != null)
{
@@ -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"));
}
-
+
string typeName = WindowsRuntimeMarshal.HStringToString(pNativeType->typeName);
if (String.IsNullOrEmpty(typeName))
{
@@ -1397,8 +1395,8 @@ namespace System.StubHelpers {
throw new ArgumentException(Environment.GetResourceString("Argument_Unexpected_TypeSource"));
}
}
-
- internal static unsafe void ClearNative(TypeNameNative *pNativeType)
+
+ internal static unsafe void ClearNative(TypeNameNative* pNativeType)
{
Debug.Assert(Environment.IsWinRTSupported);
@@ -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,7 +1610,7 @@ namespace System.StubHelpers {
//-------------------------------------------------------
// SafeHandle Helpers
//-------------------------------------------------------
-
+
// AddRefs the SH and returns the underlying unmanaged handle.
static internal IntPtr SafeHandleAddRef(SafeHandle pHandle, ref bool success)
{
@@ -1670,7 +1668,7 @@ namespace System.StubHelpers {
//-------------------------------------------------------
// Helper for the MDA RaceOnRCWCleanup
//-------------------------------------------------------
-
+
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static internal extern void StubRegisterRCW(object pThis);
@@ -1733,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)]
@@ -1748,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/Text/ASCIIEncoding.cs b/src/mscorlib/src/System/Text/ASCIIEncoding.cs
index 07b7f3e890..307e4899b7 100644
--- a/src/mscorlib/src/System/Text/ASCIIEncoding.cs
+++ b/src/mscorlib/src/System/Text/ASCIIEncoding.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.Serialization;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+
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.
@@ -55,7 +55,7 @@ namespace System.Text
// 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.
@@ -135,7 +135,7 @@ namespace System.Text
{
return EncodingForwarder.GetString(this, bytes, byteIndex, byteCount);
}
-
+
// End of overridden methods which use EncodingForwarder
// GetByteCount
@@ -184,9 +184,9 @@ namespace System.Text
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()));
+ // if (encoder.InternalHasFallbackBuffer && encoder.FallbackBuffer.Remaining > 0)
+ // throw new ArgumentException(Environment.GetResourceString("Argument_EncoderFallbackNotEmpty",
+ // this.EncodingName, encoder.Fallback.GetType()));
}
else
{
@@ -237,7 +237,6 @@ namespace System.Text
while ((ch = (fallbackBuffer == null) ? '\0' : fallbackBuffer.InternalGetNextChar()) != 0 ||
chars < charEnd)
{
-
// First unwind any fallback
if (ch == 0)
{
@@ -324,10 +323,10 @@ namespace System.Text
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()));
+ // if (encoder.m_throwOnOverflow && encoder.InternalHasFallbackBuffer &&
+ // encoder.FallbackBuffer.Remaining > 0)
+ // throw new ArgumentException(Environment.GetResourceString("Argument_EncoderFallbackNotEmpty",
+ // this.EncodingName, encoder.Fallback.GetType()));
}
else
{
@@ -384,7 +383,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);
@@ -484,7 +483,7 @@ namespace System.Text
}
Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0 ||
- (encoder != null && !encoder.m_throwOnOverflow ),
+ (encoder != null && !encoder.m_throwOnOverflow),
"[ASCIIEncoding.GetBytes]Expected Empty fallback buffer at end");
return (int)(bytes - byteStart);
@@ -627,7 +626,7 @@ namespace System.Text
// Slower way's going to need a fallback buffer
DecoderFallbackBuffer fallbackBuffer = null;
byte[] byteBuffer = new byte[1];
- char* charEnd = chars + charCount;
+ char* charEnd = chars + charCount;
// Not quite so fast loop
while (bytes < byteEnd)
@@ -695,8 +694,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),
+ Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
// Characters would be # of characters + 1 in case high surrogate is ? * max fallback
@@ -716,8 +715,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),
+ Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
// Just return length, SBCS stay the same length because they don't map to surrogate
diff --git a/src/mscorlib/src/System/Text/Decoder.cs b/src/mscorlib/src/System/Text/Decoder.cs
index a9fea82a39..e8b9128bd6 100644
--- a/src/mscorlib/src/System/Text/Decoder.cs
+++ b/src/mscorlib/src/System/Text/Decoder.cs
@@ -2,13 +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.Runtime.Serialization;
+using System.Text;
+using System;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+
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
@@ -23,17 +24,17 @@ namespace System.Text
[Serializable]
public abstract class Decoder
{
- internal DecoderFallback m_fallback = null;
+ internal DecoderFallback m_fallback = null;
[NonSerialized]
- internal DecoderFallbackBuffer m_fallbackBuffer = null;
+ internal DecoderFallbackBuffer m_fallbackBuffer = null;
internal void SerializeDecoder(SerializationInfo info)
{
info.AddValue("m_fallback", this.m_fallback);
}
- protected Decoder( )
+ protected Decoder()
{
// We don't call default reset because default reset probably isn't good if we aren't initialized.
}
@@ -193,7 +194,7 @@ namespace System.Text
Environment.GetResourceString("ArgumentNull_Array"));
if (byteCount < 0 || charCount < 0)
- throw new ArgumentOutOfRangeException((byteCount<0 ? nameof(byteCount) : nameof(charCount)),
+ throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
@@ -251,11 +252,11 @@ namespace System.Text
Environment.GetResourceString("ArgumentNull_Array"));
if (byteIndex < 0 || byteCount < 0)
- throw new ArgumentOutOfRangeException((byteIndex<0 ? nameof(byteIndex) : nameof(byteCount)),
+ 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)),
+ throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (bytes.Length - byteIndex < byteCount)
@@ -308,7 +309,7 @@ namespace System.Text
Environment.GetResourceString("ArgumentNull_Array"));
if (byteCount < 0 || charCount < 0)
- throw new ArgumentOutOfRangeException((byteCount<0 ? nameof(byteCount) : nameof(charCount)),
+ throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
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..b709dcde57 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,7 +87,7 @@ 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(" ...");
@@ -95,17 +95,16 @@ namespace System.Text
// Known index
throw new DecoderFallbackException(
Environment.GetResourceString("Argument_InvalidCodePageBytesIndex",
- strBytes, index), bytesUnknown, index);
+ 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"))
@@ -148,7 +147,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..e7b57bdff4 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");
@@ -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");
@@ -266,6 +267,5 @@ namespace System.Text
Environment.GetResourceString("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..c2f5e47e1d 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,19 +25,19 @@ 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,
+ System.Globalization.CultureInfo.CurrentCulture,
Environment.GetResourceString("NotSupported_TypeCannotDeserialized"), this.GetType()));
}
@@ -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();
@@ -83,7 +84,7 @@ namespace System.Text
Environment.GetResourceString("ArgumentNull_Array"));
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index<0 ? nameof(index) : nameof(count)),
+ throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (bytes.Length - index < count)
@@ -136,10 +137,10 @@ namespace System.Text
Environment.GetResourceString("ArgumentNull_Array"));
if (byteIndex < 0 || byteCount < 0)
- throw new ArgumentOutOfRangeException((byteIndex<0 ? nameof(byteIndex) : nameof(byteCount)),
+ throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- if ( bytes.Length - byteIndex < byteCount)
+ if (bytes.Length - byteIndex < byteCount)
throw new ArgumentOutOfRangeException(nameof(bytes),
Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
@@ -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,
@@ -174,7 +175,7 @@ namespace System.Text
Environment.GetResourceString("ArgumentNull_Array"));
if (byteCount < 0 || charCount < 0)
- throw new ArgumentOutOfRangeException((byteCount<0 ? nameof(byteCount) : nameof(charCount)),
+ throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
@@ -198,11 +199,11 @@ namespace System.Text
Environment.GetResourceString("ArgumentNull_Array"));
if (byteIndex < 0 || byteCount < 0)
- throw new ArgumentOutOfRangeException((byteIndex<0 ? nameof(byteIndex) : nameof(byteCount)),
+ 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)),
+ throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (bytes.Length - byteIndex < byteCount)
@@ -244,7 +245,7 @@ namespace System.Text
Environment.GetResourceString("ArgumentNull_Array"));
if (byteCount < 0 || charCount < 0)
- throw new ArgumentOutOfRangeException((byteCount<0 ? nameof(byteCount) : nameof(charCount)),
+ throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
diff --git a/src/mscorlib/src/System/Text/DecoderReplacementFallback.cs b/src/mscorlib/src/System/Text/DecoderReplacementFallback.cs
index 77c856046d..8147da5583 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))
@@ -66,10 +66,10 @@ namespace System.Text
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
index f766f98142..9ec8231b50 100644
--- a/src/mscorlib/src/System/Text/Encoder.cs
+++ b/src/mscorlib/src/System/Text/Encoder.cs
@@ -2,13 +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.Runtime.Serialization;
+using System.Text;
+using System;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+
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
@@ -23,10 +24,10 @@ namespace System.Text
[Serializable]
public abstract class Encoder
{
- internal EncoderFallback m_fallback = null;
+ internal EncoderFallback m_fallback = null;
[NonSerialized]
- internal EncoderFallbackBuffer m_fallbackBuffer = null;
+ internal EncoderFallbackBuffer m_fallbackBuffer = null;
internal void SerializeEncoder(SerializationInfo info)
{
@@ -98,7 +99,7 @@ namespace System.Text
// 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 = {};
+ char[] charTemp = { };
byte[] byteTemp = new byte[GetByteCount(charTemp, 0, 0, true)];
GetBytes(charTemp, 0, 0, byteTemp, 0, true);
if (m_fallbackBuffer != null)
@@ -187,7 +188,7 @@ namespace System.Text
Environment.GetResourceString("ArgumentNull_Array"));
if (charCount < 0 || byteCount < 0)
- throw new ArgumentOutOfRangeException((charCount<0 ? nameof(charCount) : nameof(byteCount)),
+ throw new ArgumentOutOfRangeException((charCount < 0 ? nameof(charCount) : nameof(byteCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
@@ -244,11 +245,11 @@ namespace System.Text
Environment.GetResourceString("ArgumentNull_Array"));
if (charIndex < 0 || charCount < 0)
- throw new ArgumentOutOfRangeException((charIndex<0 ? nameof(charIndex) : nameof(charCount)),
+ 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)),
+ throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (chars.Length - charIndex < charCount)
@@ -300,10 +301,10 @@ namespace System.Text
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)),
+ if (charCount < 0 || byteCount < 0)
+ throw new ArgumentOutOfRangeException((charCount < 0 ? nameof(charCount) : nameof(byteCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- Contract.EndContractBlock();
+ Contract.EndContractBlock();
// Get ready to do it
charsUsed = charCount;
diff --git a/src/mscorlib/src/System/Text/EncoderBestFitFallback.cs b/src/mscorlib/src/System/Text/EncoderBestFitFallback.cs
index 9be095bbd8..153155da69 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
{
// 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)
@@ -146,7 +147,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..b64e19e598 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,7 +49,7 @@ namespace System.Text
public sealed class EncoderExceptionFallbackBuffer : EncoderFallbackBuffer
{
- public EncoderExceptionFallbackBuffer(){}
+ public EncoderExceptionFallbackBuffer() { }
public override bool Fallback(char charUnknown, int index)
{
// Fall back our char
@@ -106,10 +106,10 @@ 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"))
@@ -197,7 +197,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..2d1ee52c59 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?
@@ -227,6 +227,5 @@ namespace System.Text
Environment.GetResourceString("Argument_RecursiveFallback",
charRecursive), "chars");
}
-
}
}
diff --git a/src/mscorlib/src/System/Text/EncoderNLS.cs b/src/mscorlib/src/System/Text/EncoderNLS.cs
index 95901e01f4..2ba909701c 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,22 +25,22 @@ 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,
+ System.Globalization.CultureInfo.CurrentCulture,
Environment.GetResourceString("NotSupported_TypeCannotDeserialized"), this.GetType()));
}
@@ -52,7 +53,7 @@ namespace System.Text
info.SetType(typeof(Encoding.DefaultEncoder));
}
-#endregion Serialization
+ #endregion Serialization
internal EncoderNLS(Encoding encoding)
{
@@ -83,7 +84,7 @@ namespace System.Text
Environment.GetResourceString("ArgumentNull_Array"));
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index<0 ? nameof(index) : nameof(count)),
+ throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (chars.Length - index < count)
@@ -130,7 +131,7 @@ namespace System.Text
Environment.GetResourceString("ArgumentNull_Array"));
if (charIndex < 0 || charCount < 0)
- throw new ArgumentOutOfRangeException((charIndex<0 ? nameof(charIndex) : nameof(charCount)),
+ throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (chars.Length - charIndex < charCount)
@@ -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)
@@ -166,7 +167,7 @@ namespace System.Text
Environment.GetResourceString("ArgumentNull_Array"));
if (byteCount < 0 || charCount < 0)
- throw new ArgumentOutOfRangeException((byteCount<0 ? nameof(byteCount) : nameof(charCount)),
+ throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
@@ -187,11 +188,11 @@ namespace System.Text
Environment.GetResourceString("ArgumentNull_Array"));
if (charIndex < 0 || charCount < 0)
- throw new ArgumentOutOfRangeException((charIndex<0 ? nameof(charIndex) : nameof(charCount)),
+ 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)),
+ throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (chars.Length - charIndex < charCount)
@@ -232,8 +233,8 @@ namespace System.Text
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"));
+ throw new ArgumentOutOfRangeException((charCount < 0 ? nameof(charCount) : nameof(byteCount)),
+ Environment.GetResourceString("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..0b8abb33a5 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))
@@ -68,10 +68,10 @@ namespace System.Text
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;
@@ -176,7 +176,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..09ec958f49 100644
--- a/src/mscorlib/src/System/Text/Encoding.cs
+++ b/src/mscorlib/src/System/Text/Encoding.cs
@@ -91,73 +91,73 @@ namespace System.Text
// 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 +228,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 +246,7 @@ namespace System.Text
}
// dataItem is always recalculated from the code page #
- dataItem = null;
+ dataItem = null;
}
[OnDeserializing]
@@ -274,7 +274,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 +282,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 +291,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 +304,7 @@ namespace System.Text
this.m_deserializedFromEverett = true;
// May as well be read only
- this.m_isReadOnly = true;
+ m_isReadOnly = true;
SetDefaultFallbacks();
}
}
@@ -313,11 +313,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 +332,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 +341,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 +357,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"));
}
- if (bytes == null) {
+ if (bytes == null)
+ {
throw new ArgumentNullException(nameof(bytes),
Environment.GetResourceString("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,7 +394,8 @@ 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));
@@ -501,10 +506,13 @@ namespace System.Text
return EmptyArray<Byte>.Value;
}
- 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));
}
@@ -518,7 +526,8 @@ namespace System.Text
{
get
{
- if (dataItem==null) {
+ if (dataItem == null)
+ {
GetDataItem();
}
return (dataItem.BodyName);
@@ -542,7 +551,8 @@ namespace System.Text
{
get
{
- if (dataItem==null) {
+ if (dataItem == null)
+ {
GetDataItem();
}
return (dataItem.HeaderName);
@@ -556,7 +566,8 @@ namespace System.Text
{
get
{
- if (dataItem==null) {
+ if (dataItem == null)
+ {
GetDataItem();
}
return (dataItem.WebName);
@@ -569,7 +580,8 @@ namespace System.Text
{
get
{
- if (dataItem==null) {
+ if (dataItem == null)
+ {
GetDataItem();
}
return (dataItem.UIFamilyCodePage);
@@ -579,9 +591,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 +605,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 +619,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 +635,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);
@@ -731,7 +755,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,7 +769,7 @@ namespace System.Text
public int GetByteCount(string s, int index, int count)
{
if (s == null)
- throw new ArgumentNullException(nameof(s),
+ throw new ArgumentNullException(nameof(s),
Environment.GetResourceString("ArgumentNull_String"));
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index),
@@ -944,7 +967,7 @@ namespace System.Text
Environment.GetResourceString("ArgumentNull_Array"));
if (charCount < 0 || byteCount < 0)
- throw new ArgumentOutOfRangeException((charCount<0 ? nameof(charCount) : nameof(byteCount)),
+ throw new ArgumentOutOfRangeException((charCount < 0 ? nameof(charCount) : nameof(byteCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
@@ -1098,7 +1121,7 @@ namespace System.Text
Environment.GetResourceString("ArgumentNull_Array"));
if (byteCount < 0 || charCount < 0)
- throw new ArgumentOutOfRangeException((byteCount<0 ? nameof(byteCount) : nameof(charCount)),
+ throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)),
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
@@ -1311,7 +1334,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 +1352,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,7 +1363,8 @@ namespace System.Text
}
- public override int GetHashCode() {
+ public override int GetHashCode()
+ {
return m_codePage + this.EncoderFallback.GetHashCode() + this.DecoderFallback.GetHashCode();
}
@@ -1421,16 +1446,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 +1478,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 +1491,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
@@ -1537,21 +1562,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 +1608,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 +1679,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 +1696,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 +1723,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 +1736,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,36 +1814,36 @@ 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)
@@ -1867,8 +1892,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 +1914,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 +1923,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
index 50ccbd9333..1198045689 100644
--- a/src/mscorlib/src/System/Text/EncodingForwarder.cs
+++ b/src/mscorlib/src/System/Text/EncodingForwarder.cs
@@ -129,7 +129,7 @@ namespace System.Text
// 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);
@@ -168,7 +168,7 @@ namespace System.Text
// 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])
{
@@ -308,7 +308,7 @@ namespace System.Text
throw new ArgumentOutOfRangeException(nameof(bytes), Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
}
Contract.EndContractBlock();
-
+
// Avoid problems with empty input buffer
if (count == 0)
return string.Empty;
diff --git a/src/mscorlib/src/System/Text/EncodingInfo.cs b/src/mscorlib/src/System/Text/EncodingInfo.cs
index 26ad3344c6..679abff288 100644
--- a/src/mscorlib/src/System/Text/EncodingInfo.cs
+++ b/src/mscorlib/src/System/Text/EncodingInfo.cs
@@ -2,24 +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;
+using System.Text;
+
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
+ private int iCodePage; // Code Page #
+ private String strEncodingName; // Short name (web name)
+ private String strDisplayName; // Full localized name
internal EncodingInfo(int codePage, string name, string displayName)
{
- this.iCodePage = codePage;
- this.strEncodingName = name;
- this.strDisplayName = displayName;
+ iCodePage = codePage;
+ strEncodingName = name;
+ strDisplayName = displayName;
}
@@ -52,7 +51,7 @@ namespace System.Text
public Encoding GetEncoding()
{
- return Encoding.GetEncoding(this.iCodePage);
+ return Encoding.GetEncoding(iCodePage);
}
public override bool Equals(Object value)
@@ -64,11 +63,10 @@ namespace System.Text
}
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
index cb6ed8a52c..ea2bd64b2e 100644
--- a/src/mscorlib/src/System/Text/EncodingNLS.cs
+++ b/src/mscorlib/src/System/Text/EncodingNLS.cs
@@ -4,7 +4,6 @@
namespace System.Text
{
-
using System;
using System.Diagnostics.Contracts;
using System.Collections;
@@ -12,12 +11,12 @@ namespace System.Text
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)
{
}
@@ -43,7 +42,7 @@ namespace System.Text
{
return EncodingForwarder.GetByteCount(this, chars, index, count);
}
-
+
public override int GetByteCount(String s)
{
return EncodingForwarder.GetByteCount(this, s);
@@ -59,7 +58,7 @@ namespace System.Text
{
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
@@ -68,7 +67,7 @@ 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.
-
+
public override int GetBytes(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
@@ -78,11 +77,11 @@ namespace System.Text
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);
@@ -91,7 +90,7 @@ namespace System.Text
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)
@@ -103,10 +102,10 @@ namespace System.Text
{
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);
diff --git a/src/mscorlib/src/System/Text/EncodingProvider.cs b/src/mscorlib/src/System/Text/EncodingProvider.cs
index 734d1ac761..bf29670893 100644
--- a/src/mscorlib/src/System/Text/EncodingProvider.cs
+++ b/src/mscorlib/src/System/Text/EncodingProvider.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.Collections;
+using System.Collections.Generic;
+
namespace System.Text
{
- using System;
- using System.Collections;
- using System.Collections.Generic;
-
public abstract class EncodingProvider
{
public EncodingProvider() { }
diff --git a/src/mscorlib/src/System/Text/Latin1Encoding.cs b/src/mscorlib/src/System/Text/Latin1Encoding.cs
index 26009bf6c0..569d045ae1 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);
@@ -216,7 +215,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 +261,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);
}
@@ -335,7 +334,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 +356,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 +440,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),
+ Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
// Characters would be # of characters + 1 in case high surrogate is ? * max fallback
@@ -461,8 +460,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),
+ Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
// Just return length, SBCS stay the same length because they don't map to surrogate
diff --git a/src/mscorlib/src/System/Text/Normalization.Windows.cs b/src/mscorlib/src/System/Text/Normalization.Windows.cs
index 3bcba08934..428796720a 100644
--- a/src/mscorlib/src/System/Text/Normalization.Windows.cs
+++ b/src/mscorlib/src/System/Text/Normalization.Windows.cs
@@ -2,18 +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.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
@@ -149,12 +149,12 @@ namespace System.Text
int iError = ERROR_SUCCESS;
bool result = nativeNormalizationIsNormalizedString(
- normForm,
- ref iError,
- strInput,
+ normForm,
+ ref iError,
+ strInput,
strInput.Length);
- switch(iError)
+ switch (iError)
{
// Success doesn't need to do anything
case ERROR_SUCCESS:
@@ -164,7 +164,7 @@ namespace System.Text
case ERROR_INVALID_PARAMETER:
case ERROR_NO_UNICODE_TRANSLATION:
throw new ArgumentException(
- Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex" ),
+ Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex"),
nameof(strInput));
case ERROR_NOT_ENOUGH_MEMORY:
throw new OutOfMemoryException(
@@ -193,7 +193,7 @@ namespace System.Text
{
if (iError == ERROR_INVALID_PARAMETER)
throw new ArgumentException(
- Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex" ),
+ Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex"),
nameof(strInput));
// We shouldn't really be able to get here..., guessing length is
@@ -220,18 +220,18 @@ namespace System.Text
cBuffer = new char[iLength];
iLength = nativeNormalizationNormalizeString(
- normForm,
+ normForm,
ref iError,
- strInput,
- strInput.Length,
- cBuffer,
+ strInput,
+ strInput.Length,
+ cBuffer,
cBuffer.Length);
-
+
if (iError == ERROR_SUCCESS)
break;
// Could have an error (actually it'd be quite hard to have an error here)
- switch(iError)
+ switch (iError)
{
// Do appropriate stuff for the individual errors:
case ERROR_INSUFFICIENT_BUFFER:
@@ -242,7 +242,7 @@ namespace System.Text
case ERROR_NO_UNICODE_TRANSLATION:
// Illegal code point or order found. Ie: FFFE or D800 D800, etc.
throw new ArgumentException(
- Environment.GetResourceString("Argument_InvalidCharSequence", iLength ),
+ Environment.GetResourceString("Argument_InvalidCharSequence", iLength),
nameof(strInput));
case ERROR_NOT_ENOUGH_MEMORY:
throw new OutOfMemoryException(
diff --git a/src/mscorlib/src/System/Text/Normalization.cs b/src/mscorlib/src/System/Text/Normalization.cs
index c81149d59a..dc8bc2af71 100644
--- a/src/mscorlib/src/System/Text/Normalization.cs
+++ b/src/mscorlib/src/System/Text/Normalization.cs
@@ -7,23 +7,23 @@ namespace System.Text
// This is the enumeration for Normalization Forms
public enum NormalizationForm
{
- FormC = 1,
- FormD = 2,
- FormKC = 5,
- FormKD = 6
+ FormC = 1,
+ FormD = 2,
+ FormKC = 5,
+ FormKD = 6
}
internal enum ExtendedNormalizationForms
{
- FormC = 1,
- FormD = 2,
- FormKC = 5,
- FormKD = 6,
+ FormC = 1,
+ FormD = 2,
+ FormKC = 5,
+ FormKD = 6,
FormIdna = 0xd,
- FormCDisallowUnassigned = 0x101,
- FormDDisallowUnassigned = 0x102,
- FormKCDisallowUnassigned = 0x105,
- FormKDDisallowUnassigned = 0x106,
- FormIdnaDisallowUnassigned = 0x10d
+ FormCDisallowUnassigned = 0x101,
+ FormDDisallowUnassigned = 0x102,
+ FormKCDisallowUnassigned = 0x105,
+ FormKDDisallowUnassigned = 0x106,
+ FormIdnaDisallowUnassigned = 0x10d
}
}
diff --git a/src/mscorlib/src/System/Text/StringBuilder.cs b/src/mscorlib/src/System/Text/StringBuilder.cs
index 72247c333e..0cb0db04e1 100644
--- a/src/mscorlib/src/System/Text/StringBuilder.cs
+++ b/src/mscorlib/src/System/Text/StringBuilder.cs
@@ -10,20 +10,22 @@
** 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;
+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;
+
+namespace System.Text
+{
// 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
@@ -102,7 +104,8 @@ namespace System.Text {
// String.NullString).
//
public StringBuilder(String value)
- : this(value, DefaultCapacity) {
+ : this(value, DefaultCapacity)
+ {
}
// Creates a new string builder from the specified string with the specified
@@ -112,34 +115,42 @@ namespace System.Text {
// 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) {
+ : 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) {
+ 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) {
+ if (length < 0)
+ {
throw new ArgumentOutOfRangeException(nameof(length),
Environment.GetResourceString("ArgumentOutOfRange_MustBeNonNegNum", nameof(length)));
}
- if (startIndex<0) {
+ if (startIndex < 0)
+ {
throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
}
Contract.EndContractBlock();
- if (value == null) {
+ if (value == null)
+ {
value = String.Empty;
}
- if (startIndex > value.Length - length) {
+ if (startIndex > value.Length - length)
+ {
throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_IndexLength"));
}
m_MaxCapacity = Int32.MaxValue;
- if (capacity == 0) {
+ if (capacity == 0)
+ {
capacity = DefaultCapacity;
}
if (capacity < length)
@@ -148,7 +159,8 @@ namespace System.Text {
m_ChunkChars = new char[capacity];
m_ChunkLength = length;
- unsafe {
+ unsafe
+ {
fixed (char* sourcePtr = value)
ThreadSafeCopy(sourcePtr + startIndex, m_ChunkChars, 0, length);
}
@@ -156,20 +168,25 @@ namespace System.Text {
// 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) {
+ public StringBuilder(int capacity, int maxCapacity)
+ {
+ if (capacity > maxCapacity)
+ {
throw new ArgumentOutOfRangeException(nameof(capacity), Environment.GetResourceString("ArgumentOutOfRange_Capacity"));
}
- if (maxCapacity<1) {
+ if (maxCapacity < 1)
+ {
throw new ArgumentOutOfRangeException(nameof(maxCapacity), Environment.GetResourceString("ArgumentOutOfRange_SmallMaxCapacity"));
}
- if (capacity<0) {
+ if (capacity < 0)
+ {
throw new ArgumentOutOfRangeException(nameof(capacity),
Environment.GetResourceString("ArgumentOutOfRange_MustBePositive", nameof(capacity)));
}
Contract.EndContractBlock();
- if (capacity == 0) {
+ if (capacity == 0)
+ {
capacity = Math.Min(DefaultCapacity, maxCapacity);
}
@@ -177,7 +194,8 @@ namespace System.Text {
m_ChunkChars = new char[capacity];
}
- private StringBuilder(SerializationInfo info, StreamingContext context) {
+ private StringBuilder(SerializationInfo info, StreamingContext context)
+ {
if (info == null)
throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
@@ -189,8 +207,10 @@ namespace System.Text {
// Get the data
SerializationInfoEnumerator enumerator = info.GetEnumerator();
- while (enumerator.MoveNext()) {
- switch (enumerator.Name) {
+ while (enumerator.MoveNext())
+ {
+ switch (enumerator.Name)
+ {
case MaxCapacityField:
persistedMaxCapacity = info.GetInt32(MaxCapacityField);
break;
@@ -205,28 +225,33 @@ namespace System.Text {
// Ignore other fields for forward compatibility.
break;
}
-
}
// Check values and set defaults
- if (persistedString == null) {
+ if (persistedString == null)
+ {
persistedString = String.Empty;
}
- if (persistedMaxCapacity < 1 || persistedString.Length > persistedMaxCapacity) {
+ if (persistedMaxCapacity < 1 || persistedString.Length > persistedMaxCapacity)
+ {
throw new SerializationException(Environment.GetResourceString("Serialization_StringBuilderMaxCapacity"));
}
- if (!capacityPresent) {
+ 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) {
+ if (persistedCapacity < persistedString.Length)
+ {
persistedCapacity = persistedString.Length;
}
- if (persistedCapacity > persistedMaxCapacity) {
+ if (persistedCapacity > persistedMaxCapacity)
+ {
persistedCapacity = persistedMaxCapacity;
}
}
- if (persistedCapacity < 0 || persistedCapacity < persistedString.Length || persistedCapacity > persistedMaxCapacity) {
+ if (persistedCapacity < 0 || persistedCapacity < persistedString.Length || persistedCapacity > persistedMaxCapacity)
+ {
throw new SerializationException(Environment.GetResourceString("Serialization_StringBuilderCapacity"));
}
@@ -241,7 +266,8 @@ namespace System.Text {
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
- if (info==null) {
+ if (info == null)
+ {
throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
@@ -255,11 +281,12 @@ namespace System.Text {
}
[System.Diagnostics.Conditional("_DEBUG")]
- private void VerifyClassInvariant() {
+ private void VerifyClassInvariant()
+ {
BCLDebug.Correctness((uint)(m_ChunkOffset + m_ChunkChars.Length) >= m_ChunkOffset, "Integer Overflow");
StringBuilder currentBlock = this;
int maxCapacity = this.m_MaxCapacity;
- for (; ; )
+ for (;;)
{
// All blocks have copy of the maxCapacity.
Debug.Assert(currentBlock.m_MaxCapacity == maxCapacity, "Bad maxCapacity");
@@ -281,21 +308,27 @@ namespace System.Text {
}
}
- public int Capacity {
+ public int Capacity
+ {
get { return m_ChunkChars.Length + m_ChunkOffset; }
- set {
- if (value < 0) {
+ set
+ {
+ if (value < 0)
+ {
throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_NegativeCapacity"));
}
- if (value > MaxCapacity) {
+ if (value > MaxCapacity)
+ {
throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_Capacity"));
}
- if (value < Length) {
+ if (value < Length)
+ {
throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity"));
}
Contract.EndContractBlock();
- if (Capacity != value) {
+ if (Capacity != value)
+ {
int newLen = value - m_ChunkOffset;
char[] newArray = new char[newLen];
Array.Copy(m_ChunkChars, newArray, m_ChunkLength);
@@ -304,7 +337,8 @@ namespace System.Text {
}
}
- public int MaxCapacity {
+ public int MaxCapacity
+ {
get { return m_MaxCapacity; }
}
@@ -313,8 +347,10 @@ namespace System.Text {
// 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) {
+ public int EnsureCapacity(int capacity)
+ {
+ if (capacity < 0)
+ {
throw new ArgumentOutOfRangeException(nameof(capacity), Environment.GetResourceString("ArgumentOutOfRange_NegativeCapacity"));
}
Contract.EndContractBlock();
@@ -324,17 +360,19 @@ namespace System.Text {
return Capacity;
}
- public override String ToString() {
+ 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 {
+ unsafe
+ {
fixed (char* destinationPtr = ret)
{
do
@@ -345,7 +383,7 @@ namespace System.Text {
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)
{
@@ -367,7 +405,8 @@ namespace System.Text {
// Converts a substring of this string builder to a String.
- public String ToString(int startIndex, int length) {
+ public String ToString(int startIndex, int length)
+ {
Contract.Ensures(Contract.Result<String>() != null);
int currentLength = this.Length;
@@ -395,7 +434,8 @@ namespace System.Text {
string ret = string.FastAllocateString(length);
int curDestIndex = length;
- unsafe {
+ unsafe
+ {
fixed (char* destinationPtr = ret)
{
while (curDestIndex > 0)
@@ -405,7 +445,7 @@ namespace System.Text {
{
if (chunkEndIndex > chunk.m_ChunkLength)
chunkEndIndex = chunk.m_ChunkLength;
-
+
int countLeft = curDestIndex;
int chunkCount = countLeft;
int chunkStartIndex = chunkEndIndex - countLeft;
@@ -415,12 +455,12 @@ namespace System.Text {
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)
{
@@ -442,7 +482,8 @@ namespace System.Text {
}
// Convenience method for sb.Length=0;
- public StringBuilder Clear() {
+ public StringBuilder Clear()
+ {
this.Length = 0;
return this;
}
@@ -451,18 +492,23 @@ namespace System.Text {
// 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 {
+ public int Length
+ {
+ get
+ {
Contract.Ensures(Contract.Result<int>() >= 0);
return m_ChunkOffset + m_ChunkLength;
}
- set {
+ set
+ {
//If the new length is less than 0 or greater than our Maximum capacity, bail.
- if (value<0) {
+ if (value < 0)
+ {
throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_NegativeLength"));
}
- if (value>MaxCapacity) {
+ if (value > MaxCapacity)
+ {
throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity"));
}
Contract.EndContractBlock();
@@ -497,9 +543,9 @@ namespace System.Text {
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_ChunkPrevious = chunk.m_ChunkPrevious;
m_ChunkOffset = chunk.m_ChunkOffset;
}
m_ChunkLength = value - chunk.m_ChunkOffset;
@@ -510,10 +556,12 @@ namespace System.Text {
}
[System.Runtime.CompilerServices.IndexerName("Chars")]
- public char this[int index] {
- get {
+ public char this[int index]
+ {
+ get
+ {
StringBuilder chunk = this;
- for (; ; )
+ for (;;)
{
int indexInBlock = index - chunk.m_ChunkOffset;
if (indexInBlock >= 0)
@@ -527,9 +575,10 @@ namespace System.Text {
throw new IndexOutOfRangeException();
}
}
- set {
+ set
+ {
StringBuilder chunk = this;
- for (; ; )
+ for (;;)
{
int indexInBlock = index - chunk.m_ChunkOffset;
if (indexInBlock >= 0)
@@ -547,21 +596,25 @@ namespace System.Text {
}
// 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) {
+ 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) {
+ 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) {
+ if (newLength > m_MaxCapacity || newLength < repeatCount)
+ {
throw new ArgumentOutOfRangeException(nameof(repeatCount), Environment.GetResourceString("ArgumentOutOfRange_LengthGreaterThanCapacity"));
}
@@ -587,27 +640,34 @@ namespace System.Text {
}
// 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) {
+ public StringBuilder Append(char[] value, int startIndex, int charCount)
+ {
+ if (startIndex < 0)
+ {
throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
}
- if (charCount<0) {
+ 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) {
+ if (value == null)
+ {
+ if (startIndex == 0 && charCount == 0)
+ {
return this;
}
throw new ArgumentNullException(nameof(value));
}
- if (charCount > value.Length - startIndex) {
+ if (charCount > value.Length - startIndex)
+ {
throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
- if (charCount==0) {
+ if (charCount == 0)
+ {
return this;
}
unsafe
@@ -623,10 +683,12 @@ namespace System.Text {
// Appends a copy of this string at the end of this string builder.
- public StringBuilder Append(String value) {
+ public StringBuilder Append(String value)
+ {
Contract.Ensures(Contract.Result<StringBuilder>() != null);
- if (value != null) {
+ if (value != null)
+ {
// This is a hand specialization of the 'AppendHelper' code below.
// We could have just called AppendHelper.
char[] chunkChars = m_ChunkChars;
@@ -644,7 +706,8 @@ namespace System.Text {
}
else
{
- unsafe {
+ unsafe
+ {
fixed (char* valuePtr = value)
fixed (char* destPtr = &chunkChars[chunkLength])
string.wstrcpy(destPtr, valuePtr, valueLen);
@@ -661,8 +724,10 @@ namespace System.Text {
// 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 {
+ private void AppendHelper(string value)
+ {
+ unsafe
+ {
fixed (char* valueChars = value)
Append(valueChars, value.Length);
}
@@ -676,30 +741,37 @@ namespace System.Text {
// 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) {
+ public StringBuilder Append(String value, int startIndex, int count)
+ {
+ if (startIndex < 0)
+ {
throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
- if (count < 0) {
+ 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) {
+ if (value == null)
+ {
+ if (startIndex == 0 && count == 0)
+ {
return this;
}
throw new ArgumentNullException(nameof(value));
}
- if (count == 0) {
+ if (count == 0)
+ {
return this;
}
- if (startIndex > value.Length - count) {
+ if (startIndex > value.Length - count)
+ {
throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
@@ -714,40 +786,49 @@ namespace System.Text {
}
}
- public StringBuilder AppendLine() {
+ public StringBuilder AppendLine()
+ {
Contract.Ensures(Contract.Result<StringBuilder>() != null);
return Append(Environment.NewLine);
}
- public StringBuilder AppendLine(string value) {
+ 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) {
+ public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count)
+ {
+ if (destination == null)
+ {
throw new ArgumentNullException(nameof(destination));
}
- if (count < 0) {
+ if (count < 0)
+ {
throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("Arg_NegativeArgCount"));
}
- if (destinationIndex < 0) {
+ if (destinationIndex < 0)
+ {
throw new ArgumentOutOfRangeException(nameof(destinationIndex),
Environment.GetResourceString("ArgumentOutOfRange_MustBeNonNegNum", nameof(destinationIndex)));
}
- if (destinationIndex > destination.Length - count) {
+ if (destinationIndex > destination.Length - count)
+ {
throw new ArgumentException(Environment.GetResourceString("ArgumentOutOfRange_OffsetOut"));
}
- if ((uint)sourceIndex > (uint)Length) {
+ if ((uint)sourceIndex > (uint)Length)
+ {
throw new ArgumentOutOfRangeException(nameof(sourceIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
- if (sourceIndex > Length - count) {
+ if (sourceIndex > Length - count)
+ {
throw new ArgumentException(Environment.GetResourceString("Arg_LongerThanSrcString"));
}
Contract.EndContractBlock();
@@ -788,8 +869,10 @@ namespace System.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) {
+ 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);
@@ -797,28 +880,33 @@ namespace System.Text {
//Range check the index.
int currentLength = Length;
- if ((uint)index > (uint)currentLength) {
+ 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) {
+ 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) {
+ 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) {
+ 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);
@@ -834,22 +922,27 @@ namespace System.Text {
// 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) {
+ public StringBuilder Remove(int startIndex, int length)
+ {
+ if (length < 0)
+ {
throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_NegativeLength"));
}
- if (startIndex<0) {
+ if (startIndex < 0)
+ {
throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
}
- if (length > Length - 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) {
+ if (Length == length && startIndex == 0)
+ {
// Optimization. If we are deleting everything
Length = 0;
return this;
@@ -874,7 +967,8 @@ namespace System.Text {
==============================================================================*/
// Appends a boolean to the end of this string builder.
// The capacity is adjusted as needed.
- public StringBuilder Append(bool value) {
+ public StringBuilder Append(bool value)
+ {
Contract.Ensures(Contract.Result<StringBuilder>() != null);
return Append(value.ToString());
}
@@ -882,20 +976,23 @@ namespace System.Text {
// Appends an sbyte to this string builder.
// The capacity is adjusted as needed.
[CLSCompliant(false)]
- public StringBuilder Append(sbyte value) {
+ 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) {
+ 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) {
+ public StringBuilder Append(char value)
+ {
Contract.Ensures(Contract.Result<StringBuilder>() != null);
if (m_ChunkLength < m_ChunkChars.Length)
@@ -907,40 +1004,46 @@ namespace System.Text {
// Appends a short to this string builder.
// The capacity is adjusted as needed.
- public StringBuilder Append(short value) {
+ 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) {
+ 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) {
+ 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) {
+ 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) {
+ public StringBuilder Append(double value)
+ {
Contract.Ensures(Contract.Result<StringBuilder>() != null);
return Append(value.ToString(CultureInfo.CurrentCulture));
}
- public StringBuilder Append(decimal value) {
+ public StringBuilder Append(decimal value)
+ {
Contract.Ensures(Contract.Result<StringBuilder>() != null);
return Append(value.ToString(CultureInfo.CurrentCulture));
}
@@ -948,7 +1051,8 @@ namespace System.Text {
// Appends an ushort to this string builder.
// The capacity is adjusted as needed.
[CLSCompliant(false)]
- public StringBuilder Append(ushort value) {
+ public StringBuilder Append(ushort value)
+ {
Contract.Ensures(Contract.Result<StringBuilder>() != null);
return Append(value.ToString(CultureInfo.CurrentCulture));
}
@@ -956,7 +1060,8 @@ namespace System.Text {
// Appends an uint to this string builder.
// The capacity is adjusted as needed.
[CLSCompliant(false)]
- public StringBuilder Append(uint value) {
+ public StringBuilder Append(uint value)
+ {
Contract.Ensures(Contract.Result<StringBuilder>() != null);
return Append(value.ToString(CultureInfo.CurrentCulture));
}
@@ -964,17 +1069,20 @@ namespace System.Text {
// Appends an unsigned long to this string builder.
// The capacity is adjusted as needed.
[CLSCompliant(false)]
- public StringBuilder Append(ulong value) {
+ 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) {
+ public StringBuilder Append(Object value)
+ {
Contract.Ensures(Contract.Result<StringBuilder>() != null);
- if (null==value) {
+ if (null == value)
+ {
//Appending null is now a no-op.
return this;
}
@@ -982,12 +1090,14 @@ namespace System.Text {
}
// Appends all of the characters in value to the current instance.
- public StringBuilder Append(char[] value) {
+ public StringBuilder Append(char[] value)
+ {
Contract.Ensures(Contract.Result<StringBuilder>() != null);
if (null != value && value.Length > 0)
{
- unsafe {
+ unsafe
+ {
fixed (char* valueChars = &value[0])
Append(valueChars, value.Length);
}
@@ -1086,8 +1196,10 @@ namespace System.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) {
+ 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);
@@ -1095,7 +1207,8 @@ namespace System.Text {
if (value != null)
{
- unsafe {
+ unsafe
+ {
fixed (char* sourcePtr = value)
Insert(index, sourcePtr, value.Length);
}
@@ -1108,7 +1221,8 @@ namespace System.Text {
// The capacity is adjusted as needed. If value equals String.Empty, the
// StringBuilder is not changed.
//
- public StringBuilder Insert( int index, bool value) {
+ public StringBuilder Insert(int index, bool value)
+ {
Contract.Ensures(Contract.Result<StringBuilder>() != null);
return Insert(index, value.ToString(), 1);
}
@@ -1119,7 +1233,8 @@ namespace System.Text {
// StringBuilder is not changed.
//
[CLSCompliant(false)]
- public StringBuilder Insert(int index, sbyte value) {
+ public StringBuilder Insert(int index, sbyte value)
+ {
Contract.Ensures(Contract.Result<StringBuilder>() != null);
return Insert(index, value.ToString(CultureInfo.CurrentCulture), 1);
}
@@ -1129,7 +1244,8 @@ namespace System.Text {
// The capacity is adjusted as needed. If value equals String.Empty, the
// StringBuilder is not changed.
//
- public StringBuilder Insert(int index, byte value) {
+ public StringBuilder Insert(int index, byte value)
+ {
Contract.Ensures(Contract.Result<StringBuilder>() != null);
return Insert(index, value.ToString(CultureInfo.CurrentCulture), 1);
}
@@ -1139,7 +1255,8 @@ namespace System.Text {
// The capacity is adjusted as needed. If value equals String.Empty, the
// StringBuilder is not changed.
//
- public StringBuilder Insert(int index, short value) {
+ public StringBuilder Insert(int index, short value)
+ {
Contract.Ensures(Contract.Result<StringBuilder>() != null);
return Insert(index, value.ToString(CultureInfo.CurrentCulture), 1);
}
@@ -1148,10 +1265,12 @@ namespace System.Text {
// 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) {
+ public StringBuilder Insert(int index, char value)
+ {
Contract.Ensures(Contract.Result<StringBuilder>() != null);
- unsafe {
+ unsafe
+ {
Insert(index, &value, 1);
}
return this;
@@ -1162,8 +1281,10 @@ namespace System.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) {
+ 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);
@@ -1178,16 +1299,19 @@ namespace System.Text {
// 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) {
+ 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) {
+ 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 (value == null)
+ {
if (startIndex == 0 && charCount == 0)
{
return this;
@@ -1196,21 +1320,25 @@ namespace System.Text {
}
//Range check the array.
- if (startIndex < 0) {
+ if (startIndex < 0)
+ {
throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
}
- if (charCount < 0) {
+ if (charCount < 0)
+ {
throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
}
- if (startIndex > value.Length - charCount) {
+ if (startIndex > value.Length - charCount)
+ {
throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
if (charCount > 0)
{
- unsafe {
+ unsafe
+ {
fixed (char* sourcePtr = &value[startIndex])
Insert(index, sourcePtr, charCount);
}
@@ -1223,7 +1351,8 @@ namespace System.Text {
// The capacity is adjusted as needed. If value equals String.Empty, the
// StringBuilder is not changed.
//
- public StringBuilder Insert(int index, int value){
+ public StringBuilder Insert(int index, int value)
+ {
Contract.Ensures(Contract.Result<StringBuilder>() != null);
return Insert(index, value.ToString(CultureInfo.CurrentCulture), 1);
}
@@ -1233,7 +1362,8 @@ namespace System.Text {
// The capacity is adjusted as needed. If value equals String.Empty, the
// StringBuilder is not changed.
//
- public StringBuilder Insert(int index, long value) {
+ public StringBuilder Insert(int index, long value)
+ {
Contract.Ensures(Contract.Result<StringBuilder>() != null);
return Insert(index, value.ToString(CultureInfo.CurrentCulture), 1);
}
@@ -1243,7 +1373,8 @@ namespace System.Text {
// The capacity is adjusted as needed. If value equals String.Empty, the
// StringBuilder is not changed.
//
- public StringBuilder Insert(int index, float value) {
+ public StringBuilder Insert(int index, float value)
+ {
Contract.Ensures(Contract.Result<StringBuilder>() != null);
return Insert(index, value.ToString(CultureInfo.CurrentCulture), 1);
}
@@ -1253,12 +1384,14 @@ namespace System.Text {
// The capacity is adjusted as needed. If value equals String.Empty, the
// StringBuilder is not changed.
//
- public StringBuilder Insert(int index, double value) {
+ 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) {
+ public StringBuilder Insert(int index, decimal value)
+ {
Contract.Ensures(Contract.Result<StringBuilder>() != null);
return Insert(index, value.ToString(CultureInfo.CurrentCulture), 1);
}
@@ -1268,7 +1401,8 @@ namespace System.Text {
// The capacity is adjusted as needed.
//
[CLSCompliant(false)]
- public StringBuilder Insert(int index, ushort value) {
+ public StringBuilder Insert(int index, ushort value)
+ {
Contract.Ensures(Contract.Result<StringBuilder>() != null);
return Insert(index, value.ToString(CultureInfo.CurrentCulture), 1);
}
@@ -1278,7 +1412,8 @@ namespace System.Text {
// The capacity is adjusted as needed.
//
[CLSCompliant(false)]
- public StringBuilder Insert(int index, uint value) {
+ public StringBuilder Insert(int index, uint value)
+ {
Contract.Ensures(Contract.Result<StringBuilder>() != null);
return Insert(index, value.ToString(CultureInfo.CurrentCulture), 1);
}
@@ -1288,7 +1423,8 @@ namespace System.Text {
// The capacity is adjusted as needed.
//
[CLSCompliant(false)]
- public StringBuilder Insert(int index, ulong value) {
+ public StringBuilder Insert(int index, ulong value)
+ {
Contract.Ensures(Contract.Result<StringBuilder>() != null);
return Insert(index, value.ToString(CultureInfo.CurrentCulture), 1);
}
@@ -1298,30 +1434,36 @@ namespace System.Text {
// 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) {
+ public StringBuilder Insert(int index, Object value)
+ {
Contract.Ensures(Contract.Result<StringBuilder>() != null);
- if (null == value) {
+ if (null == value)
+ {
return this;
}
return Insert(index, value.ToString(), 1);
}
- public StringBuilder AppendFormat(String format, Object arg0) {
+ 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) {
+ 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) {
+ 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) {
+ public StringBuilder AppendFormat(String format, params Object[] args)
+ {
if (args == null)
{
// To preserve the original exception behavior, throw an exception about format if both
@@ -1330,26 +1472,30 @@ namespace System.Text {
}
Contract.Ensures(Contract.Result<String>() != null);
Contract.EndContractBlock();
-
+
return AppendFormatHelper(null, format, new ParamsArray(args));
}
- public StringBuilder AppendFormat(IFormatProvider provider, String format, Object arg0) {
+ 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) {
+
+ 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) {
+
+ 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) {
+
+ 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
@@ -1358,11 +1504,12 @@ namespace System.Text {
}
Contract.Ensures(Contract.Result<String>() != null);
Contract.EndContractBlock();
-
+
return AppendFormatHelper(provider, format, new ParamsArray(args));
}
-
- private static void FormatError() {
+
+ private static void FormatError()
+ {
throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
}
@@ -1370,8 +1517,10 @@ namespace System.Text {
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) {
+ internal StringBuilder AppendFormatHelper(IFormatProvider provider, String format, ParamsArray args)
+ {
+ if (format == null)
+ {
throw new ArgumentNullException(nameof(format));
}
Contract.Ensures(Contract.Result<StringBuilder>() != null);
@@ -1383,12 +1532,15 @@ namespace System.Text {
StringBuilder unescapedItemFormat = null;
ICustomFormatter cf = null;
- if (provider != null) {
+ if (provider != null)
+ {
cf = (ICustomFormatter)provider.GetFormat(typeof(ICustomFormatter));
}
- while (true) {
- while (pos < len) {
+ while (true)
+ {
+ while (pos < len)
+ {
ch = format[pos];
pos++;
@@ -1424,7 +1576,7 @@ namespace System.Text {
// Argument Hole ::= { Index (, WS* Alignment WS*)? (: Formatting)? }
//
if (pos == len) break;
-
+
//
// Start of parsing required Index parameter.
// Index ::= ('0'-'9')+ WS*
@@ -1434,7 +1586,8 @@ namespace System.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 {
+ do
+ {
index = index * 10 + ch - '0';
pos++;
// If reached end of text then error (Unexpected end of text)
@@ -1445,7 +1598,7 @@ namespace System.Text {
// 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.
@@ -1457,18 +1610,20 @@ namespace System.Text {
bool leftJustify = false;
int width = 0;
// Is the character a comma, which indicates the start of alignment parameter.
- if (ch == ',') {
+ 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 == '-') {
+ if (ch == '-')
+ {
// Yes, then alignment is left justified.
leftJustify = true;
pos++;
@@ -1476,11 +1631,12 @@ namespace System.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 {
+ do
+ {
width = width * 10 + ch - '0';
pos++;
// If reached end of text then error. (Unexpected end of text)
@@ -1500,11 +1656,13 @@ namespace System.Text {
Object arg = args[index];
String itemFormat = null;
// Is current character a colon? which indicates start of formatting parameter.
- if (ch == ':') {
+ if (ch == ':')
+ {
pos++;
int startPos = pos;
- while (true) {
+ while (true)
+ {
// If reached end of text then error. (Unexpected end of text)
if (pos == len) FormatError();
ch = format[pos];
@@ -1566,16 +1724,21 @@ namespace System.Text {
// Construct the output for this arg hole.
pos++;
String s = null;
- if (cf != null) {
+ if (cf != null)
+ {
s = cf.Format(itemFormat, arg, provider);
}
- if (s == null) {
+ if (s == null)
+ {
IFormattable formattableArg = arg as IFormattable;
- if (formattableArg != null) {
+ if (formattableArg != null)
+ {
s = formattableArg.ToString(itemFormat, provider);
- } else if (arg != null) {
+ }
+ else if (arg != null)
+ {
s = arg.ToString();
}
}
@@ -1596,12 +1759,13 @@ namespace System.Text {
// 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) {
+ public StringBuilder Replace(String oldValue, String newValue)
+ {
Contract.Ensures(Contract.Result<StringBuilder>() != null);
return Replace(oldValue, newValue, 0, Length);
}
- public bool Equals(StringBuilder sb)
+ public bool Equals(StringBuilder sb)
{
if (sb == null)
return false;
@@ -1614,7 +1778,7 @@ namespace System.Text {
int thisChunkIndex = thisChunk.m_ChunkLength;
StringBuilder sbChunk = sb;
int sbChunkIndex = sbChunk.m_ChunkLength;
- for (; ; )
+ for (;;)
{
// Decrement the pointer to the 'this' StringBuilder
--thisChunkIndex;
@@ -1731,24 +1895,28 @@ namespace System.Text {
// 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) {
+ public StringBuilder Replace(char oldChar, char newChar)
+ {
return Replace(oldChar, newChar, 0, Length);
}
- public StringBuilder Replace(char oldChar, char newChar, int startIndex, int count) {
+ 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) {
+ if ((uint)startIndex > (uint)currentLength)
+ {
throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
- if (count < 0 || startIndex > currentLength - count) {
+ if (count < 0 || startIndex > currentLength - count)
+ {
throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
int endIndex = startIndex + count;
StringBuilder chunk = this;
- for (; ; )
+ for (;;)
{
int endIndexInChunk = endIndex - chunk.m_ChunkOffset;
int startIndexInChunk = startIndex - chunk.m_ChunkOffset;
@@ -1785,7 +1953,8 @@ namespace System.Text {
// 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) {
+ if (newLength > m_MaxCapacity || newLength < valueCount)
+ {
throw new ArgumentOutOfRangeException(nameof(valueCount), Environment.GetResourceString("ArgumentOutOfRange_LengthGreaterThanCapacity"));
}
@@ -1849,21 +2018,22 @@ namespace System.Text {
if (replacementsCount <= 0)
return;
- unsafe {
+ 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 (; ; )
+ for (;;)
{
// Copy in the new string for the ith replacement
ReplaceInPlaceAtChunk(ref targetChunk, ref targetIndexInChunk, valuePtr, value.Length);
@@ -1871,7 +2041,7 @@ namespace System.Text {
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");
@@ -1888,7 +2058,7 @@ namespace System.Text {
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);
@@ -1934,7 +2104,7 @@ namespace System.Text {
{
if (count != 0)
{
- for (; ; )
+ for (;;)
{
int lengthInChunk = chunk.m_ChunkLength - indexInChunk;
Debug.Assert(lengthInChunk >= 0, "index not in chunk");
@@ -1983,7 +2153,8 @@ namespace System.Text {
{
if ((uint)sourceIndex <= (uint)source.Length && (sourceIndex + count) <= source.Length)
{
- unsafe {
+ unsafe
+ {
fixed (char* sourcePtr = &source[sourceIndex])
ThreadSafeCopy(sourcePtr, destination, destinationIndex, count);
}
@@ -1995,29 +2166,35 @@ namespace System.Text {
}
}
- // Copies the source StringBuilder to the destination IntPtr memory allocated with len bytes.
- internal unsafe void InternalCopy(IntPtr dest, int len) {
- if(len ==0)
+ // 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();
+ 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;
+ 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 {
+ }
+ else
+ {
Buffer.Memcpy(dstPtr + chunkOffsetInBytes, srcPtr, chunkLengthInBytes);
}
}
currentSrc = currentSrc.m_ChunkPrevious;
- } while(currentSrc != null);
+ } while (currentSrc != null);
}
/// <summary>
@@ -2045,10 +2222,10 @@ namespace System.Text {
/// <returns></returns>
private StringBuilder FindChunkForByte(int byteIndex)
{
- Debug.Assert(0 <= byteIndex && byteIndex <= Length*sizeof(char), "Byte Index not in string");
+ Debug.Assert(0 <= byteIndex && byteIndex <= Length * sizeof(char), "Byte Index not in string");
StringBuilder ret = this;
- while (ret.m_ChunkOffset*sizeof(char) > byteIndex)
+ while (ret.m_ChunkOffset * sizeof(char) > byteIndex)
ret = ret.m_ChunkPrevious;
Debug.Assert(ret != null, "Byte Index not in string");
@@ -2155,7 +2332,7 @@ namespace System.Text {
// (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; )
+ for (int i = chunk.m_ChunkLength; i > indexInChunk;)
{
--i;
chunk.m_ChunkChars[i + count] = chunk.m_ChunkChars[i];
@@ -2172,10 +2349,12 @@ namespace System.Text {
int copyCount1 = Math.Min(count, indexInChunk);
if (copyCount1 > 0)
{
- unsafe {
- fixed (char* chunkCharsPtr = &chunk.m_ChunkChars[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)
@@ -2228,7 +2407,7 @@ namespace System.Text {
chunk = this;
StringBuilder endChunk = null;
int endIndexInChunk = 0;
- for (; ; )
+ for (;;)
{
if (endIndex - chunk.m_ChunkOffset >= 0)
{
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
index a7ac1d8539..f5b3d105be 100644
--- a/src/mscorlib/src/System/Text/UTF32Encoding.cs
+++ b/src/mscorlib/src/System/Text/UTF32Encoding.cs
@@ -6,13 +6,14 @@
// Don't override IsAlwaysNormalized because it is just a Unicode Transformation and could be confused.
//
+
+using System;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+using System.Globalization;
+
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,
//
@@ -45,33 +46,33 @@ namespace System.Text
private bool bigEndian = false;
- public UTF32Encoding(): this(false, true, false)
+ public UTF32Encoding() : this(false, true, false)
{
}
- public UTF32Encoding(bool bigEndian, bool byteOrderMark):
+ public UTF32Encoding(bool bigEndian, bool byteOrderMark) :
this(bigEndian, byteOrderMark, false)
{
}
- public UTF32Encoding(bool bigEndian, bool byteOrderMark, bool throwOnInvalidCharacters):
+ public UTF32Encoding(bool bigEndian, bool byteOrderMark, bool throwOnInvalidCharacters) :
base(bigEndian ? 12001 : 12000)
{
this.bigEndian = bigEndian;
- this.emitUTF32ByteOrderMark = byteOrderMark;
- this.isThrowException = throwOnInvalidCharacters;
+ emitUTF32ByteOrderMark = byteOrderMark;
+ isThrowException = throwOnInvalidCharacters;
// Encoding's constructor already did this, but it'll be wrong if we're throwing exceptions
- if (this.isThrowException)
+ if (isThrowException)
SetDefaultFallbacks();
}
internal override void SetDefaultFallbacks()
{
// For UTF-X encodings, we use a replacement fallback with an empty string
- if (this.isThrowException)
+ if (isThrowException)
{
this.encoderFallback = EncoderFallback.ExceptionFallback;
this.decoderFallback = DecoderFallback.ExceptionFallback;
@@ -176,13 +177,13 @@ namespace System.Text
{
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)
+ 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");
+ Debug.Assert(chars != null, "[UTF32Encoding.GetByteCount]chars!=null");
+ Debug.Assert(count >= 0, "[UTF32Encoding.GetByteCount]count >=0");
char* end = chars + count;
char* charStart = chars;
@@ -211,7 +212,7 @@ namespace System.Text
fallbackBuffer.InternalInitialize(charStart, end, encoder, false);
char ch;
- TryAgain:
+ TryAgain:
while (((ch = fallbackBuffer.InternalGetNextChar()) != 0) || chars < end)
{
@@ -244,7 +245,7 @@ namespace System.Text
// 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,
+ Debug.Assert(chars > charStart,
"[UTF32Encoding.GetByteCount]Expected chars to have advanced if no low surrogate");
chars--;
@@ -254,7 +255,6 @@ namespace System.Text
// We're going to fallback the old high surrogate.
highSurrogate = '\0';
continue;
-
}
// Do we have another high surrogate?
@@ -304,13 +304,13 @@ namespace System.Text
return byteCount;
}
- internal override unsafe int GetBytes(char *chars, int charCount,
+ 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");
+ 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;
@@ -340,7 +340,7 @@ namespace System.Text
fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, true);
char ch;
- TryAgain:
+ TryAgain:
while (((ch = fallbackBuffer.InternalGetNextChar()) != 0) || chars < charEnd)
{
@@ -367,7 +367,7 @@ namespace System.Text
//
// One surrogate pair will be translated into 4 bytes UTF32.
//
- if (bytes+3 >= byteEnd)
+ if (bytes + 3 >= byteEnd)
{
// Don't have 4 bytes
if (fallbackBuffer.bFallingBack)
@@ -379,9 +379,9 @@ namespace System.Text
{
// 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,
+ 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
+ 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)
@@ -407,7 +407,7 @@ namespace System.Text
// 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,
+ Debug.Assert(chars > charStart,
"[UTF32Encoding.GetBytes]Expected chars to have advanced if no low surrogate");
chars--;
@@ -440,7 +440,7 @@ namespace System.Text
}
// We get to add the character, yippee.
- if (bytes+3 >= byteEnd)
+ if (bytes + 3 >= byteEnd)
{
// Don't have 4 bytes
if (fallbackBuffer.bFallingBack)
@@ -491,7 +491,7 @@ namespace System.Text
encoder.charLeftOver = highSurrogate;
// Need # chars used
- encoder.m_charsUsed = (int)(chars-charStart);
+ encoder.m_charsUsed = (int)(chars - charStart);
}
// return the new length
@@ -500,8 +500,8 @@ namespace System.Text
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");
+ Debug.Assert(bytes != null, "[UTF32Encoding.GetCharCount]bytes!=null");
+ Debug.Assert(count >= 0, "[UTF32Encoding.GetCharCount]count >=0");
UTF32Decoder decoder = (UTF32Decoder)baseDecoder;
@@ -541,7 +541,7 @@ namespace System.Text
while (bytes < end && charCount >= 0)
{
// Get our next character
- if(bigEndian)
+ if (bigEndian)
{
// Scoot left and add it to the bottom
iChar <<= 8;
@@ -564,11 +564,11 @@ namespace System.Text
readCount = 0;
// See if its valid to encode
- if ( iChar > 0x10FFFF || (iChar >= 0xD800 && iChar <= 0xDFFF))
+ if (iChar > 0x10FFFF || (iChar >= 0xD800 && iChar <= 0xDFFF))
{
// Need to fall back these 4 bytes
byte[] fallbackBytes;
- if (this.bigEndian)
+ if (bigEndian)
{
fallbackBytes = new byte[] {
unchecked((byte)(iChar>>24)), unchecked((byte)(iChar>>16)),
@@ -607,9 +607,9 @@ namespace System.Text
{
// Oops, there's something left over with no place to go.
byte[] fallbackBytes = new byte[readCount];
- if (this.bigEndian)
+ if (bigEndian)
{
- while(readCount > 0)
+ while (readCount > 0)
{
fallbackBytes[--readCount] = unchecked((byte)iChar);
iChar >>= 8;
@@ -619,7 +619,7 @@ namespace System.Text
{
while (readCount > 0)
{
- fallbackBytes[--readCount] = unchecked((byte)(iChar>>24));
+ fallbackBytes[--readCount] = unchecked((byte)(iChar >> 24));
iChar <<= 8;
}
}
@@ -643,10 +643,10 @@ namespace System.Text
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");
+ 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;
@@ -688,7 +688,7 @@ namespace System.Text
while (bytes < byteEnd)
{
// Get our next character
- if(bigEndian)
+ if (bigEndian)
{
// Scoot left and add it to the bottom
iChar <<= 8;
@@ -711,11 +711,11 @@ namespace System.Text
readCount = 0;
// See if its valid to encode
- if ( iChar > 0x10FFFF || (iChar >= 0xD800 && iChar <= 0xDFFF))
+ if (iChar > 0x10FFFF || (iChar >= 0xD800 && iChar <= 0xDFFF))
{
// Need to fall back these 4 bytes
byte[] fallbackBytes;
- if (this.bigEndian)
+ if (bigEndian)
{
fallbackBytes = new byte[] {
unchecked((byte)(iChar>>24)), unchecked((byte)(iChar>>16)),
@@ -736,8 +736,8 @@ namespace System.Text
// 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
+ 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
@@ -760,8 +760,8 @@ namespace System.Text
// 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
+ 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
}
@@ -777,8 +777,8 @@ namespace System.Text
// 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
+ 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
}
@@ -796,9 +796,9 @@ namespace System.Text
// Oops, there's something left over with no place to go.
byte[] fallbackBytes = new byte[readCount];
int tempCount = readCount;
- if (this.bigEndian)
+ if (bigEndian)
{
- while(tempCount > 0)
+ while (tempCount > 0)
{
fallbackBytes[--tempCount] = unchecked((byte)iChar);
iChar >>= 8;
@@ -808,7 +808,7 @@ namespace System.Text
{
while (tempCount > 0)
{
- fallbackBytes[--tempCount] = unchecked((byte)(iChar>>24));
+ fallbackBytes[--tempCount] = unchecked((byte)(iChar >> 24));
iChar <<= 8;
}
}
@@ -878,8 +878,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),
+ Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
// Characters would be # of characters + 1 in case left over high surrogate is ? * max fallback
@@ -901,8 +901,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),
+ Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
// A supplementary character becomes 2 surrogate characters, so 4 input bytes becomes 2 chars,
@@ -954,7 +954,7 @@ namespace System.Text
{
return (emitUTF32ByteOrderMark == that.emitUTF32ByteOrderMark) &&
(bigEndian == that.bigEndian) &&
-// (isThrowException == that.isThrowException) && // same as encoder/decoderfallback being exceptions
+ // (isThrowException == that.isThrowException) && // same as encoder/decoderfallback being exceptions
(EncoderFallback.Equals(that.EncoderFallback)) &&
(DecoderFallback.Equals(that.DecoderFallback));
}
@@ -966,7 +966,7 @@ namespace System.Text
{
//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);
+ CodePage + (emitUTF32ByteOrderMark ? 4 : 0) + (bigEndian ? 8 : 0);
}
[Serializable]
diff --git a/src/mscorlib/src/System/Text/UTF7Encoding.cs b/src/mscorlib/src/System/Text/UTF7Encoding.cs
index 9418d2e768..d0cf9961c2 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++)
@@ -237,13 +236,13 @@ namespace System.Text
{
return EncodingForwarder.GetString(this, bytes, index, count);
}
-
+
// End of overridden methods which use EncodingForwarder
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 +251,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 +338,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 +390,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 +400,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 +448,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 +580,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),
+ Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
// Suppose that every char can not be direct-encoded, we know that
@@ -614,8 +613,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),
+ Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
// Worst case is 1 char per byte. Minimum 1 for left over bits in case decoder is being flushed
@@ -633,10 +632,12 @@ namespace System.Text
{
/*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 +646,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 +660,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
@@ -697,7 +698,8 @@ namespace System.Text
{
/*private*/
internal int bits;
- /*private*/ internal int bitCount;
+ /*private*/
+ internal int bitCount;
public Encoder(UTF7Encoding encoding) : base(encoding)
{
@@ -708,7 +710,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 +723,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 +737,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?
@@ -773,7 +775,7 @@ namespace System.Text
}
}
- public override bool Equals(Object value)
+ public override bool Equals(Object value)
{
DecoderUTF7Fallback that = value as DecoderUTF7Fallback;
if (that != null)
@@ -792,9 +794,9 @@ namespace System.Text
internal 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 +857,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.
@@ -874,6 +876,5 @@ namespace System.Text
return bytes[0] == 0 ? 0 : 1;
}
}
-
}
}
diff --git a/src/mscorlib/src/System/Text/UTF8Encoding.cs b/src/mscorlib/src/System/Text/UTF8Encoding.cs
index 191bbfef56..b2cc462027 100644
--- a/src/mscorlib/src/System/Text/UTF8Encoding.cs
+++ b/src/mscorlib/src/System/Text/UTF8Encoding.cs
@@ -51,8 +51,8 @@ namespace System.Text
Real Unicode value = (HighSurrogate - 0xD800) * 0x400 + (LowSurrogate - 0xDC00) + 0x10000
*/
- private const int UTF8_CODEPAGE=65001;
-
+ 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);
@@ -64,32 +64,32 @@ namespace System.Text
private bool isThrowException = false;
- public UTF8Encoding(): this(false)
+ public UTF8Encoding() : this(false)
{
}
- public UTF8Encoding(bool encoderShouldEmitUTF8Identifier):
+ public UTF8Encoding(bool encoderShouldEmitUTF8Identifier) :
this(encoderShouldEmitUTF8Identifier, false)
{
}
- public UTF8Encoding(bool encoderShouldEmitUTF8Identifier, bool throwOnInvalidBytes):
+ public UTF8Encoding(bool encoderShouldEmitUTF8Identifier, bool throwOnInvalidBytes) :
base(UTF8_CODEPAGE)
{
- this.emitUTF8Identifier = encoderShouldEmitUTF8Identifier;
- this.isThrowException = throwOnInvalidBytes;
+ emitUTF8Identifier = encoderShouldEmitUTF8Identifier;
+ isThrowException = throwOnInvalidBytes;
// Encoding's constructor already did this, but it'll be wrong if we're throwing exceptions
- if (this.isThrowException)
+ if (isThrowException)
SetDefaultFallbacks();
}
internal override void SetDefaultFallbacks()
{
// For UTF-X encodings, we use a replacement fallback with an empty string
- if (this.isThrowException)
+ if (isThrowException)
{
this.encoderFallback = EncoderFallback.ExceptionFallback;
this.decoderFallback = DecoderFallback.ExceptionFallback;
@@ -194,25 +194,26 @@ namespace System.Text
{
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)
+ 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;
+ 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) {
+ if (baseEncoder != null)
+ {
UTF8Encoder encoder = (UTF8Encoder)baseEncoder;
ch = encoder.surrogateChar;
@@ -229,43 +230,56 @@ namespace System.Text
}
}
- for (;;) {
+ for (;;)
+ {
// SLOWLOOP: does all range checks, handles all special cases, but it is slow
- if (pSrc >= pEnd) {
-
- if (ch == 0) {
+ if (pSrc >= pEnd)
+ {
+ if (ch == 0)
+ {
// Unroll any fallback that happens at the end
ch = fallbackBuffer != null ? fallbackBuffer.InternalGetNextChar() : 0;
- if (ch > 0) {
+ if (ch > 0)
+ {
byteCount++;
goto ProcessChar;
}
- } else {
+ }
+ else
+ {
// Case of surrogates in the fallback.
- if (fallbackBuffer != null && fallbackBuffer.bFallingBack) {
+ 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)) {
+
+ if (InRange(ch, CharUnicodeInfo.LOW_SURROGATE_START, CharUnicodeInfo.LOW_SURROGATE_END))
+ {
ch = 0xfffd;
byteCount++;
goto EncodeChar;
- } else if (ch > 0){
+ }
+ else if (ch > 0)
+ {
goto ProcessChar;
- } else {
+ }
+ else
+ {
byteCount--; // ignore last one.
break;
}
}
}
-
- if (ch <= 0) {
+
+ if (ch <= 0)
+ {
break;
}
- if (baseEncoder != null && !baseEncoder.MustFlush) {
+ if (baseEncoder != null && !baseEncoder.MustFlush)
+ {
break;
}
@@ -274,7 +288,8 @@ namespace System.Text
goto EncodeChar;
}
- if (ch > 0) {
+ if (ch > 0)
+ {
Debug.Assert(ch >= 0xD800 && ch <= 0xDBFF,
"[UTF8Encoding.GetBytes]expected high surrogate, not 0x" + ((int)ch).ToString("X4", CultureInfo.InvariantCulture));
@@ -287,13 +302,14 @@ namespace System.Text
// 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)) {
+ 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) );
+ // ch = cha + (ch << 10) +
+ // (0x10000
+ // - CharUnicodeInfo.LOW_SURROGATE_START
+ // - (CharUnicodeInfo.HIGH_SURROGATE_START << 10) );
// Use this next char
pSrc++;
@@ -323,12 +339,13 @@ namespace System.Text
ProcessChar:
// if (IsHighSurrogate(ch)) {
- if (InRange(ch, CharUnicodeInfo.HIGH_SURROGATE_START, CharUnicodeInfo.HIGH_SURROGATE_END)) {
+ 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
+ // either good char or partial surrogate
EncodeChar:
// throw exception on partial surrogate if necessary
@@ -361,8 +378,10 @@ namespace System.Text
}
// Count them
- if (ch > 0x7F) {
- if (ch > 0x7FF) {
+ 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++;
@@ -372,7 +391,8 @@ namespace System.Text
#if BIT64
// check for overflow
- if (byteCount < 0) {
+ if (byteCount < 0)
+ {
break;
}
#endif
@@ -389,16 +409,18 @@ namespace System.Text
int availableChars = PtrDiff(pEnd, pSrc);
// don't fall into the fast decoding loop if we don't have enough characters
- if (availableChars <= 13) {
+ 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) {
+ while (pSrc < pLocalEnd)
+ {
ch = *pSrc;
pSrc++;
if (ch > 0x7F)
goto ProcessChar;
}
-
+
// we are done
break;
}
@@ -412,9 +434,10 @@ namespace System.Text
// 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);
+ char* pStop = pSrc + availableChars - (3 + 4);
- while (pSrc < pStop) {
+ while (pSrc < pStop)
+ {
ch = *pSrc;
pSrc++;
@@ -426,11 +449,12 @@ namespace System.Text
goto LongCode;
byteCount++;
}
- byteCount ++;
+ byteCount++;
}
// get pSrc aligned
- if ((unchecked((int)pSrc) & 0x2) != 0) {
+ if ((unchecked((int)pSrc) & 0x2) != 0)
+ {
ch = *pSrc;
pSrc++;
if (ch > 0x7F) // Not ASCII
@@ -441,14 +465,15 @@ namespace System.Text
goto LongCode;
byteCount++;
}
- byteCount ++;
+ byteCount++;
}
}
// Run 2 * 4 characters at a time!
- while (pSrc < pStop) {
+ while (pSrc < pStop)
+ {
ch = *(int*)pSrc;
- int chc = *(int*)(pSrc+2);
+ 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
@@ -469,7 +494,7 @@ namespace System.Text
pSrc += 4;
ch = *(int*)pSrc;
- chc = *(int*)(pSrc+2);
+ 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
@@ -499,16 +524,19 @@ namespace System.Text
#endif // BIGENDIAN
pSrc++;
- if (ch <= 0x7F) {
+ 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 (ch > 0x7FF)
+ {
// if (IsLowSurrogate(ch) || IsHighSurrogate(ch))
- if (InRange(ch, CharUnicodeInfo.HIGH_SURROGATE_START, CharUnicodeInfo.LOW_SURROGATE_END)) {
+ if (InRange(ch, CharUnicodeInfo.HIGH_SURROGATE_START, CharUnicodeInfo.LOW_SURROGATE_END))
+ {
// 4 byte encoding - high surrogate + low surrogate
int chd = *pSrc;
@@ -516,7 +544,7 @@ namespace System.Text
// !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) )
+ !InRange(chd, CharUnicodeInfo.LOW_SURROGATE_START, CharUnicodeInfo.LOW_SURROGATE_END))
{
// Back up and drop out to slow loop to figure out error
pSrc--;
@@ -540,7 +568,8 @@ namespace System.Text
#if BIT64
// check for overflow
- if (byteCount < 0) {
+ if (byteCount < 0)
+ {
throw new ArgumentException(
Environment.GetResourceString("Argument_ConversionOverflow"));
}
@@ -555,7 +584,7 @@ namespace System.Text
// 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)
+ unsafe private static int PtrDiff(char* a, char* b)
{
return (int)(((uint)((byte*)a - (byte*)b)) >> 1);
}
@@ -576,27 +605,28 @@ namespace System.Text
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");
+ 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* pSrc = chars;
+ byte* pTarget = bytes;
- char *pEnd = pSrc+charCount;
- byte *pAllocatedBufferEnd = pTarget+byteCount;
+ char* pEnd = pSrc + charCount;
+ byte* pAllocatedBufferEnd = pTarget + byteCount;
int ch = 0;
// assume that JIT will enregister pSrc, pTarget and ch
- if (baseEncoder != null) {
+ if (baseEncoder != null)
+ {
encoder = (UTF8Encoder)baseEncoder;
ch = encoder.surrogateChar;
@@ -614,38 +644,49 @@ namespace System.Text
}
}
- for (;;) {
+ for (;;)
+ {
// SLOWLOOP: does all range checks, handles all special cases, but it is slow
- if (pSrc >= pEnd) {
-
- if (ch == 0) {
+ 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) {
+ if (ch > 0)
+ {
goto ProcessChar;
}
- } else {
+ }
+ else
+ {
// Case of leftover surrogates in the fallback buffer
- if (fallbackBuffer != null && fallbackBuffer.bFallingBack) {
+ 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)) {
+
+ 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){
+ }
+ else if (ch > 0)
+ {
goto ProcessChar;
- } else {
+ }
+ else
+ {
break;
}
}
}
-
+
// attempt to encode the partial surrogate (will fail or ignore)
if (ch > 0 && (encoder == null || encoder.MustFlush))
goto EncodeChar;
@@ -654,7 +695,8 @@ namespace System.Text
break;
}
- if (ch > 0) {
+ 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));
@@ -665,11 +707,12 @@ namespace System.Text
// 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)) {
+ 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) );
+ - (CharUnicodeInfo.HIGH_SURROGATE_START << 10));
pSrc++;
}
@@ -693,10 +736,11 @@ namespace System.Text
ProcessChar:
// if (IsHighSurrogate(ch)) {
- if (InRange(ch, CharUnicodeInfo.HIGH_SURROGATE_START, CharUnicodeInfo.HIGH_SURROGATE_END)) {
+ if (InRange(ch, CharUnicodeInfo.HIGH_SURROGATE_START, CharUnicodeInfo.HIGH_SURROGATE_END))
+ {
continue;
}
- // either good char or partial surrogate
+ // either good char or partial surrogate
EncodeChar:
// throw exception on partial surrogate if necessary
@@ -729,9 +773,12 @@ namespace System.Text
// Count bytes needed
int bytesNeeded = 1;
- if (ch > 0x7F) {
- if (ch > 0x7FF) {
- if (ch > 0xFFFF) {
+ if (ch > 0x7F)
+ {
+ if (ch > 0x7FF)
+ {
+ if (ch > 0xFFFF)
+ {
bytesNeeded++; // 4 bytes (surrogate pair)
}
bytesNeeded++; // 3 bytes (800-FFFF)
@@ -739,7 +786,8 @@ namespace System.Text
bytesNeeded++; // 2 bytes (80-7FF)
}
- if (pTarget > pAllocatedBufferEnd - bytesNeeded) {
+ if (pTarget > pAllocatedBufferEnd - bytesNeeded)
+ {
// Left over surrogate from last time will cause pSrc == chars, so we'll throw
if (fallbackBuffer != null && fallbackBuffer.bFallingBack)
{
@@ -760,20 +808,24 @@ namespace System.Text
break;
}
- if (ch <= 0x7F) {
+ if (ch <= 0x7F)
+ {
*pTarget = (byte)ch;
}
- else {
+ 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) {
+ if (ch <= 0x7FF)
+ {
// 2 byte encoding
chb = (byte)(unchecked((sbyte)0xC0) | (ch >> 6));
}
else
{
- if (ch <= 0xFFFF) {
+ if (ch <= 0xFFFF)
+ {
chb = (byte)(unchecked((sbyte)0xE0) | (ch >> 12));
}
else
@@ -806,17 +858,20 @@ namespace System.Text
// 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) {
+ if (availableChars <= 13)
+ {
// we are hoping for 1 byte per char
- if (availableBytes < availableChars) {
+ 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) {
+ while (pSrc < pLocalEnd)
+ {
ch = *pSrc;
pSrc++;
@@ -847,23 +902,27 @@ namespace System.Text
// 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;
+ char* pStop = pSrc + availableChars - 5;
- while (pSrc < pStop) {
+ while (pSrc < pStop)
+ {
ch = *pSrc;
pSrc++;
- if (ch > 0x7F) {
+ if (ch > 0x7F)
+ {
goto LongCode;
}
*pTarget = (byte)ch;
pTarget++;
// get pSrc aligned
- if ((unchecked((int)pSrc) & 0x2) != 0) {
+ if ((unchecked((int)pSrc) & 0x2) != 0)
+ {
ch = *pSrc;
pSrc++;
- if (ch > 0x7F) {
+ if (ch > 0x7F)
+ {
goto LongCode;
}
*pTarget = (byte)ch;
@@ -871,10 +930,12 @@ namespace System.Text
}
// Run 4 characters at a time!
- while (pSrc < pStop) {
+ while (pSrc < pStop)
+ {
ch = *(int*)pSrc;
- int chc = *(int*)(pSrc+2);
- if (((ch | chc) & unchecked((int)0xFF80FF80)) != 0) {
+ int chc = *(int*)(pSrc + 2);
+ if (((ch | chc) & unchecked((int)0xFF80FF80)) != 0)
+ {
goto LongCodeWithMask;
}
@@ -888,10 +949,10 @@ namespace System.Text
pTarget += 4;
#else // BIGENDIAN
*pTarget = (byte)ch;
- *(pTarget+1) = (byte)(ch>>16);
+ *(pTarget + 1) = (byte)(ch >> 16);
pSrc += 4;
- *(pTarget+2) = (byte)chc;
- *(pTarget+3) = (byte)(chc>>16);
+ *(pTarget + 2) = (byte)chc;
+ *(pTarget + 3) = (byte)(chc >> 16);
pTarget += 4;
#endif // BIGENDIAN
}
@@ -906,7 +967,8 @@ namespace System.Text
#endif // BIGENDIAN
pSrc++;
- if (ch > 0x7F) {
+ if (ch > 0x7F)
+ {
goto LongCode;
}
*pTarget = (byte)ch;
@@ -917,13 +979,16 @@ namespace System.Text
// 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) {
+ if (ch <= 0x7FF)
+ {
// 2 byte encoding
chd = unchecked((sbyte)0xC0) | (ch >> 6);
}
- else {
+ else
+ {
// if (!IsLowSurrogate(ch) && !IsHighSurrogate(ch))
- if (!InRange(ch, CharUnicodeInfo.HIGH_SURROGATE_START, CharUnicodeInfo.LOW_SURROGATE_END)) {
+ if (!InRange(ch, CharUnicodeInfo.HIGH_SURROGATE_START, CharUnicodeInfo.LOW_SURROGATE_END))
+ {
// 3 byte encoding
chd = unchecked((sbyte)0xE0) | (ch >> 12);
}
@@ -931,7 +996,8 @@ namespace System.Text
{
// 4 byte encoding - high surrogate + low surrogate
// if (!IsHighSurrogate(ch))
- if (ch > CharUnicodeInfo.HIGH_SURROGATE_END) {
+ if (ch > CharUnicodeInfo.HIGH_SURROGATE_END)
+ {
// low without high -> bad, try again in slow loop
pSrc -= 1;
break;
@@ -941,7 +1007,8 @@ namespace System.Text
pSrc++;
// if (!IsLowSurrogate(chd)) {
- if (!InRange(chd, CharUnicodeInfo.LOW_SURROGATE_START, CharUnicodeInfo.LOW_SURROGATE_END)) {
+ 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;
@@ -950,13 +1017,13 @@ namespace System.Text
ch = chd + (ch << 10) +
(0x10000
- CharUnicodeInfo.LOW_SURROGATE_START
- - (CharUnicodeInfo.HIGH_SURROGATE_START << 10) );
+ - (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++;
+ pTarget++;
chd = unchecked((sbyte)0x80) | (ch >> 12) & 0x3F;
}
@@ -1006,9 +1073,9 @@ namespace System.Text
// 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;
+ 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.
@@ -1017,12 +1084,12 @@ namespace System.Text
// 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");
+ 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;
+ 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
@@ -1030,7 +1097,8 @@ namespace System.Text
int ch = 0;
DecoderFallbackBuffer fallback = null;
- if (baseDecoder != 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.
@@ -1045,11 +1113,13 @@ namespace System.Text
{
// SLOWLOOP: does all range checks, handles all special cases, but it is slow
- if (pSrc >= pEnd) {
+ if (pSrc >= pEnd)
+ {
break;
}
- if (ch == 0) {
+ if (ch == 0)
+ {
// no pending bits
goto ReadChar;
}
@@ -1060,7 +1130,8 @@ namespace System.Text
pSrc++;
// we are expecting to see trailing bytes like 10vvvvvv
- if ((cha & unchecked((sbyte)0xC0)) != 0x80) {
+ 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--;
@@ -1071,27 +1142,32 @@ namespace System.Text
// fold in the new byte
ch = (ch << 6) | (cha & 0x3F);
- if ((ch & FinalByte) == 0) {
- Debug.Assert( (ch & (SupplimentarySeq | ThreeByteSeq)) != 0,
+ if ((ch & FinalByte) == 0)
+ {
+ Debug.Assert((ch & (SupplimentarySeq | ThreeByteSeq)) != 0,
"[UTF8Encoding.GetChars]Invariant volation");
- if ((ch & SupplimentarySeq) != 0) {
- if ((ch & (FinalByte >> 6)) != 0) {
+ 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)) {
+ if (!InRange(ch & 0x1F0, 0x10, 0x100))
+ {
goto InvalidByteSequence;
}
}
- else {
+ 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
+ (ch & (0xF800 >> 6)) == (0xD800 >> 6)) // illegal individually encoded surrogate
{
goto InvalidByteSequence;
}
@@ -1102,7 +1178,8 @@ namespace System.Text
// ready to punch
// adjust for surrogates in non-shortest form
- if ((ch & (SupplimentarySeq | 0x1F0000)) == SupplimentarySeq) {
+ if ((ch & (SupplimentarySeq | 0x1F0000)) == SupplimentarySeq)
+ {
charCount--;
}
goto EncodeChar;
@@ -1128,60 +1205,68 @@ namespace System.Text
pSrc++;
ProcessChar:
- if (ch > 0x7F) {
+ 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) {
+ if ((ch & 0x40) == 0)
+ {
// Unexpected trail byte
goto InvalidByteSequence;
}
// start a new long code
- if ((ch & 0x20) != 0) {
- if ((ch & 0x10) != 0) {
+ 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) {
+ 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
+ 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
+ (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);
+ (SupplimentarySeq >> 2 * 6) | (SupplimentarySeq >> 3 * 6);
// Our character count will be 2 characters for these 4 bytes, so subtract another char
charCount--;
}
- else {
+ 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) );
+ 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 {
+ else
+ {
// 2 byte encoding
ch &= 0x1F;
// check for non-shortest form
- if (ch <= 1) {
+ if (ch <= 1)
+ {
ch |= 0xc0;
goto InvalidByteSequence;
}
@@ -1198,10 +1283,12 @@ namespace System.Text
int availableBytes = PtrDiff(pEnd, pSrc);
// don't fall into the fast decoding loop if we don't have enough bytes
- if (availableBytes <= 13) {
+ 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) {
+ while (pSrc < pLocalEnd)
+ {
ch = *pSrc;
pSrc++;
@@ -1216,39 +1303,47 @@ namespace System.Text
// 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;
+ byte* pStop = pSrc + availableBytes - 7;
- while (pSrc < pStop) {
+ while (pSrc < pStop)
+ {
ch = *pSrc;
pSrc++;
- if (ch > 0x7F) {
+ if (ch > 0x7F)
+ {
goto LongCode;
}
// get pSrc 2-byte aligned
- if ((unchecked((int)pSrc) & 0x1) != 0) {
+ if ((unchecked((int)pSrc) & 0x1) != 0)
+ {
ch = *pSrc;
pSrc++;
- if (ch > 0x7F) {
+ if (ch > 0x7F)
+ {
goto LongCode;
}
}
// get pSrc 4-byte aligned
- if ((unchecked((int)pSrc) & 0x2) != 0) {
+ if ((unchecked((int)pSrc) & 0x2) != 0)
+ {
ch = *(ushort*)pSrc;
- if ((ch & 0x8080) != 0) {
+ if ((ch & 0x8080) != 0)
+ {
goto LongCodeWithMask16;
}
pSrc += 2;
}
// Run 8 + 8 characters at a time!
- while (pSrc < pStop) {
+ while (pSrc < pStop)
+ {
ch = *(int*)pSrc;
- int chb = *(int*)(pSrc+4);
- if (((ch | chb) & unchecked((int)0x80808080)) != 0) {
+ int chb = *(int*)(pSrc + 4);
+ if (((ch | chb) & unchecked((int)0x80808080)) != 0)
+ {
goto LongCodeWithMask32;
}
pSrc += 8;
@@ -1258,8 +1353,9 @@ namespace System.Text
break;
ch = *(int*)pSrc;
- chb = *(int*)(pSrc+4);
- if (((ch | chb) & unchecked((int)0x80808080)) != 0) {
+ chb = *(int*)(pSrc + 4);
+ if (((ch | chb) & unchecked((int)0x80808080)) != 0)
+ {
goto LongCodeWithMask32;
}
pSrc += 8;
@@ -1278,7 +1374,8 @@ namespace System.Text
ch &= 0xFF;
#endif // BIGENDIAN
pSrc++;
- if (ch <= 0x7F) {
+ if (ch <= 0x7F)
+ {
continue;
}
@@ -1298,12 +1395,13 @@ namespace System.Text
chc &= 0x3F;
// start a new long code
- if ((ch & 0x20) != 0) {
-
+ if ((ch & 0x20) != 0)
+ {
// fold the first two bytes together
chc |= (ch & 0x0F) << 6;
- if ((ch & 0x10) != 0) {
+ if ((ch & 0x10) != 0)
+ {
// 4 byte encoding - surrogate
ch = *pSrc;
if (
@@ -1311,16 +1409,17 @@ namespace System.Text
// 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 )
+ (ch & unchecked((sbyte)0xC0)) != 0x80)
{
goto BadLongCode;
}
chc = (chc << 6) | (ch & 0x3F);
- ch = *(pSrc+1);
+ ch = *(pSrc + 1);
// we are expecting to see trailing bytes like 10vvvvvv
- if ((ch & unchecked((sbyte)0xC0)) != 0x80) {
+ if ((ch & unchecked((sbyte)0xC0)) != 0x80)
+ {
goto BadLongCode;
}
pSrc += 2;
@@ -1328,16 +1427,17 @@ namespace System.Text
// extra byte
charCount--;
}
- else {
+ 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) ||
+ (chc & (0xF800 >> 6)) == (0xD800 >> 6) ||
// we are expecting to see trailing bytes like 10vvvvvv
- (ch & unchecked((sbyte)0xC0)) != 0x80 )
+ (ch & unchecked((sbyte)0xC0)) != 0x80)
{
goto BadLongCode;
}
@@ -1347,11 +1447,13 @@ namespace System.Text
charCount--;
}
}
- else {
+ else
+ {
// 2 byte encoding
// check for non-shortest form
- if ((ch & 0x1E) == 0) {
+ if ((ch & 0x1E) == 0)
+ {
goto BadLongCode;
}
}
@@ -1412,21 +1514,22 @@ namespace System.Text
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");
+ 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* pSrc = bytes;
+ char* pTarget = chars;
- byte *pEnd = pSrc+byteCount;
- char *pAllocatedBufferEnd = pTarget+charCount;
+ byte* pEnd = pSrc + byteCount;
+ char* pAllocatedBufferEnd = pTarget + charCount;
int ch = 0;
DecoderFallbackBuffer fallback = null;
- if (baseDecoder != null) {
+ if (baseDecoder != null)
+ {
UTF8Decoder decoder = (UTF8Decoder)baseDecoder;
ch = decoder.bits;
@@ -1440,11 +1543,13 @@ namespace System.Text
{
// SLOWLOOP: does all range checks, handles all special cases, but it is slow
- if (pSrc >= pEnd) {
+ if (pSrc >= pEnd)
+ {
break;
}
- if (ch == 0) {
+ if (ch == 0)
+ {
// no pending bits
goto ReadChar;
}
@@ -1455,7 +1560,8 @@ namespace System.Text
pSrc++;
// we are expecting to see trailing bytes like 10vvvvvv
- if ((cha & unchecked((sbyte)0xC0)) != 0x80) {
+ 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--;
@@ -1465,14 +1571,17 @@ namespace System.Text
// fold in the new byte
ch = (ch << 6) | (cha & 0x3F);
- if ((ch & FinalByte) == 0) {
+ if ((ch & FinalByte) == 0)
+ {
// Not at last byte yet
- Debug.Assert( (ch & (SupplimentarySeq | ThreeByteSeq)) != 0,
+ Debug.Assert((ch & (SupplimentarySeq | ThreeByteSeq)) != 0,
"[UTF8Encoding.GetChars]Invariant volation");
- if ((ch & SupplimentarySeq) != 0) {
+ if ((ch & SupplimentarySeq) != 0)
+ {
// Its a 4-byte supplimentary sequence
- if ((ch & (FinalByte >> 6)) != 0) {
+ if ((ch & (FinalByte >> 6)) != 0)
+ {
// this is 3rd byte of 4 byte sequence - nothing to do
continue;
}
@@ -1480,15 +1589,17 @@ namespace System.Text
// 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)) {
+ if (!InRange(ch & 0x1F0, 0x10, 0x100))
+ {
goto InvalidByteSequence;
}
}
- else {
+ 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
+ (ch & (0xF800 >> 6)) == (0xD800 >> 6)) // illegal individually encoded surrogate
{
goto InvalidByteSequence;
}
@@ -1500,11 +1611,13 @@ namespace System.Text
// 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) {
+ 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)))) );
+ if (pTarget < pAllocatedBufferEnd)
+ {
+ *pTarget = (char)(((ch >> 10) & 0x7FF) +
+ unchecked((short)((CharUnicodeInfo.HIGH_SURROGATE_START - (0x10000 >> 10)))));
pTarget++;
ch = (ch & 0x3FF) +
@@ -1537,7 +1650,7 @@ namespace System.Text
ch = 0;
break;
}
- Debug.Assert(pSrc >= bytes,
+ Debug.Assert(pSrc >= bytes,
"[UTF8Encoding.GetChars]Expected invalid byte sequence to have remained within the byte array");
ch = 0;
continue;
@@ -1547,45 +1660,53 @@ namespace System.Text
pSrc++;
ProcessChar:
- if (ch > 0x7F) {
+ 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) {
+ if ((ch & 0x40) == 0)
+ {
goto InvalidByteSequence;
}
// start a new long code
- if ((ch & 0x20) != 0) {
- if ((ch & 0x10) != 0) {
+ 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) {
+ if (ch > 0x04)
+ {
ch |= 0xf0;
goto InvalidByteSequence;
}
- ch |= (FinalByte >> 3*6) | (1 << 30) | (3 << (30-2*6)) |
+ ch |= (FinalByte >> 3 * 6) | (1 << 30) | (3 << (30 - 2 * 6)) |
(SupplimentarySeq) | (SupplimentarySeq >> 6) |
- (SupplimentarySeq >> 2*6) | (SupplimentarySeq >> 3*6);
+ (SupplimentarySeq >> 2 * 6) | (SupplimentarySeq >> 3 * 6);
}
- else {
+ else
+ {
// 3 byte encoding
- ch = (ch & 0x0F) | ( (FinalByte >> 2*6) | (1 << 30) |
- (ThreeByteSeq) | (ThreeByteSeq >> 6) | (ThreeByteSeq >> 2*6) );
+ ch = (ch & 0x0F) | ((FinalByte >> 2 * 6) | (1 << 30) |
+ (ThreeByteSeq) | (ThreeByteSeq >> 6) | (ThreeByteSeq >> 2 * 6));
}
}
- else {
+ else
+ {
// 2 byte encoding
ch &= 0x1F;
// check for non-shortest form
- if (ch <= 1) {
+ if (ch <= 1)
+ {
ch |= 0xc0;
goto InvalidByteSequence;
}
@@ -1642,9 +1763,11 @@ namespace System.Text
// 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) {
+ if (availableBytes <= 13)
+ {
// we may need as many as 1 character per byte
- if (availableChars < availableBytes) {
+ if (availableChars < availableBytes)
+ {
// not enough output room. no pending bits at this point
ch = 0;
continue;
@@ -1652,7 +1775,8 @@ namespace System.Text
// try to get over the remainder of the ascii characters fast though
byte* pLocalEnd = pEnd; // hint to get pLocalEnd enregistered
- while (pSrc < pLocalEnd) {
+ while (pSrc < pLocalEnd)
+ {
ch = *pSrc;
pSrc++;
@@ -1669,30 +1793,35 @@ namespace System.Text
// 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) {
+ 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;
+ char* pStop = pTarget + availableBytes - 7;
- while (pTarget < pStop) {
+ while (pTarget < pStop)
+ {
ch = *pSrc;
pSrc++;
- if (ch > 0x7F) {
+ if (ch > 0x7F)
+ {
goto LongCode;
}
*pTarget = (char)ch;
pTarget++;
// get pSrc to be 2-byte aligned
- if ((unchecked((int)pSrc) & 0x1) != 0) {
+ if ((unchecked((int)pSrc) & 0x1) != 0)
+ {
ch = *pSrc;
pSrc++;
- if (ch > 0x7F) {
+ if (ch > 0x7F)
+ {
goto LongCode;
}
*pTarget = (char)ch;
@@ -1700,9 +1829,11 @@ namespace System.Text
}
// get pSrc to be 4-byte aligned
- if ((unchecked((int)pSrc) & 0x2) != 0) {
+ if ((unchecked((int)pSrc) & 0x2) != 0)
+ {
ch = *(ushort*)pSrc;
- if ((ch & 0x8080) != 0) {
+ if ((ch & 0x8080) != 0)
+ {
goto LongCodeWithMask16;
}
@@ -1715,16 +1846,18 @@ namespace System.Text
#else // BIGENDIAN
*pTarget = (char)(ch & 0x7F);
pSrc += 2;
- *(pTarget+1) = (char)((ch >> 8) & 0x7F);
+ *(pTarget + 1) = (char)((ch >> 8) & 0x7F);
pTarget += 2;
#endif // BIGENDIAN
}
// Run 8 characters at a time!
- while (pTarget < pStop) {
+ while (pTarget < pStop)
+ {
ch = *(int*)pSrc;
- int chb = *(int*)(pSrc+4);
- if (((ch | chb) & unchecked((int)0x80808080)) != 0) {
+ int chb = *(int*)(pSrc + 4);
+ if (((ch | chb) & unchecked((int)0x80808080)) != 0)
+ {
goto LongCodeWithMask32;
}
@@ -1742,14 +1875,14 @@ namespace System.Text
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);
+ *(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 + 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
}
@@ -1767,7 +1900,8 @@ namespace System.Text
ch &= 0xFF;
#endif // BIGENDIAN
pSrc++;
- if (ch <= 0x7F) {
+ if (ch <= 0x7F)
+ {
*pTarget = (char)ch;
pTarget++;
continue;
@@ -1789,12 +1923,13 @@ namespace System.Text
chc &= 0x3F;
// start a new long code
- if ((ch & 0x20) != 0) {
-
+ if ((ch & 0x20) != 0)
+ {
// fold the first two bytes together
chc |= (ch & 0x0F) << 6;
- if ((ch & 0x10) != 0) {
+ if ((ch & 0x10) != 0)
+ {
// 4 byte encoding - surrogate
ch = *pSrc;
if (
@@ -1802,24 +1937,25 @@ namespace System.Text
// 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 )
+ (ch & unchecked((sbyte)0xC0)) != 0x80)
{
goto BadLongCode;
}
chc = (chc << 6) | (ch & 0x3F);
- ch = *(pSrc+1);
+ ch = *(pSrc + 1);
// we are expecting to see trailing bytes like 10vvvvvv
- if ((ch & unchecked((sbyte)0xC0)) != 0x80) {
+ 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 = (char)(((ch >> 10) & 0x7FF) +
+ unchecked((short)(CharUnicodeInfo.HIGH_SURROGATE_START - (0x10000 >> 10))));
pTarget++;
ch = (ch & 0x3FF) +
@@ -1831,16 +1967,17 @@ namespace System.Text
// one here and one below.
pStop--;
}
- else {
+ 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) ||
+ (chc & (0xF800 >> 6)) == (0xD800 >> 6) ||
// we are expecting to see trailing bytes like 10vvvvvv
- (ch & unchecked((sbyte)0xC0)) != 0x80 )
+ (ch & unchecked((sbyte)0xC0)) != 0x80)
{
goto BadLongCode;
}
@@ -1855,13 +1992,15 @@ namespace System.Text
pStop--;
}
}
- else {
+ else
+ {
// 2 byte encoding
ch &= 0x1F;
// check for non-shortest form
- if (ch <= 1) {
+ if (ch <= 1)
+ {
goto BadLongCode;
}
ch = (ch << 6) | chc;
@@ -1912,8 +2051,8 @@ namespace System.Text
fallback.InternalReset();
ThrowCharsOverflow(baseDecoder, pTarget == chars);
}
- Debug.Assert(pSrc >= bytes,
- "[UTF8Encoding.GetChars]Expected flushing invalid byte sequence to have remained within the byte array");
+ Debug.Assert(pSrc >= bytes,
+ "[UTF8Encoding.GetChars]Expected flushing invalid byte sequence to have remained within the byte array");
ch = 0;
}
@@ -1947,7 +2086,7 @@ namespace System.Text
ref byte* pSrc, int ch, DecoderFallbackBuffer fallback, ref char* pTarget)
{
// Get our byte[]
- byte *pStart = pSrc;
+ byte* pStart = pSrc;
byte[] bytesUnknown = GetBytesUnknown(ref pStart, ch);
// Do the actual fallback
@@ -1999,7 +2138,7 @@ namespace System.Text
else if ((ch & (SupplimentarySeq | ThreeByteSeq)) == 0)
{
pSrc--;
- bytesUnknown = new byte[] { unchecked((byte)((ch & 0x1F )| 0xc0)) };
+ 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
@@ -2010,7 +2149,7 @@ namespace System.Text
if ((ch & (FinalByte >> 6)) != 0)
{
// 3rd byte of 4 byte sequence
- pSrc-=3;
+ pSrc -= 3;
bytesUnknown = new byte[] {
unchecked((byte)(((ch >> 12) & 0x07) | 0xF0)),
unchecked((byte)(((ch >> 6) & 0x3F) | 0x80)),
@@ -2019,7 +2158,7 @@ namespace System.Text
else if ((ch & (FinalByte >> 12)) != 0)
{
// 2nd byte of a 4 byte sequence
- pSrc-=2;
+ pSrc -= 2;
bytesUnknown = new byte[] {
unchecked((byte)(((ch >> 6) & 0x07) | 0xF0)),
unchecked((byte)(((ch) & 0x3F) | 0x80)) };
@@ -2028,7 +2167,7 @@ namespace System.Text
{
// 4th byte of a 4 byte sequence
pSrc--;
- bytesUnknown = new byte[] { unchecked((byte)(((ch) & 0x07) | 0xF0))};
+ bytesUnknown = new byte[] { unchecked((byte)(((ch) & 0x07) | 0xF0)) };
}
}
else
@@ -2037,7 +2176,7 @@ namespace System.Text
if ((ch & (FinalByte >> 6)) != 0)
{
// So its 2nd byte of a 3 byte sequence
- pSrc-=2;
+ pSrc -= 2;
bytesUnknown = new byte[] {
unchecked((byte)(((ch >> 6) & 0x0F) | 0xE0)), unchecked ((byte)(((ch) & 0x3F) | 0x80)) };
}
@@ -2045,7 +2184,7 @@ namespace System.Text
{
// 1st byte of a 3 byte sequence
pSrc--;
- bytesUnknown = new byte[] { unchecked((byte)(((ch) & 0x0F) | 0xE0))};
+ bytesUnknown = new byte[] { unchecked((byte)(((ch) & 0x0F) | 0xE0)) };
}
}
@@ -2053,12 +2192,14 @@ namespace System.Text
}
- public override Decoder GetDecoder() {
+ public override Decoder GetDecoder()
+ {
return new UTF8Decoder(this);
}
- public override Encoder GetEncoder() {
+ public override Encoder GetEncoder()
+ {
return new UTF8Encoder(this);
}
@@ -2066,8 +2207,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),
+ Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
// Characters would be # of characters + 1 in case left over high surrogate is ? * max fallback
@@ -2089,8 +2230,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),
+ 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
@@ -2112,7 +2253,8 @@ namespace System.Text
public override byte[] GetPreamble()
{
- if (emitUTF8Identifier) {
+ if (emitUTF8Identifier)
+ {
// Allocate new array to prevent users from modifying it.
return new byte[3] { 0xEF, 0xBB, 0xBF };
}
@@ -2121,11 +2263,13 @@ namespace System.Text
}
- public override bool Equals(Object value) {
+ public override bool Equals(Object value)
+ {
UTF8Encoding that = value as UTF8Encoding;
- if (that != null) {
+ if (that != null)
+ {
return (emitUTF8Identifier == that.emitUTF8Identifier) &&
-// (isThrowException == that.isThrowException) && // Same as encoder/decoderfallbacks being exception
+ // (isThrowException == that.isThrowException) && // Same as encoder/decoderfallbacks being exception
(EncoderFallback.Equals(that.EncoderFallback)) &&
(DecoderFallback.Equals(that.DecoderFallback));
}
@@ -2133,10 +2277,11 @@ namespace System.Text
}
- public override int GetHashCode() {
+ 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);
+ UTF8_CODEPAGE + (emitUTF8Identifier ? 1 : 0);
}
[Serializable]
@@ -2155,7 +2300,7 @@ namespace System.Text
internal UTF8Encoder(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
@@ -2164,10 +2309,10 @@ namespace System.Text
// SurrogateChar happens to mean the same thing
this.surrogateChar = (int)info.GetValue("surrogateChar", typeof(int));
- try
+ try
{
- this.m_fallback = (EncoderFallback) info.GetValue("m_fallback", typeof(EncoderFallback));
- }
+ this.m_fallback = (EncoderFallback)info.GetValue("m_fallback", typeof(EncoderFallback));
+ }
catch (SerializationException)
{
this.m_fallback = null;
@@ -2178,7 +2323,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
@@ -2198,7 +2343,7 @@ namespace System.Text
{
this.surrogateChar = 0;
if (m_fallbackBuffer != null)
- m_fallbackBuffer.Reset();
+ m_fallbackBuffer.Reset();
}
// Anything left in our encoder?
@@ -2227,7 +2372,7 @@ namespace System.Text
internal UTF8Decoder(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
@@ -2237,7 +2382,7 @@ namespace System.Text
{
// Get whidbey version of bits
this.bits = (int)info.GetValue("wbits", typeof(int));
- this.m_fallback = (DecoderFallback) info.GetValue("m_fallback", typeof(DecoderFallback));
+ this.m_fallback = (DecoderFallback)info.GetValue("m_fallback", typeof(DecoderFallback));
}
catch (SerializationException)
{
@@ -2251,13 +2396,13 @@ 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 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);
+ 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);
diff --git a/src/mscorlib/src/System/Text/UnicodeEncoding.cs b/src/mscorlib/src/System/Text/UnicodeEncoding.cs
index d8ef18ab05..fb667ba2b2 100644
--- a/src/mscorlib/src/System/Text/UnicodeEncoding.cs
+++ b/src/mscorlib/src/System/Text/UnicodeEncoding.cs
@@ -25,7 +25,7 @@ namespace System.Text
[OptionalField(VersionAdded = 2)]
internal bool isThrowException = false;
-
+
internal bool bigEndian = false;
internal bool byteOrderMark = true;
@@ -57,14 +57,14 @@ namespace System.Text
SetDefaultFallbacks();
}
-#region Serialization
+ #region Serialization
[OnDeserializing]
private void OnDeserializing(StreamingContext ctx)
{
// In Everett it is false. Whidbey will overwrite this value.
isThrowException = false;
- }
-#endregion Serialization
+ }
+ #endregion Serialization
internal override void SetDefaultFallbacks()
{
@@ -174,12 +174,12 @@ namespace System.Text
{
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(chars != null, "[UnicodeEncoding.GetByteCount]chars!=null");
Debug.Assert(count >= 0, "[UnicodeEncoding.GetByteCount]count >=0");
// Start by assuming each char gets 2 bytes
@@ -193,7 +193,7 @@ namespace System.Text
char* charStart = chars;
char* charEnd = chars + count;
- char charLeftOver = (char)0;
+ char charLeftOver = (char)0;
bool wasHereBefore = false;
@@ -211,7 +211,7 @@ namespace System.Text
// Assume extra bytes to encode charLeftOver if it existed
if (charLeftOver > 0)
- byteCount+=2;
+ byteCount += 2;
// We mustn't have left over fallback data when counting
if (encoder.InternalHasFallbackBuffer)
@@ -227,9 +227,9 @@ namespace System.Text
}
char ch;
- TryAgain:
+ TryAgain:
- while (((ch = (fallbackBuffer == null) ? (char)0 :fallbackBuffer.InternalGetNextChar()) != 0) || chars < charEnd)
+ while (((ch = (fallbackBuffer == null) ? (char)0 : fallbackBuffer.InternalGetNextChar()) != 0) || chars < charEnd)
{
// First unwind any fallback
if (ch == 0)
@@ -239,7 +239,7 @@ namespace System.Text
#if BIGENDIAN // If endianess is backwards then each pair of bytes would be backwards.
if ( bigEndian &&
#else
- if ( !bigEndian &&
+ if (!bigEndian &&
#endif // BIGENDIAN
#if BIT64 // 64 bit CPU needs to be long aligned for this to work.
@@ -314,7 +314,7 @@ namespace System.Text
else
{
// We weren't preallocating fallback space.
- byteCount+=2;
+ byteCount += 2;
}
// Check for high or low surrogates
@@ -329,7 +329,7 @@ namespace System.Text
// 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,
+ Debug.Assert(chars > charStart,
"[UnicodeEncoding.GetByteCount]Expected chars to have advanced in unexpected high surrogate");
chars--;
@@ -396,7 +396,7 @@ namespace System.Text
// 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,
+ Debug.Assert(chars > charStart,
"[UnicodeEncoding.GetByteCount]Expected chars to have advanced when expected low surrogate");
chars--;
@@ -415,7 +415,7 @@ namespace System.Text
fallbackBuffer.InternalFallback(charLeftOver, ref chars);
// Ignore charLeftOver or throw
- byteCount-=2;
+ byteCount -= 2;
charLeftOver = (char)0;
continue;
@@ -472,10 +472,10 @@ namespace System.Text
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");
+ 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;
@@ -509,7 +509,7 @@ namespace System.Text
}
}
- TryAgain:
+ TryAgain:
while (((ch = (fallbackBuffer == null) ?
(char)0 : fallbackBuffer.InternalGetNextChar()) != 0) ||
chars < charEnd)
@@ -522,7 +522,7 @@ namespace System.Text
#if BIGENDIAN // If endianess is backwards then each pair of bytes would be backwards.
if ( bigEndian &&
#else
- if ( !bigEndian &&
+ 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 &&
@@ -615,7 +615,7 @@ namespace System.Text
#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 )
+ (unchecked((int)(bytes)) & 1) == 0)
{
// # to use
long iCount = ((byteEnd - bytes) >> 1 < charEnd - chars) ?
@@ -634,13 +634,13 @@ namespace System.Text
break;
// break if next one's not a low surrogate (will do fallback)
- if (*(chars+1) < 0xdc00 || *(chars+1) > 0xdfff)
+ 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)
+ else if (*(chars + 1) >= (char)0xd800 && *(chars + 1) <= 0xdfff)
{
*charOut = *chars;
charOut++;
@@ -649,13 +649,12 @@ namespace System.Text
}
*charOut = *chars;
- *(charOut+1) = *(chars+1);
- charOut+=2;
- chars+=2;
-
+ *(charOut + 1) = *(chars + 1);
+ charOut += 2;
+ chars += 2;
}
- bytes=(byte*)charOut;
+ bytes = (byte*)charOut;
if (chars >= charEnd)
break;
@@ -679,10 +678,10 @@ namespace System.Text
// 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,
+ 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)
@@ -707,7 +706,7 @@ namespace System.Text
continue;
}
- // Its a low surrogate
+ // Its a low surrogate
if (charLeftOver == 0)
{
// We'll fall back this one
@@ -745,9 +744,9 @@ namespace System.Text
{
// 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,
+ 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
+ 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
@@ -774,7 +773,7 @@ namespace System.Text
// 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,
+ Debug.Assert(chars > charStart,
"[UnicodeEncoding.GetBytes]Expected chars to have advanced after expecting low surrogate");
chars--;
@@ -808,8 +807,8 @@ namespace System.Text
{
// 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");
+ 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)
@@ -851,11 +850,11 @@ namespace System.Text
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);
@@ -864,7 +863,6 @@ namespace System.Text
goto TryAgain;
}
}
-
}
// Not flushing, remember it in the encoder
@@ -891,7 +889,7 @@ namespace System.Text
internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder)
{
- Debug.Assert(bytes!=null, "[UnicodeEncoding.GetCharCount]bytes!=null");
+ Debug.Assert(bytes != null, "[UnicodeEncoding.GetCharCount]bytes!=null");
Debug.Assert(count >= 0, "[UnicodeEncoding.GetCharCount]count >=0");
UnicodeEncoding.Decoder decoder = (UnicodeEncoding.Decoder)baseDecoder;
@@ -1052,9 +1050,8 @@ namespace System.Text
}
else
{
- byteBuffer = new byte[]
- { unchecked((byte)lastChar), unchecked((byte)(lastChar >> 8)) };
-
+ byteBuffer = new byte[]
+ { unchecked((byte)lastChar), unchecked((byte)(lastChar >> 8)) };
}
if (fallbackBuffer == null)
@@ -1094,9 +1091,8 @@ namespace System.Text
}
else
{
- byteBuffer = new byte[]
- { unchecked((byte)ch), unchecked((byte)(ch >> 8)) };
-
+ byteBuffer = new byte[]
+ { unchecked((byte)ch), unchecked((byte)(ch >> 8)) };
}
if (fallbackBuffer == null)
@@ -1134,9 +1130,8 @@ namespace System.Text
}
else
{
- byteBuffer = new byte[]
- { unchecked((byte)lastChar), unchecked((byte)(lastChar >> 8)) };
-
+ byteBuffer = new byte[]
+ { unchecked((byte)lastChar), unchecked((byte)(lastChar >> 8)) };
}
if (fallbackBuffer == null)
@@ -1175,9 +1170,8 @@ namespace System.Text
}
else
{
- byteBuffer = new byte[]
- { unchecked((byte)lastChar), unchecked((byte)(lastChar >> 8)) };
-
+ byteBuffer = new byte[]
+ { unchecked((byte)lastChar), unchecked((byte)(lastChar >> 8)) };
}
if (fallbackBuffer == null)
@@ -1210,7 +1204,7 @@ namespace System.Text
}
// No hanging odd bytes allowed if must flush
- charCount += fallbackBuffer.InternalFallback( new byte[] { unchecked((byte)lastByte) }, bytes);
+ charCount += fallbackBuffer.InternalFallback(new byte[] { unchecked((byte)lastByte) }, bytes);
lastByte = -1;
}
}
@@ -1228,12 +1222,12 @@ namespace System.Text
}
internal override unsafe int GetChars(byte* bytes, int byteCount,
- char* chars, int charCount, DecoderNLS baseDecoder )
+ 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");
+ 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;
@@ -1387,9 +1381,8 @@ namespace System.Text
}
else
{
- byteBuffer = new byte[]
- { unchecked((byte)lastChar), unchecked((byte)(lastChar >> 8)) };
-
+ byteBuffer = new byte[]
+ { unchecked((byte)lastChar), unchecked((byte)(lastChar >> 8)) };
}
if (fallbackBuffer == null)
@@ -1409,7 +1402,7 @@ namespace System.Text
// 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
+ 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
@@ -1436,9 +1429,8 @@ namespace System.Text
}
else
{
- byteBuffer = new byte[]
- { unchecked((byte)ch), unchecked((byte)(ch >> 8)) };
-
+ byteBuffer = new byte[]
+ { unchecked((byte)ch), unchecked((byte)(ch >> 8)) };
}
if (fallbackBuffer == null)
@@ -1458,7 +1450,7 @@ namespace System.Text
// 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
+ 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
@@ -1475,7 +1467,7 @@ namespace System.Text
// 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
+ 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
@@ -1495,9 +1487,8 @@ namespace System.Text
}
else
{
- byteBuffer = new byte[]
- { unchecked((byte)lastChar), unchecked((byte)(lastChar >> 8)) };
-
+ byteBuffer = new byte[]
+ { unchecked((byte)lastChar), unchecked((byte)(lastChar >> 8)) };
}
if (fallbackBuffer == null)
@@ -1517,7 +1508,7 @@ namespace System.Text
// 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
+ 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
@@ -1534,7 +1525,7 @@ namespace System.Text
// 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
+ 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
}
@@ -1557,9 +1548,8 @@ namespace System.Text
}
else
{
- byteBuffer = new byte[]
- { unchecked((byte)lastChar), unchecked((byte)(lastChar >> 8)) };
-
+ byteBuffer = new byte[]
+ { unchecked((byte)lastChar), unchecked((byte)(lastChar >> 8)) };
}
if (fallbackBuffer == null)
@@ -1579,13 +1569,13 @@ namespace System.Text
// 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
+ 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;
+ bytes += 2;
if (lastByte >= 0)
bytes++;
goto End;
@@ -1609,7 +1599,7 @@ namespace System.Text
}
// No hanging odd bytes allowed if must flush
- if (!fallbackBuffer.InternalFallback( new byte[] { unchecked((byte)lastByte) }, bytes, ref chars ))
+ if (!fallbackBuffer.InternalFallback(new byte[] { unchecked((byte)lastByte) }, bytes, ref chars))
{
// odd byte couldn't fall back
bytes--; // didn't use this byte
@@ -1625,14 +1615,14 @@ namespace System.Text
}
}
- End:
+ 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")
+ // + " " + ((int)lastChar).ToString("X4") + " " + lastByte.ToString("X2")
);
decoder.m_bytesUsed = (int)(bytes - byteStart);
@@ -1682,8 +1672,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),
+ Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
// Characters would be # of characters + 1 in case left over high surrogate is ? * max fallback
@@ -1705,8 +1695,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),
+ Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
// long because byteCount could be biggest int.
@@ -1737,7 +1727,7 @@ namespace System.Text
//
return (CodePage == that.CodePage) &&
byteOrderMark == that.byteOrderMark &&
-// isThrowException == that.isThrowException && // Same as Encoder/Decoder being exception fallbacks
+ // isThrowException == that.isThrowException && // Same as Encoder/Decoder being exception fallbacks
bigEndian == that.bigEndian &&
(EncoderFallback.Equals(that.EncoderFallback)) &&
(DecoderFallback.Equals(that.DecoderFallback));
@@ -1748,7 +1738,7 @@ namespace System.Text
public override int GetHashCode()
{
return CodePage + this.EncoderFallback.GetHashCode() + this.DecoderFallback.GetHashCode() +
- (byteOrderMark?4:0) + (bigEndian?8:0);
+ (byteOrderMark ? 4 : 0) + (bigEndian ? 8 : 0);
}
[Serializable]
@@ -1766,7 +1756,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
@@ -1791,7 +1781,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
diff --git a/src/mscorlib/src/System/Threading/AbandonedMutexException.cs b/src/mscorlib/src/System/Threading/AbandonedMutexException.cs
index 6b4977fbc5..b39cb208b8 100644
--- a/src/mscorlib/src/System/Threading/AbandonedMutexException.cs
+++ b/src/mscorlib/src/System/Threading/AbandonedMutexException.cs
@@ -9,77 +9,86 @@
// 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;
+using System;
+using System.Runtime.Serialization;
+using System.Threading;
+using System.Runtime.InteropServices;
+
+namespace System.Threading
+{
[Serializable]
[ComVisibleAttribute(false)]
- public class AbandonedMutexException : SystemException {
-
+ public class AbandonedMutexException : SystemException
+ {
private int m_MutexIndex = -1;
private Mutex m_Mutex = null;
- public AbandonedMutexException()
- : base(Environment.GetResourceString("Threading.AbandonedMutexException")) {
+ public AbandonedMutexException()
+ : base(Environment.GetResourceString("Threading.AbandonedMutexException"))
+ {
SetErrorCode(__HResults.COR_E_ABANDONEDMUTEX);
}
- public AbandonedMutexException(String message)
- : base(message) {
+ public AbandonedMutexException(String message)
+ : base(message)
+ {
SetErrorCode(__HResults.COR_E_ABANDONEDMUTEX);
}
- public AbandonedMutexException(String message, Exception inner )
- : base(message, inner) {
+ 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")) {
+ public AbandonedMutexException(int location, WaitHandle handle)
+ : base(Environment.GetResourceString("Threading.AbandonedMutexException"))
+ {
SetErrorCode(__HResults.COR_E_ABANDONEDMUTEX);
- SetupException(location,handle);
+ SetupException(location, handle);
}
-
- public AbandonedMutexException(String message,int location, WaitHandle handle)
- : base(message) {
+
+ public AbandonedMutexException(String message, int location, WaitHandle handle)
+ : base(message)
+ {
SetErrorCode(__HResults.COR_E_ABANDONEDMUTEX);
- SetupException(location,handle);
+ SetupException(location, handle);
}
- public AbandonedMutexException(String message, Exception inner,int location, WaitHandle handle )
- : base(message, inner) {
+ public AbandonedMutexException(String message, Exception inner, int location, WaitHandle handle)
+ : base(message, inner)
+ {
SetErrorCode(__HResults.COR_E_ABANDONEDMUTEX);
- SetupException(location,handle);
+ SetupException(location, handle);
}
private void SetupException(int location, WaitHandle handle)
{
m_MutexIndex = location;
- if(handle != null)
+ if (handle != null)
m_Mutex = handle as Mutex;
}
- protected AbandonedMutexException(SerializationInfo info, StreamingContext context) : base(info, context) {
+ protected AbandonedMutexException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
}
public Mutex Mutex
{
- get {
+ get
+ {
return m_Mutex;
}
}
public int MutexIndex
{
- get{
+ get
+ {
return m_MutexIndex;
}
}
-
}
}
-
+
diff --git a/src/mscorlib/src/System/Threading/ApartmentState.cs b/src/mscorlib/src/System/Threading/ApartmentState.cs
index 1edf0af98a..445d70f1c6 100644
--- a/src/mscorlib/src/System/Threading/ApartmentState.cs
+++ b/src/mscorlib/src/System/Threading/ApartmentState.cs
@@ -12,11 +12,11 @@
**
=============================================================================*/
-namespace System.Threading {
-
+namespace System.Threading
+{
[Serializable]
public enum ApartmentState
- {
+ {
/*=========================================================================
** Constants for thread apartment states.
=========================================================================*/
diff --git a/src/mscorlib/src/System/Threading/AsyncLocal.cs b/src/mscorlib/src/System/Threading/AsyncLocal.cs
index 8c4319bd2c..b1d90b3983 100644
--- a/src/mscorlib/src/System/Threading/AsyncLocal.cs
+++ b/src/mscorlib/src/System/Threading/AsyncLocal.cs
@@ -46,7 +46,7 @@ namespace System.Threading
//
// Constructs an AsyncLocal<T> that does not receive change notifications.
//
- public AsyncLocal()
+ public AsyncLocal()
{
}
@@ -54,21 +54,21 @@ namespace System.Threading
// Constructs an AsyncLocal<T> with a delegate that is called whenever the current value changes
// on any thread.
//
- public AsyncLocal(Action<AsyncLocalValueChangedArgs<T>> valueChangedHandler)
+ public AsyncLocal(Action<AsyncLocalValueChangedArgs<T>> valueChangedHandler)
{
m_valueChangedHandler = valueChangedHandler;
}
public T Value
{
- get
- {
+ get
+ {
object obj = ExecutionContext.GetLocalValue(this);
return (obj == null) ? default(T) : (T)obj;
}
- set
+ set
{
- ExecutionContext.SetLocalValue(this, value, m_valueChangedHandler != null);
+ ExecutionContext.SetLocalValue(this, value, m_valueChangedHandler != null);
}
}
@@ -93,7 +93,7 @@ namespace System.Threading
{
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.
@@ -114,7 +114,7 @@ namespace System.Threading
// 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
+ internal interface IAsyncLocalValueMap
{
bool TryGetValue(IAsyncLocal key, out object value);
IAsyncLocalValueMap Set(IAsyncLocal key, object value);
diff --git a/src/mscorlib/src/System/Threading/AutoResetEvent.cs b/src/mscorlib/src/System/Threading/AutoResetEvent.cs
index fc6b2301ca..41a012cf58 100644
--- a/src/mscorlib/src/System/Threading/AutoResetEvent.cs
+++ b/src/mscorlib/src/System/Threading/AutoResetEvent.cs
@@ -11,14 +11,15 @@
**
**
=============================================================================*/
-namespace System.Threading {
-
- using System;
- using System.Runtime.InteropServices;
+using System;
+using System.Runtime.InteropServices;
+
+namespace System.Threading
+{
public sealed class AutoResetEvent : EventWaitHandle
{
- public AutoResetEvent(bool initialState) : base(initialState,EventResetMode.AutoReset){ }
+ 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..4d8212044c 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();
}
@@ -479,7 +479,7 @@ namespace System.Threading
// -----------------------------------
// 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..eef3a15644 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);
@@ -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);
}
@@ -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/CountdownEvent.cs b/src/mscorlib/src/System/Threading/CountdownEvent.cs
index af055e347e..8a36a84dc3 100644
--- a/src/mscorlib/src/System/Threading/CountdownEvent.cs
+++ b/src/mscorlib/src/System/Threading/CountdownEvent.cs
@@ -18,7 +18,6 @@ using System.Diagnostics.Contracts;
namespace System.Threading
{
-
/// <summary>
/// Represents a synchronization primitive that is signaled when its count reaches zero.
/// </summary>
@@ -80,7 +79,7 @@ namespace System.Threading
/// </value>
public int CurrentCount
{
- get
+ get
{
int observedCount = m_currentCount;
return observedCount < 0 ? 0 : observedCount;
diff --git a/src/mscorlib/src/System/Threading/EventResetMode.cs b/src/mscorlib/src/System/Threading/EventResetMode.cs
index edafab9bb5..89bf7a769e 100644
--- a/src/mscorlib/src/System/Threading/EventResetMode.cs
+++ b/src/mscorlib/src/System/Threading/EventResetMode.cs
@@ -14,9 +14,10 @@
=============================================================================*/
+using System.Runtime.InteropServices;
+
namespace System.Threading
{
- using System.Runtime.InteropServices;
[ComVisibleAttribute(false)]
public enum EventResetMode
{
diff --git a/src/mscorlib/src/System/Threading/EventWaitHandle.cs b/src/mscorlib/src/System/Threading/EventWaitHandle.cs
index 0268948a5c..034c4b0ee6 100644
--- a/src/mscorlib/src/System/Threading/EventWaitHandle.cs
+++ b/src/mscorlib/src/System/Threading/EventWaitHandle.cs
@@ -39,11 +39,11 @@ 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"));
@@ -55,9 +55,9 @@ namespace System.Threading
#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(Environment.GetResourceString("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(Environment.GetResourceString("Threading.WaitHandleCannotBeOpenedException_InvalidHandle", name));
__Error.WinIOError(errorCode, name);
}
@@ -90,7 +90,7 @@ 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"));
@@ -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(Environment.GetResourceString("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(Environment.GetResourceString("Threading.WaitHandleCannotBeOpenedException_InvalidHandle", name));
__Error.WinIOError(errorCode, name);
}
@@ -180,16 +179,16 @@ namespace System.Threading
throw new ArgumentNullException(nameof(name), Environment.GetResourceString("ArgumentNull_WithParamName"));
}
- if(name.Length == 0)
+ if (name.Length == 0)
{
throw new ArgumentException(Environment.GetResourceString("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));
}
-
+
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
index 47a55a3bb9..1e9e9b4ef1 100644
--- a/src/mscorlib/src/System/Threading/ExecutionContext.cs
+++ b/src/mscorlib/src/System/Threading/ExecutionContext.cs
@@ -9,23 +9,24 @@
**
**
===========================================================*/
-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;
+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;
+
+namespace System.Threading
+{
public delegate void ContextCallback(Object state);
internal struct ExecutionContextSwitcher
@@ -42,7 +43,7 @@ namespace System.Threading
{
currentThread.SynchronizationContext = m_sc;
}
-
+
if (currentThread.ExecutionContext != m_ec)
{
ExecutionContext.Restore(currentThread, m_ec);
@@ -178,11 +179,11 @@ namespace System.Threading
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);
@@ -192,8 +193,8 @@ namespace System.Threading
static internal void EstablishCopyOnWriteScope(Thread currentThread, ref ExecutionContextSwitcher ecsw)
{
Debug.Assert(currentThread == Thread.CurrentThread);
-
- ecsw.m_ec = currentThread.ExecutionContext;
+
+ ecsw.m_ec = currentThread.ExecutionContext;
ecsw.m_sc = currentThread.SynchronizationContext;
}
@@ -203,7 +204,7 @@ namespace System.Threading
Debug.Assert(previous != null);
Debug.Assert(current != null);
Debug.Assert(previous != current);
-
+
foreach (IAsyncLocal local in previous.m_localChangeNotifications)
{
object previousValue;
@@ -237,10 +238,10 @@ namespace System.Threading
catch (Exception ex)
{
Environment.FailFast(
- Environment.GetResourceString("ExecutionContext_ExceptionInAsyncLocalNotification"),
+ Environment.GetResourceString("ExecutionContext_ExceptionInAsyncLocalNotification"),
ex);
}
- }
+ }
}
internal static object GetLocalValue(IAsyncLocal local)
diff --git a/src/mscorlib/src/System/Threading/Interlocked.cs b/src/mscorlib/src/System/Threading/Interlocked.cs
index 131d51a65b..578201e5a3 100644
--- a/src/mscorlib/src/System/Threading/Interlocked.cs
+++ b/src/mscorlib/src/System/Threading/Interlocked.cs
@@ -3,21 +3,22 @@
// 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;
+
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 +103,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 +143,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,22 +170,22 @@ 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);
}
diff --git a/src/mscorlib/src/System/Threading/LazyInitializer.cs b/src/mscorlib/src/System/Threading/LazyInitializer.cs
index af32673d03..82fb2579bb 100644
--- a/src/mscorlib/src/System/Threading/LazyInitializer.cs
+++ b/src/mscorlib/src/System/Threading/LazyInitializer.cs
@@ -13,9 +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>
@@ -241,11 +241,10 @@ namespace System.Threading
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);
diff --git a/src/mscorlib/src/System/Threading/LockRecursionException.cs b/src/mscorlib/src/System/Threading/LockRecursionException.cs
index 40f04b00b4..5624282a40 100644
--- a/src/mscorlib/src/System/Threading/LockRecursionException.cs
+++ b/src/mscorlib/src/System/Threading/LockRecursionException.cs
@@ -12,12 +12,12 @@
// support it in its current state.
============================================================*/
+using System;
+using System.Runtime.Serialization;
+using System.Runtime.CompilerServices;
+
namespace System.Threading
{
- using System;
- using System.Runtime.Serialization;
- using System.Runtime.CompilerServices;
-
[Serializable]
public class LockRecursionException : System.Exception
{
@@ -26,5 +26,4 @@ namespace System.Threading
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
index a8e012fb43..bb875c4f49 100644
--- a/src/mscorlib/src/System/Threading/ManualResetEvent.cs
+++ b/src/mscorlib/src/System/Threading/ManualResetEvent.cs
@@ -11,14 +11,15 @@
**
**
=============================================================================*/
-namespace System.Threading {
-
- using System;
- using System.Runtime.InteropServices;
+using System;
+using System.Runtime.InteropServices;
+
+namespace System.Threading
+{
public sealed class ManualResetEvent : EventWaitHandle
- {
- public ManualResetEvent(bool initialState) : base(initialState,EventResetMode.ManualReset){}
+ {
+ 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..c0bdbcece2 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();
@@ -169,7 +167,6 @@ namespace System.Threading
UpdateStateAtomically(value << NumWaitersState_ShiftCount, NumWaitersState_BitMask);
}
-
}
//-----------------------------------------------------------------------------------
@@ -184,7 +181,6 @@ namespace System.Threading
public ManualResetEventSlim()
: this(false)
{
-
}
/// <summary>
@@ -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)
-
}
}
}
diff --git a/src/mscorlib/src/System/Threading/Monitor.cs b/src/mscorlib/src/System/Threading/Monitor.cs
index fdbc384243..8cebe647bb 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
@@ -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
diff --git a/src/mscorlib/src/System/Threading/Mutex.cs b/src/mscorlib/src/System/Threading/Mutex.cs
index dcb821307a..cac423f6a8 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
{
@@ -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)
@@ -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
@@ -229,12 +233,12 @@ namespace System.Threading
throw new ArgumentNullException(nameof(name), Environment.GetResourceString("ArgumentNull_WithParamName"));
}
- if(name.Length == 0)
+ if (name.Length == 0)
{
throw new ArgumentException(Environment.GetResourceString("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));
}
@@ -262,7 +266,7 @@ namespace System.Threading
}
#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);
@@ -291,7 +295,7 @@ namespace System.Threading
}
}
- 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 fe55be73ea..8712c12c8f 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,11 +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;
+ 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)
{
@@ -75,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
@@ -93,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
{
@@ -108,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);
-
}
}
@@ -143,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()
{
@@ -165,7 +164,8 @@ namespace System.Threading
unsafe internal NativeOverlapped* Pack(IOCompletionCallback iocb, Object userData)
{
- if (!m_pinSelf.IsNull()) {
+ if (!m_pinSelf.IsNull())
+ {
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_Overlapped_Pack"));
}
@@ -195,8 +195,9 @@ namespace System.Threading
}
unsafe internal NativeOverlapped* UnsafePack(IOCompletionCallback iocb, Object userData)
- {
- if (!m_pinSelf.IsNull()) {
+ {
+ if (!m_pinSelf.IsNull())
+ {
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_Overlapped_Pack"));
}
m_userObject = userData;
@@ -221,7 +222,7 @@ namespace System.Threading
get { return m_nativeOverlapped.EventHandle; }
set { m_nativeOverlapped.EventHandle = value; }
}
-
+
[MethodImplAttribute(MethodImplOptions.InternalCall)]
unsafe private extern NativeOverlapped* AllocateNativeOverlapped();
@@ -229,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,17 +245,17 @@ namespace System.Threading
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;
@@ -317,7 +318,7 @@ namespace System.Threading
[CLSCompliant(false)]
unsafe public NativeOverlapped* Pack(IOCompletionCallback iocb)
{
- return Pack (iocb, null);
+ return Pack(iocb, null);
}
[CLSCompliant(false)]
@@ -330,12 +331,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);
}
@@ -351,7 +352,7 @@ namespace System.Threading
Contract.EndContractBlock();
Overlapped overlapped = OverlappedData.GetOverlappedFromNative(nativeOverlappedPtr).m_overlapped;
-
+
return overlapped;
}
@@ -369,9 +370,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
index 32b63153c4..74f17a5d75 100644
--- a/src/mscorlib/src/System/Threading/ParameterizedThreadStart.cs
+++ b/src/mscorlib/src/System/Threading/ParameterizedThreadStart.cs
@@ -14,10 +14,11 @@
=============================================================================*/
-namespace System.Threading {
- using System.Threading;
- using System.Runtime.InteropServices;
+using System.Threading;
+using System.Runtime.InteropServices;
+namespace System.Threading
+{
[ComVisibleAttribute(false)]
public delegate void ParameterizedThreadStart(object obj);
}
diff --git a/src/mscorlib/src/System/Threading/SemaphoreFullException.cs b/src/mscorlib/src/System/Threading/SemaphoreFullException.cs
index 01c5040b7e..ca01dba07e 100644
--- a/src/mscorlib/src/System/Threading/SemaphoreFullException.cs
+++ b/src/mscorlib/src/System/Threading/SemaphoreFullException.cs
@@ -2,25 +2,30 @@
// 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;
+using System;
+using System.Runtime.Serialization;
+using System.Runtime.InteropServices;
+namespace System.Threading
+{
[Serializable]
[ComVisibleAttribute(false)]
- public class SemaphoreFullException : SystemException {
-
- public SemaphoreFullException() : base(Environment.GetResourceString("Threading_SemaphoreFullException")){
+ public class SemaphoreFullException : SystemException
+ {
+ public SemaphoreFullException() : base(Environment.GetResourceString("Threading_SemaphoreFullException"))
+ {
}
-
- public SemaphoreFullException(String message) : base(message) {
+
+ public SemaphoreFullException(String message) : base(message)
+ {
}
- public SemaphoreFullException(String message, Exception innerException) : base(message, innerException) {
+ public SemaphoreFullException(String message, Exception innerException) : base(message, innerException)
+ {
}
-
- protected SemaphoreFullException(SerializationInfo info, StreamingContext context) : base (info, context) {
+
+ 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..7be7d2fb55 100644
--- a/src/mscorlib/src/System/Threading/SemaphoreSlim.cs
+++ b/src/mscorlib/src/System/Threading/SemaphoreSlim.cs
@@ -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()
{
@@ -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)
{
@@ -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");
@@ -882,7 +883,7 @@ namespace System.Threading
}
-
+
/// <summary>
/// Private helper method to wake up waiters when a cancellationToken gets canceled.
/// </summary>
diff --git a/src/mscorlib/src/System/Threading/SendOrPostCallback.cs b/src/mscorlib/src/System/Threading/SendOrPostCallback.cs
index b81d2bff64..c08b1aba6e 100644
--- a/src/mscorlib/src/System/Threading/SendOrPostCallback.cs
+++ b/src/mscorlib/src/System/Threading/SendOrPostCallback.cs
@@ -11,6 +11,6 @@
===========================================================*/
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..e5bd3c71c2 100644
--- a/src/mscorlib/src/System/Threading/SpinWait.cs
+++ b/src/mscorlib/src/System/Threading/SpinWait.cs
@@ -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
@@ -267,7 +266,6 @@ namespace System.Threading
}
}
return true;
-
}
#endregion
@@ -360,5 +358,4 @@ namespace System.Threading
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
index de42c1f232..1f7a284ff4 100644
--- a/src/mscorlib/src/System/Threading/SynchronizationLockException.cs
+++ b/src/mscorlib/src/System/Threading/SynchronizationLockException.cs
@@ -13,31 +13,37 @@
**
=============================================================================*/
-namespace System.Threading {
- using System;
- using System.Runtime.Serialization;
+using System;
+using System.Runtime.Serialization;
+
+namespace System.Threading
+{
[Serializable]
- public class SynchronizationLockException : SystemException {
- public SynchronizationLockException()
- : base(Environment.GetResourceString("Arg_SynchronizationLockException")) {
+ public class SynchronizationLockException : SystemException
+ {
+ public SynchronizationLockException()
+ : base(Environment.GetResourceString("Arg_SynchronizationLockException"))
+ {
SetErrorCode(__HResults.COR_E_SYNCHRONIZATIONLOCK);
}
-
- public SynchronizationLockException(String message)
- : base(message) {
+
+ public SynchronizationLockException(String message)
+ : base(message)
+ {
SetErrorCode(__HResults.COR_E_SYNCHRONIZATIONLOCK);
}
-
- public SynchronizationLockException(String message, Exception innerException)
- : base(message, innerException) {
+
+ public SynchronizationLockException(String message, Exception innerException)
+ : base(message, innerException)
+ {
SetErrorCode(__HResults.COR_E_SYNCHRONIZATIONLOCK);
}
- protected SynchronizationLockException(SerializationInfo info, StreamingContext context) : base (info, context) {
+ 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..19430596be 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",
+ Guid = "2e5dba47-a3d2-4d16-8ee0-6671ffdcd7b5",
LocalizationResources = System.CoreLib.Name)]
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 c7de16c145..b9f58c0ea0 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 |
@@ -1785,7 +1783,7 @@ namespace System.Threading.Tasks
catch (ThreadAbortException tae)
{
AddException(tae);
- FinishThreadAbortedTask(delegateRan:false);
+ FinishThreadAbortedTask(delegateRan: false);
}
catch (Exception e)
{
@@ -2253,7 +2251,6 @@ namespace System.Threading.Tasks
tmp.Add(childTask);
}
}
-
}
if (Interlocked.Decrement(ref props.m_completionCountdown) == 0)
@@ -2352,7 +2349,7 @@ namespace System.Threading.Tasks
if (!IsCompleted)
{
HandleException(tae);
- FinishThreadAbortedTask(delegateRan:false);
+ FinishThreadAbortedTask(delegateRan: false);
}
}
@@ -2479,7 +2476,7 @@ namespace System.Threading.Tasks
finally
{
currentTaskSlot = previousTask;
-
+
// ETW event for Task Completed
if (etwIsEnabled)
{
@@ -2992,7 +2989,6 @@ namespace System.Threading.Tasks
{
Thread.SpinWait(PlatformHelper.ProcessorCount * (4 << i));
}
-
}
return IsCompleted;
@@ -3050,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)
@@ -3144,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);
@@ -4169,7 +4163,7 @@ namespace System.Threading.Tasks
TaskContinuationOptions.LongRunning |
TaskContinuationOptions.DenyChildAttach |
TaskContinuationOptions.HideScheduler |
- TaskContinuationOptions.AttachedToParent|
+ TaskContinuationOptions.AttachedToParent |
TaskContinuationOptions.RunContinuationsAsynchronously;
// Check that LongRunning and ExecuteSynchronously are not specified together
@@ -4181,7 +4175,7 @@ namespace System.Threading.Tasks
// Check that no illegal options were specified
if ((continuationOptions &
- ~(CreationOptionsMask | NotOnAnything |
+ ~(CreationOptionsMask | NotOnAnything |
TaskContinuationOptions.LazyCancellation | TaskContinuationOptions.ExecuteSynchronously)) != 0)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.continuationOptions);
@@ -4434,7 +4428,6 @@ namespace System.Threading.Tasks
{
// null out that TaskContinuation entry, which will be interpreted as "to be cleaned up"
continuationsLocalListRef[index] = null;
-
}
}
}
@@ -4517,7 +4510,6 @@ namespace System.Threading.Tasks
}
return WaitAll(tasks, (int)totalMilliseconds);
-
}
/// <summary>
@@ -5120,7 +5112,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>
@@ -5129,7 +5121,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>
@@ -5139,7 +5131,7 @@ namespace System.Threading.Tasks
{
return FromCanceled<TResult>(cancellationToken);
}
-
+
#endregion
#region Run methods
@@ -6137,8 +6129,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;
}
@@ -6209,11 +6201,8 @@ namespace System.Threading.Tasks
private static Task[] GetActiveTasks()
{
-
return new List<Task>(s_currentActiveTasks.Values).ToArray();
}
-
-
}
internal sealed class CompletionActionInvoker : IThreadPoolWorkItem
@@ -6732,5 +6721,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
index f15e3e783a..890a9c8b9b 100644
--- a/src/mscorlib/src/System/Threading/Tasks/TaskCanceledException.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/TaskCanceledException.cs
@@ -16,14 +16,12 @@ 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.
@@ -60,7 +58,7 @@ namespace System.Threading.Tasks
/// </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())
+ base(Environment.GetResourceString("TaskCanceledException_ctor_DefaultMessage"), task != null ? task.CancellationToken : new CancellationToken())
{
m_canceledTask = task;
}
@@ -87,7 +85,5 @@ namespace System.Threading.Tasks
{
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 017de0e485..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)
{
@@ -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..2ff127d7b7 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"),
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,13 +267,13 @@ 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));
@@ -281,7 +281,7 @@ namespace System.Threading.Tasks
}
}
}
-
+
// 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 ed9b798902..fd6c7216bb 100644
--- a/src/mscorlib/src/System/Threading/Tasks/TaskFactory.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/TaskFactory.cs
@@ -2315,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);
@@ -2358,7 +2358,6 @@ namespace System.Threading.Tasks
!task.IsCompleted) task.RemoveContinuation(this);
}
_tasks = null;
-
}
}
@@ -2380,7 +2379,7 @@ namespace System.Threading.Tasks
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));
@@ -2654,7 +2653,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>
@@ -2766,7 +2765,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>
@@ -3080,5 +3079,4 @@ namespace System.Threading.Tasks
Contract.EndContractBlock();
}
}
-
}
diff --git a/src/mscorlib/src/System/Threading/Tasks/TaskScheduler.cs b/src/mscorlib/src/System/Threading/Tasks/TaskScheduler.cs
index 7cdf1964ac..94d3f1189e 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)
{
@@ -216,7 +216,7 @@ 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"));
}
@@ -240,7 +240,7 @@ namespace System.Threading.Tasks
/// Notifies the scheduler that a work item has made progress.
/// </summary>
internal virtual void NotifyWorkItemProgress()
- {
+ {
}
/// <summary>
@@ -275,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();
@@ -322,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
{
@@ -337,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
{
@@ -358,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;
}
@@ -404,7 +404,7 @@ namespace System.Threading.Tasks
{
newId = Interlocked.Increment(ref s_taskSchedulerIdCounter);
} while (newId == 0);
-
+
Interlocked.CompareExchange(ref m_taskSchedulerId, newId, 0);
}
@@ -483,12 +483,12 @@ namespace System.Threading.Tasks
lock (_unobservedTaskExceptionLockObject) _unobservedTaskException -= value;
}
}
-
-
+
+
////////////////////////////////////////////////////////////
//
// Internal methods
@@ -596,17 +596,16 @@ namespace System.Threading.Tasks
// 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
+ public IEnumerable<Task> ScheduledTasks
{
get { return m_taskScheduler.GetScheduledTasks(); }
}
}
-
}
@@ -636,7 +635,6 @@ namespace System.Threading.Tasks
}
m_synchronizationContext = synContext;
-
}
/// <summary>
@@ -725,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
index 1d85e49342..3726a5e18e 100644
--- a/src/mscorlib/src/System/Threading/Tasks/TaskSchedulerException.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/TaskSchedulerException.cs
@@ -16,7 +16,6 @@ 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"/>.
@@ -74,8 +73,5 @@ namespace System.Threading.Tasks
: 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 a1852f8bfb..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
@@ -56,7 +56,7 @@ 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.
diff --git a/src/mscorlib/src/System/Threading/Tasks/future.cs b/src/mscorlib/src/System/Threading/Tasks/future.cs
index 9fed97e629..147456af5f 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 : Environment.GetResourceString("TaskT_DebuggerNoResult");
}
}
@@ -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 60b3378e5e..0b6c1668f2 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,9 +34,9 @@ namespace System.Threading {
internal class 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;
@@ -47,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;
@@ -63,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);
}
@@ -78,7 +79,7 @@ namespace System.Threading {
// call back helper
internal void ThreadStart()
{
- if (_executionContext != null)
+ if (_executionContext != null)
{
ExecutionContext.Run(_executionContext, _ccb, (Object)this);
}
@@ -109,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
@@ -124,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
@@ -141,25 +142,25 @@ 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;
+ internal static CultureInfo m_CurrentUICulture;
- static AsyncLocal<CultureInfo> s_asyncLocalCurrentCulture;
- static AsyncLocal<CultureInfo> s_asyncLocalCurrentUICulture;
+ private static AsyncLocal<CultureInfo> s_asyncLocalCurrentCulture;
+ private static AsyncLocal<CultureInfo> s_asyncLocalCurrentUICulture;
- static void AsyncLocalSetCurrentCulture(AsyncLocalValueChangedArgs<CultureInfo> args)
+ private static void AsyncLocalSetCurrentCulture(AsyncLocalValueChangedArgs<CultureInfo> args)
{
m_CurrentCulture = args.CurrentValue;
}
- static void AsyncLocalSetCurrentUICulture(AsyncLocalValueChangedArgs<CultureInfo> args)
+ private static void AsyncLocalSetCurrentUICulture(AsyncLocalValueChangedArgs<CultureInfo> args)
{
m_CurrentUICulture = args.CurrentValue;
}
// Adding an empty default ctor for annotation purposes
- internal Thread(){}
+ internal Thread() { }
/*=========================================================================
** Creates a new Thread object which will begin execution at
@@ -167,37 +168,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), Environment.GetResourceString("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), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
SetStartHelper((Delegate)start, maxStackSize);
}
@@ -247,7 +256,7 @@ namespace System.Threading {
{
//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.
@@ -283,7 +292,7 @@ namespace System.Threading {
internal ExecutionContext ExecutionContext
{
- get { return m_ExecutionContext; }
+ get { return m_ExecutionContext; }
set { m_ExecutionContext = value; }
}
@@ -318,14 +327,14 @@ 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)
+ if (tm < -1 || tm > (long)Int32.MaxValue)
throw new ArgumentOutOfRangeException(nameof(timeout), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
Sleep((int)tm);
}
@@ -351,9 +360,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();
}
@@ -366,14 +377,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);
- }
+ }
}
/*=========================================================================
@@ -435,22 +446,27 @@ 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()) {
+ if (AppDomain.IsAppXModel())
+ {
return CultureInfo.GetCultureInfoForUserPreferredLanguageInAppX() ?? GetCurrentUICultureNoAppX();
- }
- else
+ }
+ else
#endif
{
return GetCurrentUICultureNoAppX();
}
}
- set {
- if (value == null) {
+ set
+ {
+ if (value == null)
+ {
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
@@ -482,8 +498,8 @@ namespace System.Threading {
}
}
- internal CultureInfo GetCurrentUICultureNoAppX() {
-
+ internal CultureInfo GetCurrentUICultureNoAppX()
+ {
Contract.Ensures(Contract.Result<CultureInfo>() != null);
#if FEATURE_COREFX_GLOBALIZATION
@@ -492,7 +508,8 @@ namespace System.Threading {
// Fetch a local copy of m_CurrentUICulture to
// avoid race conditions that malicious user can introduce
- if (m_CurrentUICulture == null) {
+ if (m_CurrentUICulture == null)
+ {
CultureInfo appDomainDefaultUICulture = CultureInfo.DefaultThreadCurrentUICulture;
return (appDomainDefaultUICulture != null ? appDomainDefaultUICulture : CultureInfo.UserDefaultUICulture);
}
@@ -515,23 +532,28 @@ 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()) {
+ if (AppDomain.IsAppXModel())
+ {
return CultureInfo.GetCultureInfoForUserPreferredLanguageInAppX() ?? GetCurrentCultureNoAppX();
- }
- else
+ }
+ else
#endif
{
return GetCurrentCultureNoAppX();
}
}
- set {
- if (null==value) {
+ set
+ {
+ if (null == value)
+ {
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
@@ -558,8 +580,8 @@ namespace System.Threading {
}
}
- private CultureInfo GetCurrentCultureNoAppX() {
-
+ private CultureInfo GetCurrentCultureNoAppX()
+ {
#if FEATURE_COREFX_GLOBALIZATION
return CultureInfo.CurrentCulture;
#else
@@ -567,8 +589,9 @@ namespace System.Threading {
// Fetch a local copy of m_CurrentCulture to
// avoid race conditions that malicious user can introduce
- if (m_CurrentCulture == null) {
- CultureInfo appDomainDefaultCulture = CultureInfo.DefaultThreadCurrentCulture;
+ if (m_CurrentCulture == null)
+ {
+ CultureInfo appDomainDefaultCulture = CultureInfo.DefaultThreadCurrentCulture;
return (appDomainDefaultCulture != null ? appDomainDefaultCulture : CultureInfo.UserDefaultCulture);
}
@@ -614,12 +637,16 @@ 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"));
m_Name = value;
@@ -635,7 +662,6 @@ namespace System.Threading {
[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
@@ -649,5 +675,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
index 25925048bf..21abb413db 100644
--- a/src/mscorlib/src/System/Threading/ThreadAbortException.cs
+++ b/src/mscorlib/src/System/Threading/ThreadAbortException.cs
@@ -15,24 +15,24 @@
**
=============================================================================*/
-namespace System.Threading
-{
- using System;
- using System.Runtime.Serialization;
- using System.Runtime.CompilerServices;
+using System;
+using System.Runtime.Serialization;
+using System.Runtime.CompilerServices;
+namespace System.Threading
+{
[Serializable]
- public sealed class ThreadAbortException : SystemException
+ public sealed class ThreadAbortException : SystemException
{
- private ThreadAbortException()
+ private ThreadAbortException()
: base(GetMessageFromNativeResources(ExceptionMessageKind.ThreadAbort))
{
SetErrorCode(__HResults.COR_E_THREADABORTED);
}
//required for serialization
- internal ThreadAbortException(SerializationInfo info, StreamingContext context)
- : base(info, context)
+ 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..2a0772d01f 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)) {
+ public class ThreadInterruptedException : SystemException
+ {
+ public ThreadInterruptedException()
+ : base(GetMessageFromNativeResources(ExceptionMessageKind.ThreadInterrupted))
+ {
SetErrorCode(__HResults.COR_E_THREADINTERRUPTED);
}
-
- public ThreadInterruptedException(String message)
- : base(message) {
+
+ public ThreadInterruptedException(String message)
+ : base(message)
+ {
SetErrorCode(__HResults.COR_E_THREADINTERRUPTED);
}
-
- public ThreadInterruptedException(String message, Exception innerException)
- : base(message, innerException) {
+
+ public ThreadInterruptedException(String message, Exception innerException)
+ : base(message, innerException)
+ {
SetErrorCode(__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..67407e7704 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.
diff --git a/src/mscorlib/src/System/Threading/ThreadPool.cs b/src/mscorlib/src/System/Threading/ThreadPool.cs
index ccd528d620..e193967971 100644
--- a/src/mscorlib/src/System/Threading/ThreadPool.cs
+++ b/src/mscorlib/src/System/Threading/ThreadPool.cs
@@ -33,7 +33,7 @@ namespace System.Threading
public static readonly int processorCount = Environment.ProcessorCount;
- public static readonly bool tpHosted = ThreadPool.IsThreadPoolHosted();
+ public static readonly bool tpHosted = ThreadPool.IsThreadPoolHosted();
public static volatile bool vmTpInitialized;
public static bool enableWorkerTracking;
@@ -124,7 +124,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 +158,7 @@ namespace System.Threading
finally
{
if (lockTaken)
- m_foreignLock.Exit(useMemoryBarrier:true);
+ m_foreignLock.Exit(useMemoryBarrier: true);
}
}
@@ -200,7 +200,7 @@ namespace System.Threading
finally
{
if (lockTaken)
- m_foreignLock.Exit(useMemoryBarrier:false);
+ m_foreignLock.Exit(useMemoryBarrier: false);
}
}
}
@@ -254,7 +254,7 @@ namespace System.Threading
finally
{
if (lockTaken)
- m_foreignLock.Exit(useMemoryBarrier:false);
+ m_foreignLock.Exit(useMemoryBarrier: false);
}
}
}
@@ -321,7 +321,7 @@ namespace System.Threading
finally
{
if (lockTaken)
- m_foreignLock.Exit(useMemoryBarrier:false);
+ m_foreignLock.Exit(useMemoryBarrier: false);
}
}
}
@@ -366,7 +366,7 @@ namespace System.Threading
finally
{
if (taken)
- m_foreignLock.Exit(useMemoryBarrier:false);
+ m_foreignLock.Exit(useMemoryBarrier: false);
}
missedSteal = true;
@@ -381,10 +381,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 +401,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 +439,7 @@ namespace System.Threading
ThreadPoolWorkQueueThreadLocals tl = null;
if (!forceGlobal)
tl = ThreadPoolWorkQueueThreadLocals.threadLocals;
-
+
if (null != tl)
{
tl.workStealingQueue.LocalPush(callback);
@@ -511,7 +511,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 +603,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 +707,7 @@ namespace System.Threading
private volatile int m_lock = 0;
internal IntPtr GetHandle() => registeredWaitHandle;
-
+
internal void SetHandle(IntPtr handle)
{
registeredWaitHandle = handle;
@@ -731,7 +731,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 +745,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)
{
@@ -841,9 +841,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 +852,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 +906,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 +934,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 +954,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 +984,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 +1002,7 @@ namespace System.Threading
void IThreadPoolWorkItem.ExecuteWorkItem()
{
#if DEBUG
- MarkExecuted(aborted:false);
+ MarkExecuted(aborted: false);
#endif
ExecutionContext.Run(ExecutionContext.Default, ccb, this);
}
@@ -1011,7 +1012,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 +1030,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 +1047,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 +1075,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
{
@@ -1114,40 +1114,40 @@ namespace System.Threading
[CLSCompliant(false)]
[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)]
[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 +1160,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,
@@ -1178,102 +1178,102 @@ namespace System.Threading
[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"));
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);
}
[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"));
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);
}
[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"));
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);
}
[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"));
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);
}
[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)
+ if (tm > (long)Int32.MaxValue)
throw new ArgumentOutOfRangeException(nameof(timeout), Environment.GetResourceString("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);
}
[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)
+ if (tm > (long)Int32.MaxValue)
throw new ArgumentOutOfRangeException(nameof(timeout), Environment.GetResourceString("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 +1428,7 @@ namespace System.Threading
EnsureVMInitializedCore(); // separate out to help with inlining
}
}
-
+
private static void EnsureVMInitializedCore()
{
ThreadPool.InitializeVMTp(ref ThreadPoolGlobals.enableWorkerTracking);
@@ -1436,7 +1436,7 @@ namespace System.Threading
}
// Native methods:
-
+
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool SetMinThreadsNative(int workerThreads, int completionPortThreads);
@@ -1476,14 +1476,14 @@ namespace System.Threading
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 +1497,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
index 6303c2fd94..64b77ea89d 100644
--- a/src/mscorlib/src/System/Threading/ThreadPriority.cs
+++ b/src/mscorlib/src/System/Threading/ThreadPriority.cs
@@ -12,12 +12,13 @@
**
=============================================================================*/
-namespace System.Threading {
- using System.Threading;
+using System.Threading;
+namespace System.Threading
+{
[Serializable]
public enum ThreadPriority
- {
+ {
/*=========================================================================
** Constants for thread priorities.
=========================================================================*/
@@ -26,6 +27,5 @@ namespace System.Threading {
Normal = 2,
AboveNormal = 3,
Highest = 4
-
}
}
diff --git a/src/mscorlib/src/System/Threading/ThreadStart.cs b/src/mscorlib/src/System/Threading/ThreadStart.cs
index e4beddcd75..c065fddbcf 100644
--- a/src/mscorlib/src/System/Threading/ThreadStart.cs
+++ b/src/mscorlib/src/System/Threading/ThreadStart.cs
@@ -13,9 +13,10 @@
**
=============================================================================*/
-namespace System.Threading {
- using System.Threading;
+using System.Threading;
+namespace System.Threading
+{
// Define the delegate
// NOTE: If you change the signature here, there is code in COMSynchronization
// that invokes this delegate in native.
diff --git a/src/mscorlib/src/System/Threading/ThreadStartException.cs b/src/mscorlib/src/System/Threading/ThreadStartException.cs
index 33fb460b3d..5b5ee82fc7 100644
--- a/src/mscorlib/src/System/Threading/ThreadStartException.cs
+++ b/src/mscorlib/src/System/Threading/ThreadStartException.cs
@@ -4,17 +4,17 @@
//
-namespace System.Threading
-{
- using System;
- using System.Runtime.Serialization;
- using System.Runtime.InteropServices;
+using System;
+using System.Runtime.Serialization;
+using System.Runtime.InteropServices;
+namespace System.Threading
+{
[Serializable]
- public sealed class ThreadStartException : SystemException
+ public sealed class ThreadStartException : SystemException
{
- private ThreadStartException()
- : base(Environment.GetResourceString("Arg_ThreadStartException"))
+ private ThreadStartException()
+ : base(Environment.GetResourceString("Arg_ThreadStartException"))
{
SetErrorCode(__HResults.COR_E_THREADSTART);
}
@@ -26,11 +26,10 @@ namespace System.Threading
}
//required for serialization
- internal ThreadStartException(SerializationInfo info, StreamingContext context)
- : base(info, context)
+ 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
index 2d953f384a..c95772e9a7 100644
--- a/src/mscorlib/src/System/Threading/ThreadState.cs
+++ b/src/mscorlib/src/System/Threading/ThreadState.cs
@@ -12,12 +12,12 @@
**
=============================================================================*/
-namespace System.Threading {
-
-[Serializable]
-[Flags]
+namespace System.Threading
+{
+ [Serializable]
+ [Flags]
public enum ThreadState
- {
+ {
/*=========================================================================
** Constants for thread states.
=========================================================================*/
diff --git a/src/mscorlib/src/System/Threading/ThreadStateException.cs b/src/mscorlib/src/System/Threading/ThreadStateException.cs
index 97c03ce06c..0df4416a93 100644
--- a/src/mscorlib/src/System/Threading/ThreadStateException.cs
+++ b/src/mscorlib/src/System/Threading/ThreadStateException.cs
@@ -13,28 +13,34 @@
**
=============================================================================*/
-namespace System.Threading {
- using System;
- using System.Runtime.Serialization;
+using System;
+using System.Runtime.Serialization;
+
+namespace System.Threading
+{
[Serializable]
- public class ThreadStateException : SystemException {
- public ThreadStateException()
- : base(Environment.GetResourceString("Arg_ThreadStateException")) {
+ public class ThreadStateException : SystemException
+ {
+ public ThreadStateException()
+ : base(Environment.GetResourceString("Arg_ThreadStateException"))
+ {
SetErrorCode(__HResults.COR_E_THREADSTATE);
}
-
- public ThreadStateException(String message)
- : base(message) {
+
+ public ThreadStateException(String message)
+ : base(message)
+ {
SetErrorCode(__HResults.COR_E_THREADSTATE);
}
-
- public ThreadStateException(String message, Exception innerException)
- : base(message, innerException) {
+
+ public ThreadStateException(String message, Exception innerException)
+ : base(message, innerException)
+ {
SetErrorCode(__HResults.COR_E_THREADSTATE);
}
- protected ThreadStateException(SerializationInfo info, StreamingContext context) : base (info, context) {
+ 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
index 80bdbccf4e..df1ea5f2bc 100644
--- a/src/mscorlib/src/System/Threading/Timeout.cs
+++ b/src/mscorlib/src/System/Threading/Timeout.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.Threading {
- using System.Threading;
- using System;
+using System.Threading;
+using System;
+
+namespace System.Threading
+{
// A constant used by methods that take a timeout (Object.Wait, Thread.Sleep
// etc) to indicate that no timeout should occur.
//
@@ -15,5 +17,4 @@ namespace System.Threading {
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..666fe70b32 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)
@@ -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 )
+ if (period < -1)
throw new ArgumentOutOfRangeException(nameof(period), Environment.GetResourceString("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), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
if (dueTm > MAX_SUPPORTED_TIMEOUT)
- throw new ArgumentOutOfRangeException(nameof(dueTm),Environment.GetResourceString("ArgumentOutOfRange_TimeoutTooLarge"));
+ throw new ArgumentOutOfRangeException(nameof(dueTm), Environment.GetResourceString("ArgumentOutOfRange_TimeoutTooLarge"));
long periodTm = (long)period.TotalMilliseconds;
if (periodTm < -1)
- throw new ArgumentOutOfRangeException(nameof(periodTm),Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(periodTm), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
if (periodTm > MAX_SUPPORTED_TIMEOUT)
- throw new ArgumentOutOfRangeException(nameof(periodTm),Environment.GetResourceString("ArgumentOutOfRange_PeriodTooLarge"));
+ throw new ArgumentOutOfRangeException(nameof(periodTm), Environment.GetResourceString("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), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
if (period < -1)
- throw new ArgumentOutOfRangeException(nameof(period),Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(period), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
if (dueTime > MAX_SUPPORTED_TIMEOUT)
- throw new ArgumentOutOfRangeException(nameof(dueTime),Environment.GetResourceString("ArgumentOutOfRange_TimeoutTooLarge"));
+ throw new ArgumentOutOfRangeException(nameof(dueTime), Environment.GetResourceString("ArgumentOutOfRange_TimeoutTooLarge"));
if (period > MAX_SUPPORTED_TIMEOUT)
- throw new ArgumentOutOfRangeException(nameof(period),Environment.GetResourceString("ArgumentOutOfRange_PeriodTooLarge"));
+ throw new ArgumentOutOfRangeException(nameof(period), Environment.GetResourceString("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), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
if (period < -1)
- throw new ArgumentOutOfRangeException(nameof(period),Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(period), Environment.GetResourceString("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,7 +766,7 @@ namespace System.Threading
public bool Change(long dueTime, long period)
{
- if (dueTime < -1 )
+ if (dueTime < -1)
throw new ArgumentOutOfRangeException(nameof(dueTime), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
if (period < -1)
throw new ArgumentOutOfRangeException(nameof(period), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
@@ -779,16 +778,16 @@ namespace System.Threading
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..620aa5ee47 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;
diff --git a/src/mscorlib/src/System/Threading/WaitHandle.cs b/src/mscorlib/src/System/Threading/WaitHandle.cs
index d4dcd710be..7ffd4b8d5a 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"));
}
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"));
}
- 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.")]
@@ -199,16 +200,16 @@ namespace System.Threading
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
@@ -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,8 +240,8 @@ 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)
@@ -249,7 +250,7 @@ namespace System.Threading
{
throw new ArgumentNullException(nameof(waitHandles), Environment.GetResourceString("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.
@@ -272,7 +273,7 @@ namespace System.Threading
}
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];
@@ -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"));
}
- 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,14 +345,14 @@ 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"));
}
- if(waitHandles.Length == 0)
+ if (waitHandles.Length == 0)
{
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyWaithandleArray"));
}
@@ -365,7 +366,7 @@ namespace System.Threading
}
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];
@@ -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"));
}
- 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);
}
/*=================================================
@@ -437,9 +438,9 @@ namespace System.Threading
==
==================================================*/
#if !PLATFORM_UNIX
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern int SignalAndWaitOne(SafeWaitHandle waitHandleToSignal,SafeWaitHandle waitHandleToWaitOn, int millisecondsTimeout,
- bool hasThreadAffinity, bool exitContext);
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ private static extern int SignalAndWaitOne(SafeWaitHandle waitHandleToSignal, SafeWaitHandle waitHandleToWaitOn, int millisecondsTimeout,
+ bool hasThreadAffinity, bool exitContext);
#endif // !PLATFORM_UNIX
public static bool SignalAndWait(
@@ -449,7 +450,7 @@ namespace System.Threading
#if PLATFORM_UNIX
throw new PlatformNotSupportedException();
#else
- return SignalAndWait(toSignal,toWaitOn,-1,false);
+ return SignalAndWait(toSignal, toWaitOn, -1, false);
#endif
}
@@ -463,11 +464,11 @@ namespace System.Threading
throw new PlatformNotSupportedException();
#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"));
}
- return SignalAndWait(toSignal,toWaitOn,(int)tm,exitContext);
+ return SignalAndWait(toSignal, toWaitOn, (int)tm, exitContext);
#endif
}
@@ -481,11 +482,11 @@ namespace System.Threading
#if PLATFORM_UNIX
throw new PlatformNotSupportedException();
#else
- if(null == toSignal)
+ if (null == toSignal)
{
throw new ArgumentNullException(nameof(toSignal));
}
- if(null == toWaitOn)
+ if (null == toWaitOn)
{
throw new ArgumentNullException(nameof(toWaitOn));
}
@@ -496,21 +497,21 @@ namespace System.Threading
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"));
}
//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
index 68445a78d9..acdb19cfac 100644
--- a/src/mscorlib/src/System/Threading/WaitHandleCannotBeOpenedException.cs
+++ b/src/mscorlib/src/System/Threading/WaitHandleCannotBeOpenedException.cs
@@ -3,21 +3,23 @@
// See the LICENSE file in the project root for more information.
//
-namespace System.Threading
-{
- using System;
- using System.Runtime.Serialization;
- using System.Runtime.InteropServices;
+using System;
+using System.Runtime.Serialization;
+using System.Runtime.InteropServices;
+
+namespace System.Threading
+{
[Serializable]
[ComVisibleAttribute(false)]
- public class WaitHandleCannotBeOpenedException : ApplicationException {
- public WaitHandleCannotBeOpenedException() : base(Environment.GetResourceString("Threading.WaitHandleCannotBeOpenedException"))
+ 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);
@@ -28,7 +30,7 @@ namespace System.Threading
SetErrorCode(__HResults.COR_E_WAITHANDLECANNOTBEOPENED);
}
- protected WaitHandleCannotBeOpenedException(SerializationInfo info, StreamingContext context) : base (info, context)
+ 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 f187193e06..978e47a80f 100644
--- a/src/mscorlib/src/System/ThrowHelper.cs
+++ b/src/mscorlib/src/System/ThrowHelper.cs
@@ -3,136 +3,160 @@
// 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), 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 System.Collections.Generic;
+using System.Runtime.CompilerServices;
+using System.Runtime.Serialization;
+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) {
+ internal static void ThrowInvalidTypeWithPointersNotSupported(Type targetType)
+ {
throw new ArgumentException(Environment.GetResourceString("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() {
+ internal static void ThrowArgumentException_DestinationTooShort()
+ {
throw new ArgumentException(Environment.GetResourceString("Argument_DestinationTooShort"));
}
- internal static void ThrowNotSupportedException_CannotCallEqualsOnSpan() {
+ internal static void ThrowNotSupportedException_CannotCallEqualsOnSpan()
+ {
throw new NotSupportedException(Environment.GetResourceString("NotSupported_CannotCallEqualsOnSpan"));
}
- internal static void ThrowNotSupportedException_CannotCallGetHashCodeOnSpan() {
+ internal static void ThrowNotSupportedException_CannotCallGetHashCodeOnSpan()
+ {
throw new NotSupportedException(Environment.GetResourceString("NotSupported_CannotCallGetHashCodeOnSpan"));
}
- 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) {
+ private static ArgumentException GetAddingDuplicateWithKeyArgumentException(object key)
+ {
return new ArgumentException(Environment.GetResourceString("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));
}
@@ -141,87 +165,108 @@ namespace System {
throw new ArgumentNullException(GetArgumentName(argument), GetResourceString(resource));
}
- internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument) {
+ 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)
@@ -233,31 +278,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) {
+ private static ArgumentException GetWrongKeyTypeArgumentException(object key, Type targetType)
+ {
return new ArgumentException(Environment.GetResourceString("Arg_WrongType", key, targetType), nameof(key));
}
- private static ArgumentException GetWrongValueTypeArgumentException(object value, Type targetType) {
+ private static ArgumentException GetWrongValueTypeArgumentException(object value, Type targetType)
+ {
return new ArgumentException(Environment.GetResourceString("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));
}
@@ -265,7 +317,8 @@ 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);
@@ -273,7 +326,8 @@ namespace System {
// This function will convert an ExceptionArgument enum value to the argument name string.
[MethodImpl(MethodImplOptions.NoInlining)]
- private static string GetArgumentName(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.");
@@ -282,7 +336,8 @@ namespace System {
// This function will convert an ExceptionResource enum value to the resource string.
[MethodImpl(MethodImplOptions.NoInlining)]
- private static string GetResourceString(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.");
@@ -293,7 +348,8 @@ namespace System {
//
// The convention for this enum is using the argument name as the enum name
//
- internal enum ExceptionArgument {
+ internal enum ExceptionArgument
+ {
obj,
dictionary,
dictionaryCreationThreshold,
@@ -374,23 +430,24 @@ namespace System {
//
// 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,
diff --git a/src/mscorlib/src/System/TimeSpan.cs b/src/mscorlib/src/System/TimeSpan.cs
index 7b71b48fed..f7c864d923 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)
{
}
@@ -90,43 +94,53 @@ 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;
+ _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,15 +152,18 @@ 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.
@@ -160,14 +177,16 @@ 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"));
@@ -177,26 +196,31 @@ namespace System {
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)
+ public TimeSpan Duration()
+ {
+ if (Ticks == TimeSpan.MinValue.Ticks)
throw new OverflowException(Environment.GetResourceString("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,49 +231,58 @@ 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"));
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"));
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)
+ public TimeSpan Negate()
+ {
+ if (Ticks == TimeSpan.MinValue.Ticks)
throw new OverflowException(Environment.GetResourceString("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.
@@ -259,11 +292,13 @@ namespace System {
return new TimeSpan(result);
}
- public static TimeSpan FromTicks(long value) {
+ 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;
@@ -274,102 +309,129 @@ namespace System {
// 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)
+
+ public static TimeSpan operator -(TimeSpan t)
+ {
+ if (t._ticks == TimeSpan.MinValue._ticks)
throw new OverflowException(Environment.GetResourceString("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 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 +467,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
index 8ede49293e..88e2e21864 100644
--- a/src/mscorlib/src/System/TimeZone.cs
+++ b/src/mscorlib/src/System/TimeZone.cs
@@ -4,7 +4,6 @@
/*============================================================
**
-** Class: TimeZone
**
**
** Purpose:
@@ -18,23 +17,29 @@
**
**
============================================================*/
-namespace System {
- using System;
- using System.Text;
- using System.Threading;
- using System.Collections;
- using System.Globalization;
+using System;
+using System.Text;
+using System.Threading;
+using System.Collections;
+using System.Globalization;
+
+namespace System
+{
[Serializable]
[Obsolete("System.TimeZone has been deprecated. Please investigate the use of System.TimeZoneInfo instead.")]
- public abstract class TimeZone {
+ 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) {
+ private static Object InternalSyncObject
+ {
+ get
+ {
+ if (s_InternalSyncObject == null)
+ {
Object o = new Object();
Interlocked.CompareExchange<Object>(ref s_InternalSyncObject, o, null);
}
@@ -43,17 +48,23 @@ namespace System {
}
- protected TimeZone() {
+ protected TimeZone()
+ {
}
-
- public static TimeZone CurrentTimeZone {
- get {
+
+ 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) {
+ if (tz == null)
+ {
+ lock (InternalSyncObject)
+ {
+ if (currentTimeZone == null)
+ {
currentTimeZone = new CurrentSystemTimeZone();
}
tz = currentTimeZone;
@@ -66,19 +77,24 @@ namespace System {
//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) {
+ internal static void ResetTimeZone()
+ {
+ if (currentTimeZone != null)
+ {
+ lock (InternalSyncObject)
+ {
currentTimeZone = null;
}
}
}
-
- public abstract String StandardName {
+
+ public abstract String StandardName
+ {
get;
}
-
- public abstract String DaylightName {
+
+ public abstract String DaylightName
+ {
get;
}
@@ -87,15 +103,19 @@ namespace System {
//
// Converts the specified datatime to the Universal time base on the current timezone
//
- public virtual DateTime ToUniversalTime(DateTime time) {
- if (time.Kind == DateTimeKind.Utc) {
+ public virtual DateTime ToUniversalTime(DateTime time)
+ {
+ if (time.Kind == DateTimeKind.Utc)
+ {
return time;
}
long tickCount = time.Ticks - GetUtcOffset(time).Ticks;
- if (tickCount>DateTime.MaxTicks) {
+ if (tickCount > DateTime.MaxTicks)
+ {
return new DateTime(DateTime.MaxTicks, DateTimeKind.Utc);
}
- if (tickCount<DateTime.MinTicks) {
+ if (tickCount < DateTime.MinTicks)
+ {
return new DateTime(DateTime.MinTicks, DateTimeKind.Utc);
}
return new DateTime(tickCount, DateTimeKind.Utc);
@@ -104,30 +124,34 @@ namespace System {
//
// 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) {
+ 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) {
+ 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;
+ 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,
@@ -156,7 +180,7 @@ namespace System {
//
// 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,
@@ -188,12 +212,15 @@ namespace System {
//
// 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) {
+ internal static TimeSpan CalculateUtcOffset(DateTime time, DaylightTime daylightTimes)
+ {
+ if (daylightTimes == null)
+ {
return TimeSpan.Zero;
}
DateTimeKind kind = time.Kind;
- if (kind == DateTimeKind.Utc) {
+ if (kind == DateTimeKind.Utc)
+ {
return TimeSpan.Zero;
}
@@ -204,40 +231,48 @@ namespace System {
// 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) {
+ DateTime ambiguousEnd;
+ if (daylightTimes.Delta.Ticks > 0)
+ {
ambiguousStart = endTime - daylightTimes.Delta;
ambiguousEnd = endTime;
- } else {
+ }
+ else
+ {
ambiguousStart = startTime;
ambiguousEnd = startTime - daylightTimes.Delta;
}
Boolean isDst = false;
- if (startTime > endTime) {
+ 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) {
+ if (time >= startTime || time < endTime)
+ {
isDst = true;
}
}
- else if (time>=startTime && time < endTime) {
+ 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) {
+ if (isDst && time >= ambiguousStart && time < ambiguousEnd)
+ {
isDst = time.IsAmbiguousDaylightSavingTime();
}
-
- if (isDst) {
+
+ 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..21238fb94f 100644
--- a/src/mscorlib/src/System/TimeZoneInfo.AdjustmentRule.cs
+++ b/src/mscorlib/src/System/TimeZoneInfo.AdjustmentRule.cs
@@ -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.TransitionTime.cs b/src/mscorlib/src/System/TimeZoneInfo.TransitionTime.cs
index dedcb880a4..354d0acdb7 100644
--- a/src/mscorlib/src/System/TimeZoneInfo.TransitionTime.cs
+++ b/src/mscorlib/src/System/TimeZoneInfo.TransitionTime.cs
@@ -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.Win32.cs b/src/mscorlib/src/System/TimeZoneInfo.Win32.cs
index 79ee535505..09a926f1aa 100644
--- a/src/mscorlib/src/System/TimeZoneInfo.Win32.cs
+++ b/src/mscorlib/src/System/TimeZoneInfo.Win32.cs
@@ -1016,7 +1016,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..1f628793d4 100644
--- a/src/mscorlib/src/System/TimeZoneInfo.cs
+++ b/src/mscorlib/src/System/TimeZoneInfo.cs
@@ -513,7 +513,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);
@@ -868,7 +867,6 @@ namespace System
return false;
}
}
-
}
return sameRules;
}
@@ -915,7 +913,6 @@ namespace System
AdjustmentRule[] adjustmentRules,
bool disableDaylightSavingTime)
{
-
bool adjustmentRulesSupportDst;
ValidateTimeZoneInfo(id, baseUtcOffset, adjustmentRules, out adjustmentRulesSupportDst);
@@ -1034,7 +1031,7 @@ namespace System
info.AddValue("SupportsDaylightSavingTime", _supportsDaylightSavingTime);
}
- TimeZoneInfo(SerializationInfo info, StreamingContext context)
+ private TimeZoneInfo(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
@@ -1430,7 +1427,6 @@ namespace System
}
catch (ArgumentOutOfRangeException) { }
}
-
}
}
@@ -1889,7 +1885,6 @@ namespace System
if (UtcOffsetOutOfRange(baseUtcOffset))
{
-
throw new ArgumentOutOfRangeException(nameof(baseUtcOffset), Environment.GetResourceString("ArgumentOutOfRange_UtcOffset"));
}
diff --git a/src/mscorlib/src/System/Tuple.cs b/src/mscorlib/src/System/Tuple.cs
index bb0dbcad6f..02894c2a2b 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; } }
@@ -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;
@@ -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;
@@ -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;
@@ -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;
@@ -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;
@@ -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;
@@ -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;
diff --git a/src/mscorlib/src/System/Type.cs b/src/mscorlib/src/System/Type.cs
index 192760830b..795a42fef0 100644
--- a/src/mscorlib/src/System/Type.cs
+++ b/src/mscorlib/src/System/Type.cs
@@ -40,7 +40,7 @@ namespace System
public static readonly Object Missing = System.Reflection.Missing.Value;
- public static readonly char Delimiter = '.';
+ 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;
@@ -49,18 +49,20 @@ namespace System
private static Binder defaultBinder;
- protected Type() {}
+ protected Type() { }
// MemberInfo Methods....
// The Member type Field.
- public override MemberTypes MemberType {
- get {return System.Reflection.MemberTypes.TypeInfo;}
+ 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 override Type DeclaringType
+ {
+ get { return null; }
}
public virtual MethodBase DeclaringMethod { get { return null; } }
@@ -68,7 +70,7 @@ namespace System
// Return the class that was used to obtain this type.
public override Type ReflectedType
{
- get {return null;}
+ get { return null; }
}
////////////////////////////////////////////////////////////////////////////////
@@ -78,19 +80,22 @@ namespace System
////
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
- public static Type GetType(String typeName, bool throwOnError, bool ignoreCase) {
+ 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) {
+ 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) {
+ public static Type GetType(String typeName)
+ {
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return RuntimeType.GetType(typeName, false, false, false, ref stackMark);
}
@@ -129,7 +134,7 @@ namespace System
}
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
- public static Type ReflectionOnlyGetType(String typeName, bool throwIfNotFound, bool ignoreCase)
+ public static Type ReflectionOnlyGetType(String typeName, bool throwIfNotFound, bool ignoreCase)
{
if (typeName == null)
throw new ArgumentNullException(nameof(typeName));
@@ -155,7 +160,7 @@ namespace System
////
public static Type GetTypeFromProgID(String progID)
{
- return RuntimeType.GetTypeFromProgIDImpl(progID, null, false);
+ return RuntimeType.GetTypeFromProgIDImpl(progID, null, false);
}
////////////////////////////////////////////////////////////////////////////////
@@ -169,17 +174,17 @@ namespace System
////
public static Type GetTypeFromProgID(String progID, bool throwOnError)
{
- return RuntimeType.GetTypeFromProgIDImpl(progID, null, throwOnError);
+ return RuntimeType.GetTypeFromProgIDImpl(progID, null, throwOnError);
}
public static Type GetTypeFromProgID(String progID, String server)
{
- return RuntimeType.GetTypeFromProgIDImpl(progID, server, false);
+ return RuntimeType.GetTypeFromProgIDImpl(progID, server, false);
}
public static Type GetTypeFromProgID(String progID, String server, bool throwOnError)
{
- return RuntimeType.GetTypeFromProgIDImpl(progID, server, throwOnError);
+ return RuntimeType.GetTypeFromProgIDImpl(progID, server, throwOnError);
}
////////////////////////////////////////////////////////////////////////////////
@@ -191,22 +196,22 @@ namespace System
////
public static Type GetTypeFromCLSID(Guid clsid)
{
- return RuntimeType.GetTypeFromCLSIDImpl(clsid, null, false);
+ return RuntimeType.GetTypeFromCLSIDImpl(clsid, null, false);
}
public static Type GetTypeFromCLSID(Guid clsid, bool throwOnError)
{
- return RuntimeType.GetTypeFromCLSIDImpl(clsid, null, throwOnError);
+ return RuntimeType.GetTypeFromCLSIDImpl(clsid, null, throwOnError);
}
public static Type GetTypeFromCLSID(Guid clsid, String server)
{
- return RuntimeType.GetTypeFromCLSIDImpl(clsid, server, false);
+ return RuntimeType.GetTypeFromCLSIDImpl(clsid, server, false);
}
public static Type GetTypeFromCLSID(Guid clsid, String server, bool throwOnError)
{
- return RuntimeType.GetTypeFromCLSIDImpl(clsid, server, throwOnError);
+ return RuntimeType.GetTypeFromCLSIDImpl(clsid, server, throwOnError);
}
// GetTypeCode
@@ -227,18 +232,21 @@ namespace System
// 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 {
+ public abstract Guid GUID
+ {
get;
}
// Return the Default binder used by the system.
- static public Binder DefaultBinder {
- get {
+ static public Binder DefaultBinder
+ {
+ get
+ {
// Allocate the default binder if it hasn't been allocated yet.
if (defaultBinder == null)
CreateBinder();
@@ -246,7 +254,7 @@ namespace System
}
}
- static private void CreateBinder()
+ static private void CreateBinder()
{
if (defaultBinder == null)
{
@@ -255,43 +263,43 @@ namespace System
}
}
- // 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);
+ // 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)
+ 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);
+ 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)
+ public Object InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args)
{
- return InvokeMember(name,invokeAttr,binder,target,args,null,null,null);
+ return InvokeMember(name, invokeAttr, binder, target, args, null, null, null);
}
@@ -299,7 +307,8 @@ namespace System
public new abstract Module Module { get; }
// Assembly Property associated with a class.
- public abstract Assembly Assembly {
+ public abstract Assembly Assembly
+ {
[Pure]
get;
}
@@ -316,7 +325,8 @@ namespace System
}
}
- internal virtual RuntimeTypeHandle GetTypeHandleInternal() {
+ internal virtual RuntimeTypeHandle GetTypeHandleInternal()
+ {
return TypeHandle;
}
@@ -337,26 +347,30 @@ namespace System
// Return the fully qualified name. The name does contain the namespace.
- public abstract String FullName {
+ public abstract String FullName
+ {
[Pure]
get;
}
// Return the name space of the class.
- public abstract String Namespace {
+ public abstract String Namespace
+ {
[Pure]
get;
}
- public abstract String AssemblyQualifiedName {
+ public abstract String AssemblyQualifiedName
+ {
[Pure]
get;
}
[Pure]
- public virtual int GetArrayRank() {
+ public virtual int GetArrayRank()
+ {
Contract.Ensures(Contract.Result<int>() >= 0);
throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride"));
}
@@ -364,7 +378,8 @@ namespace System
// 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 {
+ public abstract Type BaseType
+ {
[Pure]
get;
}
@@ -376,15 +391,15 @@ namespace System
// reason is that we don't typically expose the class initializer.
public ConstructorInfo GetConstructor(BindingFlags bindingAttr,
Binder binder,
- CallingConventions callConvention,
+ CallingConventions callConvention,
Type[] types,
ParameterModifier[] modifiers)
- {
- // Must provide some types (Type[0] for nothing)
+ {
+ // 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++)
+ for (int i = 0; i < types.Length; i++)
if (types[i] == null)
throw new ArgumentNullException(nameof(types));
return GetConstructorImpl(bindingAttr, binder, callConvention, types, modifiers);
@@ -395,7 +410,7 @@ namespace System
if (types == null)
throw new ArgumentNullException(nameof(types));
Contract.EndContractBlock();
- for (int i=0;i<types.Length;i++)
+ 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);
@@ -409,7 +424,7 @@ namespace System
abstract protected ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr,
Binder binder,
- CallingConventions callConvention,
+ CallingConventions callConvention,
Type[] types,
ParameterModifier[] modifiers);
@@ -417,14 +432,17 @@ namespace System
// 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() {
+ public ConstructorInfo[] GetConstructors()
+ {
return GetConstructors(BindingFlags.Public | BindingFlags.Instance);
}
-
+
abstract public ConstructorInfo[] GetConstructors(BindingFlags bindingAttr);
- public ConstructorInfo TypeInitializer {
- get {
+ public ConstructorInfo TypeInitializer
+ {
+ get
+ {
return GetConstructorImpl(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic,
null,
CallingConventions.Any,
@@ -480,20 +498,20 @@ namespace System
if (types == null)
throw new ArgumentNullException(nameof(types));
Contract.EndContractBlock();
- for (int i=0;i<types.Length;i++)
+ 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)
+ 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++)
+ 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);
@@ -518,14 +536,15 @@ namespace System
abstract protected MethodInfo GetMethodImpl(String name,
BindingFlags bindingAttr,
Binder binder,
- CallingConventions callConvention,
+ CallingConventions callConvention,
Type[] types,
ParameterModifier[] modifiers);
// GetMethods
// This routine will return all the methods implemented by the class
- public MethodInfo[] GetMethods() {
+ public MethodInfo[] GetMethods()
+ {
return GetMethods(Type.DefaultLookup);
}
@@ -536,14 +555,16 @@ namespace System
abstract public FieldInfo GetField(String name, BindingFlags bindingAttr);
- public FieldInfo GetField(String name) {
+ 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() {
+ public FieldInfo[] GetFields()
+ {
return GetFields(Type.DefaultLookup);
}
abstract public FieldInfo[] GetFields(BindingFlags bindingAttr);
@@ -551,8 +572,9 @@ namespace System
// 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);
+ public Type GetInterface(String name)
+ {
+ return GetInterface(name, false);
}
abstract public Type GetInterface(String name, bool ignoreCase);
@@ -563,25 +585,27 @@ namespace System
// FindInterfaces
// This method will filter the interfaces supported the class
- public virtual Type[] FindInterfaces(TypeFilter filter,Object filterCriteria)
+ 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))
+ 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++) {
+ cnt = 0;
+ for (int i = 0; i < c.Length; i++)
+ {
if (c[i] != null)
ret[cnt++] = c[i];
}
@@ -593,15 +617,17 @@ namespace System
// null is returned if the event is not found
- public EventInfo GetEvent(String name) {
- return GetEvent(name,Type.DefaultLookup);
+ public EventInfo GetEvent(String name)
+ {
+ return GetEvent(name, Type.DefaultLookup);
}
- abstract public EventInfo GetEvent(String name,BindingFlags bindingAttr);
+ 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() {
+ virtual public EventInfo[] GetEvents()
+ {
return GetEvents(Type.DefaultLookup);
}
abstract public EventInfo[] GetEvents(BindingFlags bindingAttr);
@@ -609,7 +635,7 @@ namespace System
// Return a property based upon the passed criteria. The nameof the
// parameter must be provided.
- public PropertyInfo GetProperty(String name,BindingFlags bindingAttr,Binder binder,
+ public PropertyInfo GetProperty(String name, BindingFlags bindingAttr, Binder binder,
Type returnType, Type[] types, ParameterModifier[] modifiers)
{
if (name == null)
@@ -617,17 +643,17 @@ namespace System
if (types == null)
throw new ArgumentNullException(nameof(types));
Contract.EndContractBlock();
- return GetPropertyImpl(name,bindingAttr,binder,returnType,types,modifiers);
+ return GetPropertyImpl(name, bindingAttr, binder, returnType, types, modifiers);
}
- public PropertyInfo GetProperty(String name, Type returnType, Type[] types,ParameterModifier[] 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);
+ return GetPropertyImpl(name, Type.DefaultLookup, null, returnType, types, modifiers);
}
public PropertyInfo GetProperty(String name, BindingFlags bindingAttr)
@@ -635,7 +661,7 @@ namespace System
if (name == null)
throw new ArgumentNullException(nameof(name));
Contract.EndContractBlock();
- return GetPropertyImpl(name,bindingAttr,null,null,null,null);
+ return GetPropertyImpl(name, bindingAttr, null, null, null, null);
}
public PropertyInfo GetProperty(String name, Type returnType, Type[] types)
@@ -645,7 +671,7 @@ namespace System
if (types == null)
throw new ArgumentNullException(nameof(types));
Contract.EndContractBlock();
- return GetPropertyImpl(name,Type.DefaultLookup,null,returnType,types,null);
+ return GetPropertyImpl(name, Type.DefaultLookup, null, returnType, types, null);
}
public PropertyInfo GetProperty(String name, Type[] types)
@@ -655,7 +681,7 @@ namespace System
if (types == null)
throw new ArgumentNullException(nameof(types));
Contract.EndContractBlock();
- return GetPropertyImpl(name,Type.DefaultLookup,null,null,types,null);
+ return GetPropertyImpl(name, Type.DefaultLookup, null, null, types, null);
}
public PropertyInfo GetProperty(String name, Type returnType)
@@ -665,7 +691,7 @@ namespace System
if (returnType == null)
throw new ArgumentNullException(nameof(returnType));
Contract.EndContractBlock();
- return GetPropertyImpl(name,Type.DefaultLookup,null,returnType,null,null);
+ return GetPropertyImpl(name, Type.DefaultLookup, null, returnType, null, null);
}
public PropertyInfo GetProperty(String name)
@@ -673,10 +699,10 @@ namespace System
if (name == null)
throw new ArgumentNullException(nameof(name));
Contract.EndContractBlock();
- return GetPropertyImpl(name,Type.DefaultLookup,null,null,null,null);
+ return GetPropertyImpl(name, Type.DefaultLookup, null, null, null, null);
}
- protected abstract PropertyInfo GetPropertyImpl(String name, BindingFlags bindingAttr,Binder binder,
+ protected abstract PropertyInfo GetPropertyImpl(String name, BindingFlags bindingAttr, Binder binder,
Type returnType, Type[] types, ParameterModifier[] modifiers);
@@ -701,7 +727,7 @@ namespace System
public Type GetNestedType(String name)
{
- return GetNestedType(name,Type.DefaultLookup);
+ return GetNestedType(name, Type.DefaultLookup);
}
abstract public Type GetNestedType(String name, BindingFlags bindingAttr);
@@ -709,15 +735,16 @@ namespace System
// 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);
+ public MemberInfo[] GetMember(String name)
+ {
+ return GetMember(name, Type.DefaultLookup);
}
virtual public MemberInfo[] GetMember(String name, BindingFlags bindingAttr)
{
- return GetMember(name,MemberTypes.All,bindingAttr);
+ return GetMember(name, MemberTypes.All, bindingAttr);
}
-
+
virtual public MemberInfo[] GetMember(String name, MemberTypes type, BindingFlags bindingAttr)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride"));
@@ -726,7 +753,8 @@ namespace System
// GetMembers
// This will return a Member array of all of the members of a class
- public MemberInfo[] GetMembers() {
+ public MemberInfo[] GetMembers()
+ {
return GetMembers(Type.DefaultLookup);
}
abstract public MemberInfo[] GetMembers(BindingFlags bindingAttr);
@@ -741,7 +769,7 @@ namespace System
// FindMembers
// This will return a filtered version of the member information
- public virtual MemberInfo[] FindMembers(MemberTypes memberType,BindingFlags bindingAttr,MemberFilter filter,Object filterCriteria)
+ public virtual MemberInfo[] FindMembers(MemberTypes memberType, BindingFlags bindingAttr, MemberFilter filter, Object filterCriteria)
{
// Define the work arrays
MethodInfo[] m = null;
@@ -750,168 +778,199 @@ namespace System
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) {
+ 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))
+ if (filter != null)
+ {
+ for (i = 0; i < m.Length; i++)
+ if (!filter(m[i], filterCriteria))
m[i] = null;
else
cnt++;
- } else {
- cnt+=m.Length;
+ }
+ else
+ {
+ cnt += m.Length;
}
}
-
+
// Check the constructors
- if ((memberType & System.Reflection.MemberTypes.Constructor) != 0) {
+ 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))
+ if (filter != null)
+ {
+ for (i = 0; i < c.Length; i++)
+ if (!filter(c[i], filterCriteria))
c[i] = null;
else
cnt++;
- } else {
- cnt+=c.Length;
+ }
+ else
+ {
+ cnt += c.Length;
}
}
-
+
// Check the fields
- if ((memberType & System.Reflection.MemberTypes.Field) != 0) {
+ 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))
+ if (filter != null)
+ {
+ for (i = 0; i < f.Length; i++)
+ if (!filter(f[i], filterCriteria))
f[i] = null;
else
cnt++;
- } else {
- cnt+=f.Length;
+ }
+ else
+ {
+ cnt += f.Length;
}
}
-
+
// Check the Properties
- if ((memberType & System.Reflection.MemberTypes.Property) != 0) {
+ 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))
+ if (filter != null)
+ {
+ for (i = 0; i < p.Length; i++)
+ if (!filter(p[i], filterCriteria))
p[i] = null;
else
cnt++;
- } else {
- cnt+=p.Length;
+ }
+ else
+ {
+ cnt += p.Length;
}
}
-
+
// Check the Events
- if ((memberType & System.Reflection.MemberTypes.Event) != 0) {
+ 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))
+ if (filter != null)
+ {
+ for (i = 0; i < e.Length; i++)
+ if (!filter(e[i], filterCriteria))
e[i] = null;
else
cnt++;
- } else {
- cnt+=e.Length;
+ }
+ else
+ {
+ cnt += e.Length;
}
}
-
+
// Check the Types
- if ((memberType & System.Reflection.MemberTypes.NestedType) != 0) {
+ 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))
+ if (filter != null)
+ {
+ for (i = 0; i < t.Length; i++)
+ if (!filter(t[i], filterCriteria))
t[i] = null;
else
cnt++;
- } else {
- cnt+=t.Length;
+ }
+ 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 != 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 != 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 != 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 != 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 != 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 != 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.
- //
- ////////////////////////////////////////////////////////////////////////////////
+ ////////////////////////////////////////////////////////////////////////////////
+ //
+ // 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
+ public bool IsNested
{
[Pure]
- get
+ get
{
- return DeclaringType != null;
+ return DeclaringType != null;
}
}
// The attribute property on the Type.
- public TypeAttributes Attributes {
+ public TypeAttributes Attributes
+ {
[Pure]
- get {return GetAttributeFlagsImpl();}
+ get { return GetAttributeFlagsImpl(); }
}
public virtual GenericParameterAttributes GenericParameterAttributes
@@ -922,7 +981,7 @@ namespace System
public bool IsVisible
{
[Pure]
- get
+ get
{
RuntimeType rt = this as RuntimeType;
if (rt != null)
@@ -964,59 +1023,71 @@ namespace System
public bool IsNotPublic
{
[Pure]
- get {return ((GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NotPublic);}
+ get { return ((GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NotPublic); }
}
- public bool IsPublic {
+ public bool IsPublic
+ {
[Pure]
- get {return ((GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.Public);}
+ get { return ((GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.Public); }
}
- public bool IsNestedPublic {
+ public bool IsNestedPublic
+ {
[Pure]
- get {return ((GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPublic);}
+ get { return ((GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPublic); }
}
- public bool IsNestedPrivate {
+ public bool IsNestedPrivate
+ {
[Pure]
- get {return ((GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate);}
+ get { return ((GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate); }
}
- public bool IsNestedFamily {
+ public bool IsNestedFamily
+ {
[Pure]
- get {return ((GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NestedFamily);}
+ get { return ((GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NestedFamily); }
}
- public bool IsNestedAssembly {
+ public bool IsNestedAssembly
+ {
[Pure]
- get {return ((GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NestedAssembly);}
+ get { return ((GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NestedAssembly); }
}
- public bool IsNestedFamANDAssem {
+ public bool IsNestedFamANDAssem
+ {
[Pure]
- get {return ((GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NestedFamANDAssem);}
+ get { return ((GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NestedFamANDAssem); }
}
- public bool IsNestedFamORAssem{
+ public bool IsNestedFamORAssem
+ {
[Pure]
- get {return ((GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NestedFamORAssem);}
+ get { return ((GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NestedFamORAssem); }
}
- public bool IsAutoLayout {
+ public bool IsAutoLayout
+ {
[Pure]
- get {return ((GetAttributeFlagsImpl() & TypeAttributes.LayoutMask) == TypeAttributes.AutoLayout);}
+ get { return ((GetAttributeFlagsImpl() & TypeAttributes.LayoutMask) == TypeAttributes.AutoLayout); }
}
- public bool IsLayoutSequential {
+ public bool IsLayoutSequential
+ {
[Pure]
- get {return ((GetAttributeFlagsImpl() & TypeAttributes.LayoutMask) == TypeAttributes.SequentialLayout);}
+ get { return ((GetAttributeFlagsImpl() & TypeAttributes.LayoutMask) == TypeAttributes.SequentialLayout); }
}
- public bool IsExplicitLayout {
+ public bool IsExplicitLayout
+ {
[Pure]
- get {return ((GetAttributeFlagsImpl() & TypeAttributes.LayoutMask) == TypeAttributes.ExplicitLayout);}
+ get { return ((GetAttributeFlagsImpl() & TypeAttributes.LayoutMask) == TypeAttributes.ExplicitLayout); }
}
- public bool IsClass {
+ public bool IsClass
+ {
[Pure]
- get {return ((GetAttributeFlagsImpl() & TypeAttributes.ClassSemanticsMask) == TypeAttributes.Class && !IsValueType);}
+ get { return ((GetAttributeFlagsImpl() & TypeAttributes.ClassSemanticsMask) == TypeAttributes.Class && !IsValueType); }
}
- public bool IsInterface {
+ public bool IsInterface
+ {
[Pure]
get
{
@@ -1028,38 +1099,44 @@ namespace System
}
}
- public bool IsValueType {
+ public bool IsValueType
+ {
+ [Pure]
+ get { return IsValueTypeImpl(); }
+ }
+
+ public bool IsAbstract
+ {
[Pure]
- get {return IsValueTypeImpl();}
+ get { return ((GetAttributeFlagsImpl() & TypeAttributes.Abstract) != 0); }
}
- public bool IsAbstract {
+ public bool IsSealed
+ {
[Pure]
- get { return ((GetAttributeFlagsImpl() & TypeAttributes.Abstract) != 0); }
- }
-
- public bool IsSealed {
+ get { return ((GetAttributeFlagsImpl() & TypeAttributes.Sealed) != 0); }
+ }
+
+ public virtual bool IsEnum
+ {
[Pure]
- get {return ((GetAttributeFlagsImpl() & TypeAttributes.Sealed) != 0);}
- }
-
- public virtual bool IsEnum {
- [Pure]
- get
- {
+ 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 bool IsSpecialName
+ {
+ [Pure]
+ get { return ((GetAttributeFlagsImpl() & TypeAttributes.SpecialName) != 0); }
+ }
+
+ public bool IsImport
+ {
+ [Pure]
+ get { return ((GetAttributeFlagsImpl() & TypeAttributes.Import) != 0); }
}
public virtual bool IsSerializable
@@ -1079,40 +1156,47 @@ namespace System
}
}
- public bool IsAnsiClass {
- [Pure]
- get {return ((GetAttributeFlagsImpl() & TypeAttributes.StringFormatMask) == TypeAttributes.AnsiClass);}
+ public bool IsAnsiClass
+ {
+ [Pure]
+ get { return ((GetAttributeFlagsImpl() & TypeAttributes.StringFormatMask) == TypeAttributes.AnsiClass); }
}
- public bool IsUnicodeClass {
- [Pure]
- get {return ((GetAttributeFlagsImpl() & TypeAttributes.StringFormatMask) == TypeAttributes.UnicodeClass);}
+ public bool IsUnicodeClass
+ {
+ [Pure]
+ get { return ((GetAttributeFlagsImpl() & TypeAttributes.StringFormatMask) == TypeAttributes.UnicodeClass); }
}
- public bool IsAutoClass {
- [Pure]
- get {return ((GetAttributeFlagsImpl() & TypeAttributes.StringFormatMask) == TypeAttributes.AutoClass);}
+ 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;}
+ // These are not backed up by attributes. Instead they are implemented
+ // based internally.
+ public bool IsArray
+ {
+ [Pure]
+ get { return IsArrayImpl(); }
}
- public virtual bool IsGenericType {
- [Pure]
+ internal virtual bool IsSzArray
+ {
+ [Pure]
get { return false; }
}
- public virtual bool IsGenericTypeDefinition {
- [Pure]
+ public virtual bool IsGenericType
+ {
+ [Pure]
+ get { return false; }
+ }
+
+ public virtual bool IsGenericTypeDefinition
+ {
+ [Pure]
get { return false; }
}
@@ -1128,22 +1212,23 @@ namespace System
get { return false; }
}
- public virtual int GenericParameterPosition {
- [Pure]
- get {throw new InvalidOperationException(Environment.GetResourceString("Arg_NotGenericParameter")); }
+ public virtual int GenericParameterPosition
+ {
+ [Pure]
+ get { throw new InvalidOperationException(Environment.GetResourceString("Arg_NotGenericParameter")); }
}
- public virtual bool ContainsGenericParameters
+ public virtual bool ContainsGenericParameters
{
[Pure]
- get
+ get
{
if (HasElementType)
return GetRootElementType().ContainsGenericParameters;
if (IsGenericParameter)
return true;
-
+
if (!IsGenericType)
return false;
@@ -1168,50 +1253,59 @@ namespace System
throw new InvalidOperationException();
}
- public bool IsByRef {
- [Pure]
- get {return IsByRefImpl();}
+ public bool IsByRef
+ {
+ [Pure]
+ get { return IsByRefImpl(); }
}
- public bool IsPointer {
- [Pure]
- get {return IsPointerImpl();}
+ public bool IsPointer
+ {
+ [Pure]
+ get { return IsPointerImpl(); }
}
- public bool IsPrimitive {
- [Pure]
- get {return IsPrimitiveImpl();}
+ public bool IsPrimitive
+ {
+ [Pure]
+ get { return IsPrimitiveImpl(); }
}
- public bool IsCOMObject {
- [Pure]
- get {return IsCOMObjectImpl();}
+ public bool IsCOMObject
+ {
+ [Pure]
+ get { return IsCOMObjectImpl(); }
}
#if FEATURE_COMINTEROP
- internal bool IsWindowsRuntimeObject {
+ internal bool IsWindowsRuntimeObject
+ {
[Pure]
get { return IsWindowsRuntimeObjectImpl(); }
}
- internal bool IsExportedToWindowsRuntime {
+ internal bool IsExportedToWindowsRuntime
+ {
[Pure]
get { return IsExportedToWindowsRuntimeImpl(); }
}
#endif // FEATURE_COMINTEROP
- public bool HasElementType {
- [Pure]
- get {return HasElementTypeImpl();}
- }
+ public bool HasElementType
+ {
+ [Pure]
+ get { return HasElementTypeImpl(); }
+ }
+
+ public bool IsContextful
+ {
+ [Pure]
+ get { return IsContextfulImpl(); }
+ }
- public bool IsContextful {
- [Pure]
- get {return IsContextfulImpl();}
+ public bool IsMarshalByRef
+ {
+ [Pure]
+ get { return IsMarshalByRefImpl(); }
}
- 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()
@@ -1228,7 +1322,7 @@ namespace System
// Protected routine to get the attributes.
abstract protected TypeAttributes GetAttributeFlagsImpl();
-
+
// Protected routine to determine if this class represents an Array
abstract protected bool IsArrayImpl();
@@ -1237,31 +1331,34 @@ namespace System
// 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() {
+ 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() {
+ virtual internal bool IsExportedToWindowsRuntimeImpl()
+ {
throw new NotImplementedException();
}
#endif // FEATURE_COMINTEROP
- public virtual Type MakeGenericType(params Type[] typeArguments) {
+ 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()
{
@@ -1278,25 +1375,28 @@ namespace System
abstract public Type GetElementType();
[Pure]
- public virtual Type[] GetGenericArguments()
- {
+ public virtual Type[] GetGenericArguments()
+ {
throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride"));
}
- public virtual Type[] GenericTypeArguments{
- get{
- if(IsGenericType && !IsGenericTypeDefinition){
+ public virtual Type[] GenericTypeArguments
+ {
+ get
+ {
+ if (IsGenericType && !IsGenericTypeDefinition)
+ {
return GetGenericArguments();
}
- else{
+ else
+ {
return Type.EmptyTypes;
}
-
}
}
[Pure]
- public virtual Type GetGenericTypeDefinition()
+ public virtual Type GetGenericTypeDefinition()
{
Contract.Ensures(Contract.Result<Type>() != null);
throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride"));
@@ -1315,7 +1415,7 @@ namespace System
return rootElementType;
}
-#region Enum methods
+ #region Enum methods
// Default implementations of GetEnumNames, GetEnumValues, and GetEnumUnderlyingType
// Subclass of types can override these methods.
@@ -1514,7 +1614,7 @@ namespace System
t == typeof(char) ||
t == typeof(bool));
}
-#endregion
+ #endregion
public virtual bool IsSecurityCritical { [Pure] get { throw new NotImplementedException(); } }
@@ -1562,9 +1662,10 @@ namespace System
// 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 {
+ 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
@@ -1576,29 +1677,30 @@ namespace System
Type p = this;
if (p == c)
return false;
- while (p != null) {
+ 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)
+ 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.
//
@@ -1660,7 +1762,7 @@ namespace System
{
// Interfaces don't derive from other interfaces, they implement them.
// So instead of IsSubclassOf, we should use ImplementInterface instead.
- if (interfaces[i] == ifaceType ||
+ if (interfaces[i] == ifaceType ||
(interfaces[i] != null && interfaces[i].ImplementInterface(ifaceType)))
return true;
}
@@ -1693,12 +1795,13 @@ namespace System
// This method will return an array of classes based upon the array of
// types.
- public static Type[] GetTypeArray(Object[] args) {
+ 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++)
+ for (int i = 0; i < cls.Length; i++)
{
if (args[i] == null)
throw new ArgumentNullException();
@@ -1760,5 +1863,5 @@ namespace System
// 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/TypeLoadException.cs b/src/mscorlib/src/System/TypeLoadException.cs
index 7bc3a1bcce..750e84ffa5 100644
--- a/src/mscorlib/src/System/TypeLoadException.cs
+++ b/src/mscorlib/src/System/TypeLoadException.cs
@@ -10,52 +10,59 @@
**
**
=============================================================================*/
-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")) {
+namespace System
+{
+ [Serializable]
+ public class TypeLoadException : SystemException, ISerializable
+ {
+ public TypeLoadException()
+ : base(Environment.GetResourceString("Arg_TypeLoadException"))
+ {
SetErrorCode(__HResults.COR_E_TYPELOAD);
}
-
- public TypeLoadException(String message)
- : base(message) {
+
+ public TypeLoadException(String message)
+ : base(message)
+ {
SetErrorCode(__HResults.COR_E_TYPELOAD);
}
-
- public TypeLoadException(String message, Exception inner)
- : base(message, inner) {
+
+ public TypeLoadException(String message, Exception inner)
+ : base(message, inner)
+ {
SetErrorCode(__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");
- else {
+ else
+ {
if (AssemblyName == null)
AssemblyName = Environment.GetResourceString("IO_UnknownFileName");
if (ClassName == null)
@@ -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;
+ 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..4dee3d4c88 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;
@@ -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
@@ -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)
{
@@ -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(Environment.GetResourceString("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
index f05d673a74..841a281ea1 100644
--- a/src/mscorlib/src/System/TypeUnloadedException.cs
+++ b/src/mscorlib/src/System/TypeUnloadedException.cs
@@ -11,31 +11,37 @@
**
=============================================================================*/
-namespace System {
-
- using System.Runtime.Serialization;
+using System.Runtime.Serialization;
+
+namespace System
+{
[Serializable]
- public class TypeUnloadedException : SystemException {
- public TypeUnloadedException()
- : base(Environment.GetResourceString("Arg_TypeUnloadedException")) {
+ public class TypeUnloadedException : SystemException
+ {
+ public TypeUnloadedException()
+ : base(Environment.GetResourceString("Arg_TypeUnloadedException"))
+ {
SetErrorCode(__HResults.COR_E_TYPEUNLOADED);
}
-
- public TypeUnloadedException(String message)
- : base(message) {
+
+ public TypeUnloadedException(String message)
+ : base(message)
+ {
SetErrorCode(__HResults.COR_E_TYPEUNLOADED);
}
-
- public TypeUnloadedException(String message, Exception innerException)
- : base(message, innerException) {
+
+ 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) {
+ 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..eb5234ec85 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,7 +23,8 @@ 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)
@@ -43,25 +45,25 @@ namespace System {
if (field.IsInitOnly || field.IsStatic)
throw new ArgumentException(Environment.GetResourceString("Argument_TypedReferenceInvalidField"));
-
+
if (targetType != field.GetDeclaringTypeInternal() && !targetType.IsSubclassOf(field.GetDeclaringTypeInternal()))
throw new MissingMemberException(Environment.GetResourceString("MissingMemberTypeRef"));
RuntimeType fieldType = (RuntimeType)field.FieldType;
if (fieldType.IsPrimitive)
throw new ArgumentException(Environment.GetResourceString("Arg_TypeRefPrimitve"));
-
+
if (i < (flds.Length - 1) && !fieldType.IsValueType)
throw new MissingMemberException(Environment.GetResourceString("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);
}
@@ -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..b9b541273f 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"));
}
- 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,62 +70,73 @@ 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) {
+ catch (OverflowException e)
+ {
throw new OverflowException(Environment.GetResourceString("Overflow_UInt16"), e);
}
@@ -126,110 +145,130 @@ namespace System {
}
[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) {
+ DateTime IConvertible.ToDateTime(IFormatProvider provider)
+ {
throw new InvalidCastException(Environment.GetResourceString("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..503a136e2f 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;
@@ -51,16 +56,19 @@ namespace System {
throw new ArgumentException(Environment.GetResourceString("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,99 @@ 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) {
+ DateTime IConvertible.ToDateTime(IFormatProvider provider)
+ {
throw new InvalidCastException(Environment.GetResourceString("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..f034d17de9 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(Environment.GetResourceString("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,100 @@ 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) {
+ DateTime IConvertible.ToDateTime(IFormatProvider provider)
+ {
throw new InvalidCastException(Environment.GetResourceString("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..09e61a3a50 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) {
+ if (Size == 4 && l > UInt32.MaxValue)
+ {
throw new ArgumentException(Environment.GetResourceString("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/UnitySerializationHolder.cs b/src/mscorlib/src/System/UnitySerializationHolder.cs
index 712391a915..f343cf616c 100644
--- a/src/mscorlib/src/System/UnitySerializationHolder.cs
+++ b/src/mscorlib/src/System/UnitySerializationHolder.cs
@@ -11,39 +11,39 @@ using System.Runtime.Versioning;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
-namespace System {
-
+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 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 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;
+
+ 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.SetType(typeof(UnitySerializationHolder));
info.AddValue("UnityType", MissingUnity);
}
internal static RuntimeType AddElementTypes(SerializationInfo info, RuntimeType type)
{
List<int> elementTypes = new List<int>();
- while(type.HasElementType)
+ while (type.HasElementType)
{
if (type.IsSzArray)
{
@@ -62,7 +62,7 @@ namespace System {
{
elementTypes.Add(ByRef);
}
-
+
type = (RuntimeType)type.GetElementType();
}
@@ -73,7 +73,7 @@ namespace System {
internal Type MakeElementTypes(Type type)
{
- for (int i = m_elementTypes.Length - 1; i >= 0; i --)
+ for (int i = m_elementTypes.Length - 1; i >= 0; i--)
{
if (m_elementTypes[i] == SzArray)
{
@@ -95,7 +95,7 @@ namespace System {
return type;
}
-
+
internal static void GetUnitySerializationInfo(SerializationInfo info, RuntimeType type)
{
if (type.GetRootElementType().IsGenericParameter)
@@ -138,11 +138,11 @@ namespace System {
String assemName;
- if (assembly == null)
+ if (assembly == null)
{
assemName = String.Empty;
- }
- else
+ }
+ else
{
assemName = assembly.FullName;
}
@@ -163,16 +163,16 @@ namespace System {
#endregion
#region Constructor
- internal UnitySerializationHolder(SerializationInfo info, StreamingContext context)
+ 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;
+ return;
if (m_unityType == GenericParameterTypeUnity)
{
@@ -204,14 +204,14 @@ namespace System {
#endregion
#region ISerializable
- public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
+ public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnitySerHolder"));
}
#endregion
#region IObjectReference
- public virtual Object GetRealObject(StreamingContext context)
+ 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.
@@ -220,95 +220,95 @@ namespace System {
Assembly assembly;
- switch (m_unityType)
+ switch (m_unityType)
{
case EmptyUnity:
- {
- return Empty.Value;
- }
+ {
+ return Empty.Value;
+ }
case NullUnity:
- {
- return DBNull.Value;
- }
+ {
+ return DBNull.Value;
+ }
case MissingUnity:
- {
- return Missing.Value;
- }
+ {
+ 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));
- }
+ {
+ 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]);
- }
+ {
+ 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;
- }
+ {
+ 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;
- }
+ {
+ 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_data == null || m_data.Length == 0)
+ ThrowInsufficientInformation("Data");
- if (m_assemblyName == null)
- ThrowInsufficientInformation("AssemblyName");
+ if (m_assemblyName == null)
+ ThrowInsufficientInformation("AssemblyName");
- assembly = Assembly.Load(m_assemblyName);
-
- return assembly;
- }
+ assembly = Assembly.Load(m_assemblyName);
+
+ return assembly;
+ }
default:
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidUnity"));
@@ -316,7 +316,6 @@ namespace System {
}
#endregion
}
-
}
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..3036e5b45d 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;
}
}
diff --git a/src/mscorlib/src/System/Version.cs b/src/mscorlib/src/System/Version.cs
index 7c58d3c0c4..03d45af395 100644
--- a/src/mscorlib/src/System/Version.cs
+++ b/src/mscorlib/src/System/Version.cs
@@ -10,8 +10,9 @@
**
**
===========================================================*/
-namespace System {
+namespace System
+{
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Text;
@@ -33,57 +34,61 @@ namespace System {
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"));
+ 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"));
+ 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"));
+ 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 (minor < 0)
+ throw new ArgumentOutOfRangeException(nameof(minor), Environment.GetResourceString("ArgumentOutOfRange_Version"));
- if (build < 0)
- throw new ArgumentOutOfRangeException(nameof(build),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"));
+ 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) {
+ public Version(String version)
+ {
Version v = Version.Parse(version);
_Major = v.Major;
_Minor = v.Minor;
@@ -91,7 +96,7 @@ namespace System {
_Revision = v.Revision;
}
- public Version()
+ public Version()
{
_Major = 0;
_Minor = 0;
@@ -108,31 +113,38 @@ namespace System {
}
// Properties for setting and getting version numbers
- public int Major {
+ public int Major
+ {
get { return _Major; }
}
-
- public int Minor {
+
+ public int Minor
+ {
get { return _Minor; }
}
-
- public int Build {
+
+ public int Build
+ {
get { return _Build; }
}
-
- public int Revision {
+
+ public int Revision
+ {
get { return _Revision; }
}
- public short MajorRevision {
+ public short MajorRevision
+ {
get { return (short)(_Revision >> 16); }
}
- public short MinorRevision {
+ public short MinorRevision
+ {
get { return (short)(_Revision & 0xFFFF); }
}
-
- public Object Clone() {
+
+ public Object Clone()
+ {
return new Version(this);
}
@@ -164,7 +176,8 @@ namespace System {
0;
}
- public override bool Equals(Object obj) {
+ public override bool Equals(Object obj)
+ {
return Equals(obj as Version);
}
@@ -185,65 +198,68 @@ namespace System {
int accumulator = 0;
- accumulator |= (this._Major & 0x0000000F) << 28;
- accumulator |= (this._Minor & 0x000000FF) << 20;
- accumulator |= (this._Build & 0x000000FF) << 12;
- accumulator |= (this._Revision & 0x00000FFF);
+ accumulator |= (_Major & 0x0000000F) << 28;
+ accumulator |= (_Minor & 0x000000FF) << 20;
+ accumulator |= (_Build & 0x000000FF) << 12;
+ accumulator |= (_Revision & 0x00000FFF);
return accumulator;
}
- public override String ToString() {
- if (_Build == -1) return(ToString(2));
- if (_Revision == -1) return(ToString(3));
- return(ToString(4));
+ public override String ToString()
+ {
+ if (_Build == -1) return (ToString(2));
+ if (_Revision == -1) return (ToString(3));
+ return (ToString(4));
}
-
- public String ToString(int fieldCount) {
+
+ 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)
- {
+ 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);
- 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));
+ 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 (fieldCount == 4)
- {
- sb = StringBuilderCache.Acquire();
- AppendPositiveNumber(_Major, sb);
- sb.Append('.');
- AppendPositiveNumber(_Minor, sb);
- sb.Append('.');
- AppendPositiveNumber(_Build, sb);
- sb.Append('.');
- AppendPositiveNumber(_Revision, sb);
- return StringBuilderCache.GetStringAndRelease(sb);
- }
+ if (_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));
+ throw new ArgumentException(Environment.GetResourceString("ArgumentOutOfRange_Bounds_Lower_Upper", "0", "4"), nameof(fieldCount));
}
}
@@ -253,7 +269,7 @@ namespace System {
// 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 const int ZERO_CHAR_VALUE = (int)'0';
private static void AppendPositiveNumber(int num, StringBuilder sb)
{
Debug.Assert(num >= 0, "AppendPositiveNumber expect positive numbers");
@@ -269,83 +285,105 @@ namespace System {
} while (num > 0);
}
- public static Version Parse(string input) {
- if (input == null) {
+ 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)) {
+ if (!TryParseVersion(input, ref r))
+ {
throw r.GetVersionParseException();
}
return r.m_parsedVersion;
}
- public static bool TryParse(string input, out Version result) {
+ 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) {
+
+ private static bool TryParseVersion(string version, ref VersionResult result)
+ {
int major, minor, build, revision;
- if ((Object)version == null) {
+ if ((Object)version == null)
+ {
result.SetFailure(ParseFailureKind.ArgumentNullException);
return false;
}
String[] parsedComponents = version.Split('.');
int parsedComponentsLength = parsedComponents.Length;
- if ((parsedComponentsLength < 2) || (parsedComponentsLength > 4)) {
+ if ((parsedComponentsLength < 2) || (parsedComponentsLength > 4))
+ {
result.SetFailure(ParseFailureKind.ArgumentException);
return false;
}
- if (!TryParseComponent(parsedComponents[0], nameof(version), ref result, out major)) {
+ if (!TryParseComponent(parsedComponents[0], nameof(version), ref result, out major))
+ {
return false;
}
- if (!TryParseComponent(parsedComponents[1], nameof(version), ref result, out minor)) {
+ 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)) {
+ 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)) {
+ if (parsedComponentsLength > 0)
+ {
+ if (!TryParseComponent(parsedComponents[3], "revision", ref result, out revision))
+ {
return false;
- } else {
+ }
+ else
+ {
result.m_parsedVersion = new Version(major, minor, build, revision);
}
- } else {
+ }
+ else
+ {
result.m_parsedVersion = new Version(major, minor, build);
}
- } else {
+ }
+ 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)) {
+ 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) {
+ if (parsedComponent < 0)
+ {
result.SetFailure(ParseFailureKind.ArgumentOutOfRangeException, componentName);
return false;
}
@@ -353,73 +391,88 @@ namespace System {
return true;
}
- public static bool operator ==(Version v1, Version v2) {
- if (Object.ReferenceEquals(v1, null)) {
+ 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) {
+ public static bool operator !=(Version v1, Version v2)
+ {
return !(v1 == v2);
}
- public static bool operator <(Version v1, Version v2) {
- if ((Object) v1 == null)
+ 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)
+
+ 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) {
+
+ public static bool operator >(Version v1, Version v2)
+ {
return (v2 < v1);
}
-
- public static bool operator >=(Version v1, Version v2) {
+
+ public static bool operator >=(Version v1, Version v2)
+ {
return (v2 <= v1);
}
- internal enum ParseFailureKind {
- ArgumentNullException,
- ArgumentException,
- ArgumentOutOfRangeException,
- FormatException
+ internal enum ParseFailureKind
+ {
+ ArgumentNullException,
+ ArgumentException,
+ ArgumentOutOfRangeException,
+ FormatException
}
- internal struct VersionResult {
+ 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) {
+ internal void Init(string argumentName, bool canThrow)
+ {
m_canThrow = canThrow;
m_argumentName = argumentName;
}
- internal void SetFailure(ParseFailureKind failure) {
+ internal void SetFailure(ParseFailureKind failure)
+ {
SetFailure(failure, String.Empty);
}
- internal void SetFailure(ParseFailureKind failure, string argument) {
+ internal void SetFailure(ParseFailureKind failure, string argument)
+ {
m_failure = failure;
m_exceptionArgument = argument;
- if (m_canThrow) {
+ if (m_canThrow)
+ {
throw GetVersionParseException();
}
}
- internal Exception GetVersionParseException() {
- switch (m_failure) {
+ internal Exception GetVersionParseException()
+ {
+ switch (m_failure)
+ {
case ParseFailureKind.ArgumentNullException:
return new ArgumentNullException(m_argumentName);
case ParseFailureKind.ArgumentException:
@@ -428,11 +481,16 @@ namespace System {
return new ArgumentOutOfRangeException(m_exceptionArgument, Environment.GetResourceString("ArgumentOutOfRange_Version"));
case ParseFailureKind.FormatException:
// Regenerate the FormatException as would be thrown by Int32.Parse()
- try {
+ try
+ {
Int32.Parse(m_exceptionArgument, CultureInfo.InvariantCulture);
- } catch (FormatException e) {
+ }
+ catch (FormatException e)
+ {
return e;
- } catch (OverflowException e) {
+ }
+ catch (OverflowException e)
+ {
return e;
}
Debug.Assert(false, "Int32.Parse() did not throw exception but TryParse failed: " + m_exceptionArgument);
@@ -442,7 +500,6 @@ namespace System {
return new ArgumentException(Environment.GetResourceString("Arg_VersionString"));
}
}
-
}
}
}
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
index 04a8e688e6..7acd7310d0 100644
--- a/src/mscorlib/src/System/XmlIgnoreMemberAttribute.cs
+++ b/src/mscorlib/src/System/XmlIgnoreMemberAttribute.cs
@@ -14,7 +14,7 @@
namespace System
{
- [AttributeUsage(AttributeTargets.Property|AttributeTargets.Field)]
+ [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
index aabb52d803..32d1db3143 100644
--- a/src/mscorlib/src/System/__Filters.cs
+++ b/src/mscorlib/src/System/__Filters.cs
@@ -8,13 +8,15 @@
//
//
-namespace System {
- using System;
- using System.Reflection;
- using System.Globalization;
+using System;
+using System.Reflection;
+using System.Globalization;
+
+namespace System
+{
[Serializable]
- internal class __Filters {
-
+ 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
@@ -25,131 +27,137 @@ namespace System {
// 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)
+ 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:
+
+ switch (m.MemberType)
{
- 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;
- }
+ 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)
+ internal virtual bool FilterName(MemberInfo m, Object filterCriteria)
{
// Check that the criteria object is a String object
- if(filterCriteria == null || !(filterCriteria is String))
+ 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);
+ 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)
+ 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] == '*') {
+ 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)
+ internal virtual bool FilterIgnoreCase(MemberInfo m, Object filterCriteria)
{
// Check that the criteria object is a String object
- if(filterCriteria == null || !(filterCriteria is String))
+ if (filterCriteria == null || !(filterCriteria is String))
throw new InvalidFilterCriteriaException(Environment.GetResourceString("RFLCT.FltCritString"));
-
- String str = (String) filterCriteria;
+
+ 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)
+ 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] == '*') {
+ 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(name, 0, str, 0, str.Length, StringComparison.OrdinalIgnoreCase) == 0);
}
-
- return (String.Compare(str,name, 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..17ad5ae84b 100644
--- a/src/mscorlib/src/mscorlib.Friends.cs
+++ b/src/mscorlib/src/mscorlib.Friends.cs
@@ -1,17 +1,18 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+
using System.Runtime.CompilerServices;
// We need this to be able to typeforward to internal types
-[assembly: InternalsVisibleTo("mscorlib, PublicKey=00240000048000009400000006020000002400005253413100040000010001008d56c76f9e8649383049f383c44be0ec204181822a6c31cf5eb7ef486944d032188ea1d3920763712ccb12d75fb77e9811149e6148e5d32fbaab37611c1878ddc19e20ef135d0cb2cff2bfec3d115810c3d9069638fe4be215dbf795861920e5ab6f7db2e2ceef136ac23d5dd2bf031700aec232f6c6b1c785b4305c123b37ab", AllInternalsVisible=false)]
+[assembly: InternalsVisibleTo("mscorlib, PublicKey=00240000048000009400000006020000002400005253413100040000010001008d56c76f9e8649383049f383c44be0ec204181822a6c31cf5eb7ef486944d032188ea1d3920763712ccb12d75fb77e9811149e6148e5d32fbaab37611c1878ddc19e20ef135d0cb2cff2bfec3d115810c3d9069638fe4be215dbf795861920e5ab6f7db2e2ceef136ac23d5dd2bf031700aec232f6c6b1c785b4305c123b37ab", AllInternalsVisible = false)]
// 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)]