From 5821d7e3cd349af97829cc5d2cc3b6c682a420c1 Mon Sep 17 00:00:00 2001 From: Fadi Hanna Date: Thu, 21 Jun 2018 14:27:26 -0700 Subject: [PATCH 01/69] 1- Fix baseline TOC reading to handle missing/changed contents correctly (we were not handing MissingMemberExceptions, we were just handling TypeLoadExceptions) 2- Fix ordinal assignment bug for nodes that do not exist in a baseline TOC 3- Remove unnecessary counter instructions from type layout TOC data (the counters were initially made so that the TOC tool would know how many items to parse, but it no longer parses the type layout data. Instead, we just ildasm the contents for diffing). [tfs-changeset: 1705044] --- src/ILCompiler.Compiler/src/Compiler/ILStreamReader.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/ILCompiler.Compiler/src/Compiler/ILStreamReader.cs b/src/ILCompiler.Compiler/src/Compiler/ILStreamReader.cs index 8facc05f74b..badf0151aaa 100644 --- a/src/ILCompiler.Compiler/src/Compiler/ILStreamReader.cs +++ b/src/ILCompiler.Compiler/src/Compiler/ILStreamReader.cs @@ -179,9 +179,9 @@ public bool TryReadLdtokenAsTypeSystemEntity(out TypeSystemEntity entity) try { tokenResolved = TryReadLdtoken(out token); - entity = tokenResolved ?(TypeSystemEntity)_methodIL.GetObject(token) : null; + entity = tokenResolved ? (TypeSystemEntity)_methodIL.GetObject(token) : null; } - catch (TypeSystemException.TypeLoadException) + catch (TypeSystemException) { tokenResolved = false; entity = null; From 2bcf67a5f1d0a8f1b97bfa0d5e2e084a9678a0e1 Mon Sep 17 00:00:00 2001 From: Michal Strehovsky Date: Thu, 21 Jun 2018 15:21:18 -0700 Subject: [PATCH 02/69] Allow constructed byref-like types We were not allowing these because we couldn't properly fill out the vtable (can't really make unboxing thunks to put in the vtable). We actually need the vtable, but only because the generic dictionary lives there and reflection might touch it. [tfs-changeset: 1705047] --- .../CompilerTypeSystemContext.BoxedTypes.cs | 37 ++++++++++++- .../DependencyAnalysis/CanonicalEETypeNode.cs | 1 - .../ConstructedEETypeNode.cs | 4 -- tests/src/Simple/Reflection/Reflection.cs | 55 ++++++++++++++++--- 4 files changed, 82 insertions(+), 15 deletions(-) diff --git a/src/ILCompiler.Compiler/src/Compiler/CompilerTypeSystemContext.BoxedTypes.cs b/src/ILCompiler.Compiler/src/Compiler/CompilerTypeSystemContext.BoxedTypes.cs index 44e7ec0386a..71b9720fc1b 100644 --- a/src/ILCompiler.Compiler/src/Compiler/CompilerTypeSystemContext.BoxedTypes.cs +++ b/src/ILCompiler.Compiler/src/Compiler/CompilerTypeSystemContext.BoxedTypes.cs @@ -290,7 +290,17 @@ public BoxedValueType(ModuleDesc owningModule, MetadataType valuetype) Module = owningModule; ValueTypeRepresented = valuetype; - BoxedValue = new BoxedValueField(this); + + // Unboxing thunks for byref-like types don't make sense. Byref-like types cannot be boxed. + // We still allow these to exist in the system, because it's easier than trying to prevent + // their creation. We create them as if they existed (in lieu of e.g. pointing all of them + // to the same __unreachable method body) so that the various places that store pointers to + // them because they want to be able to extract the target instance method can use the same + // mechanism they use for everything else at runtime. + // The main difference is that the "Boxed_ValueType" version has no fields. Reference types + // cannot have byref-like fields. + if (!valuetype.IsByRefLike) + BoxedValue = new BoxedValueField(this); } public override ClassLayoutMetadata GetClassLayout() => default(ClassLayoutMetadata); @@ -332,7 +342,7 @@ protected override TypeFlags ComputeTypeFlags(TypeFlags mask) public override FieldDesc GetField(string name) { - if (name == BoxedValueFieldName) + if (name == BoxedValueFieldName && BoxedValue != null) return BoxedValue; return null; @@ -340,7 +350,10 @@ public override FieldDesc GetField(string name) public override IEnumerable GetFields() { - yield return BoxedValue; + if (BoxedValue != null) + return new FieldDesc[] { BoxedValue }; + + return Array.Empty(); } /// @@ -439,6 +452,15 @@ public override string Name public override MethodIL EmitIL() { + if (_owningType.BoxedValue == null) + { + // If this is the fake unboxing thunk for ByRef-like types, just make a method that throws. + return new ILStubMethodIL(this, + new byte[] { (byte)ILOpcode.ldnull, (byte)ILOpcode.throw_ }, + Array.Empty(), + Array.Empty()); + } + // Generate the unboxing stub. This loosely corresponds to following C#: // return BoxedValue.InstanceMethod(this.m_pEEType, [rest of parameters]) @@ -507,6 +529,15 @@ public override string Name public override MethodIL EmitIL() { + if (_owningType.BoxedValue == null) + { + // If this is the fake unboxing thunk for ByRef-like types, just make a method that throws. + return new ILStubMethodIL(this, + new byte[] { (byte)ILOpcode.ldnull, (byte)ILOpcode.throw_ }, + Array.Empty(), + Array.Empty()); + } + // Generate the unboxing stub. This loosely corresponds to following C#: // return BoxedValue.InstanceMethod([rest of parameters]) diff --git a/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/CanonicalEETypeNode.cs b/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/CanonicalEETypeNode.cs index 07efe41dddb..70e39e6c1db 100644 --- a/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/CanonicalEETypeNode.cs +++ b/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/CanonicalEETypeNode.cs @@ -27,7 +27,6 @@ public CanonicalEETypeNode(NodeFactory factory, TypeDesc type) : base(factory, t Debug.Assert(type.IsCanonicalSubtype(CanonicalFormKind.Any)); Debug.Assert(type == type.ConvertToCanonForm(CanonicalFormKind.Specific)); Debug.Assert(!type.IsMdArray); - Debug.Assert(!type.IsByRefLike); } public override bool StaticDependenciesAreComputed => true; diff --git a/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ConstructedEETypeNode.cs b/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ConstructedEETypeNode.cs index 6f9d6016a75..23a9a47d2b6 100644 --- a/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ConstructedEETypeNode.cs +++ b/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ConstructedEETypeNode.cs @@ -204,10 +204,6 @@ public static bool CreationAllowed(TypeDesc type) if (type.IsCanonicalDefinitionType(CanonicalFormKind.Any)) return false; - // Byref-like types have interior pointers and cannot be heap allocated. - if (type.IsByRefLike) - return false; - // The global "" type can never be allocated. if (((MetadataType)type).IsModuleType) return false; diff --git a/tests/src/Simple/Reflection/Reflection.cs b/tests/src/Simple/Reflection/Reflection.cs index 39c7b211f0a..d66511229a1 100644 --- a/tests/src/Simple/Reflection/Reflection.cs +++ b/tests/src/Simple/Reflection/Reflection.cs @@ -437,7 +437,23 @@ public override string ToString() } } + ref struct ByRefLike + { + public readonly T Value; + + public ByRefLike(T value) + { + Value = value; + } + + public override string ToString() + { + return Value.ToString() + " " + typeof(T).ToString(); + } + } + delegate string ToStringDelegate(ref ByRefLike thisObj); + delegate string ToStringDelegate(ref ByRefLike thisObj); public static void Run() { @@ -449,15 +465,40 @@ public static void Run() default(ByRefLike).ToString(); ToStringDelegate s = null; s = s.Invoke; + default(ByRefLike).ToString(); + ToStringDelegate s2 = null; + s2 = s2.Invoke; } - Type byRefLikeType = GetTestType(nameof(TestByRefLikeTypeMethod), nameof(ByRefLike)); - MethodInfo toStringMethod = byRefLikeType.GetMethod("ToString"); - var toString = (ToStringDelegate)toStringMethod.CreateDelegate(typeof(ToStringDelegate)); + { + Type byRefLikeType = GetTestType(nameof(TestByRefLikeTypeMethod), nameof(ByRefLike)); + MethodInfo toStringMethod = byRefLikeType.GetMethod("ToString"); + var toString = (ToStringDelegate)toStringMethod.CreateDelegate(typeof(ToStringDelegate)); - ByRefLike foo = new ByRefLike(123); - if (toString(ref foo) != "123") - throw new Exception(); + ByRefLike foo = new ByRefLike(123); + if (toString(ref foo) != "123") + throw new Exception(); + } + + { + Type byRefLikeGenericType = typeof(ByRefLike); + MethodInfo toStringGenericMethod = byRefLikeGenericType.GetMethod("ToString"); + var toStringGeneric = (ToStringDelegate)toStringGenericMethod.CreateDelegate(typeof(ToStringDelegate)); + + ByRefLike fooGeneric = new ByRefLike("Hello"); + if (toStringGeneric(ref fooGeneric) != "Hello System.String") + throw new Exception(); + } + + { + Type byRefLikeGenericType = typeof(ByRefLike); + MethodInfo toStringGenericMethod = byRefLikeGenericType.GetMethod("ToString"); + var toStringGeneric = (ToStringDelegate)toStringGenericMethod.CreateDelegate(typeof(ToStringDelegate)); + + ByRefLike fooGeneric = new ByRefLike("Hello"); + if (toStringGeneric(ref fooGeneric) != "Hello System.Object") + throw new Exception(); + } } } @@ -591,4 +632,4 @@ private static bool HasTypeHandle(Type type) } class TestAssemblyAttribute : Attribute { } -class TestModuleAttribute : Attribute { } +class TestModuleAttribute : Attribute { } \ No newline at end of file From 5132d4ae8989e65ac60d80d486efa04ddb63b2c7 Mon Sep 17 00:00:00 2001 From: Stephen Toub Date: Thu, 21 Jun 2018 21:36:59 -0400 Subject: [PATCH 03/69] Update behaviors of new TextWriter StringBuilder overloads (#18578) Two issues addressed: - CancellationToken was being ignored; the overloads should check whether cancellation was requested. This applies to the existing Write{Line}Async overloads that were added in 2.1. - The other overloads support inputs (string, char[], etc.) being null, and just treat that the same as an empty string. We should do the same for StringBuilder rather than throwing. Signed-off-by: dotnet-bot --- .../shared/System/IO/TextWriter.cs | 32 +++++++++++++------ 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/src/System.Private.CoreLib/shared/System/IO/TextWriter.cs b/src/System.Private.CoreLib/shared/System/IO/TextWriter.cs index c41dabd35dc..0acb4d18cf6 100644 --- a/src/System.Private.CoreLib/shared/System/IO/TextWriter.cs +++ b/src/System.Private.CoreLib/shared/System/IO/TextWriter.cs @@ -559,18 +559,17 @@ public virtual Task WriteAsync(string value) /// The string (as a StringBuilder) to write to the stream public virtual Task WriteAsync(StringBuilder value, CancellationToken cancellationToken = default) { - // Do the argument checking before 'going async' so you get it early - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - // Then do the rest which may be deferred (done in the returned Task) - return WriteAsyncCore(value, cancellationToken); + return + cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : + value == null ? Task.CompletedTask : + WriteAsyncCore(value, cancellationToken); async Task WriteAsyncCore(StringBuilder sb, CancellationToken ct) { foreach (ReadOnlyMemory chunk in sb.GetChunks()) + { await WriteAsync(chunk, ct).ConfigureAwait(false); + } } } @@ -596,6 +595,7 @@ public virtual Task WriteAsync(char[] buffer, int index, int count) } public virtual Task WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) => + cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : MemoryMarshal.TryGetArray(buffer, out ArraySegment array) ? WriteAsync(array.Array, array.Offset, array.Count) : Task.Factory.StartNew(state => @@ -631,10 +631,21 @@ public virtual Task WriteLineAsync(string value) /// StringBuilder.GetChunks() method to avoid creating the intermediate string /// /// The string (as a StringBuilder) to write to the stream - public async virtual Task WriteLineAsync(StringBuilder value, CancellationToken cancellationToken = default) + public virtual Task WriteLineAsync(StringBuilder value, CancellationToken cancellationToken = default) { - await WriteAsync(value, cancellationToken).ConfigureAwait(false); - await WriteAsync(CoreNewLine, cancellationToken).ConfigureAwait(false); + return + cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : + value == null ? WriteAsync(CoreNewLine, cancellationToken) : + WriteLineAsyncCore(value, cancellationToken); + + async Task WriteLineAsyncCore(StringBuilder sb, CancellationToken ct) + { + foreach (ReadOnlyMemory chunk in sb.GetChunks()) + { + await WriteAsync(chunk, ct).ConfigureAwait(false); + } + await WriteAsync(CoreNewLine, ct).ConfigureAwait(false); + } } public Task WriteLineAsync(char[] buffer) @@ -659,6 +670,7 @@ public virtual Task WriteLineAsync(char[] buffer, int index, int count) } public virtual Task WriteLineAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) => + cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : MemoryMarshal.TryGetArray(buffer, out ArraySegment array) ? WriteLineAsync(array.Array, array.Offset, array.Count) : Task.Factory.StartNew(state => From 4f98b1f44fcca8cac9c3a669e40bdd71a5d18c95 Mon Sep 17 00:00:00 2001 From: Anirudh Agnihotry Date: Thu, 21 Jun 2018 18:39:23 -0700 Subject: [PATCH 04/69] Moved Semaphore.cs and Semaphore.Windows.cs to shared (#18597) * TryOpenexistingworker and createsemaphore moved to semaphore.windows.cs * Common code moved to verifyCounts and CreateMutexCore and then moved to semaphore.windows.cs * CreateSemaphore merged with CreateSemaphore core * Moving interop functions from win32Native to inteop.kernel32 * Moving the files to shared * Minor Formating Signed-off-by: dotnet-bot --- .../Windows/Kernel32/Interop.Constants.cs | 1 + .../Windows/Kernel32/Interop.Semaphore.cs | 23 +++++ .../System.Private.CoreLib.Shared.projitems | 3 + .../System/Threading/Semaphore.Windows.cs | 91 +++++++++++++++++++ .../shared/System/Threading/Semaphore.cs | 75 +++++++++++++++ 5 files changed, 193 insertions(+) create mode 100644 src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.Semaphore.cs create mode 100644 src/System.Private.CoreLib/shared/System/Threading/Semaphore.Windows.cs create mode 100644 src/System.Private.CoreLib/shared/System/Threading/Semaphore.cs diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.Constants.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.Constants.cs index 8437f4b8f89..59dace98e04 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.Constants.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.Constants.cs @@ -9,5 +9,6 @@ internal static partial class Kernel32 internal const int MAXIMUM_ALLOWED = 0x02000000; internal const int SYNCHRONIZE = 0x00100000; internal const int MUTEX_MODIFY_STATE = 0x00000001; + internal const int SEMAPHORE_MODIFY_STATE = 0x00000002; } } diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.Semaphore.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.Semaphore.cs new file mode 100644 index 00000000000..6d1467b25dd --- /dev/null +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.Semaphore.cs @@ -0,0 +1,23 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using Microsoft.Win32.SafeHandles; +using System; +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static partial class Kernel32 + { + [DllImport(Interop.Libraries.Kernel32, SetLastError = true, CharSet = CharSet.Unicode)] + internal static extern SafeWaitHandle OpenSemaphore(uint desiredAccess, bool inheritHandle, string name); + + [DllImport(Libraries.Kernel32, SetLastError = true, CharSet = CharSet.Unicode)] + internal static extern SafeWaitHandle CreateSemaphoreEx(IntPtr lpSecurityAttributes, int initialCount, int maximumCount, string name, uint flags, uint desiredAccess); + + [DllImport(Interop.Libraries.Kernel32, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool ReleaseSemaphore(SafeWaitHandle handle, int releaseCount, out int previousCount); + } +} diff --git a/src/System.Private.CoreLib/shared/System.Private.CoreLib.Shared.projitems b/src/System.Private.CoreLib/shared/System.Private.CoreLib.Shared.projitems index 7ee032144da..eeef09bc67c 100644 --- a/src/System.Private.CoreLib/shared/System.Private.CoreLib.Shared.projitems +++ b/src/System.Private.CoreLib/shared/System.Private.CoreLib.Shared.projitems @@ -591,6 +591,7 @@ + @@ -812,8 +813,10 @@ + + diff --git a/src/System.Private.CoreLib/shared/System/Threading/Semaphore.Windows.cs b/src/System.Private.CoreLib/shared/System/Threading/Semaphore.Windows.cs new file mode 100644 index 00000000000..f1015647989 --- /dev/null +++ b/src/System.Private.CoreLib/shared/System/Threading/Semaphore.Windows.cs @@ -0,0 +1,91 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using Microsoft.Win32.SafeHandles; +using System.Diagnostics; +using System.IO; +using System.Runtime.InteropServices; + +namespace System.Threading +{ + public sealed partial class Semaphore + { + private const uint AccessRights = (uint)Interop.Kernel32.MAXIMUM_ALLOWED | Interop.Kernel32.SYNCHRONIZE | Interop.Kernel32.SEMAPHORE_MODIFY_STATE; + + private Semaphore(SafeWaitHandle handle) + { + SafeWaitHandle = handle; + } + + private void CreateSemaphoreCore(int initialCount, int maximumCount, string name, out bool createdNew) + { + Debug.Assert(initialCount >= 0); + Debug.Assert(maximumCount >= 1); + Debug.Assert(initialCount <= maximumCount); + +#if PLATFORM_UNIX + if (name != null) + throw new PlatformNotSupportedException(SR.PlatformNotSupported_NamedSynchronizationPrimitives); +#endif + SafeWaitHandle myHandle = Interop.Kernel32.CreateSemaphoreEx(IntPtr.Zero, initialCount, maximumCount, name, 0, AccessRights); + + int errorCode = Marshal.GetLastWin32Error(); + if (myHandle.IsInvalid) + { + if (name != null && name.Length != 0 && errorCode == Interop.Errors.ERROR_INVALID_HANDLE) + throw new WaitHandleCannotBeOpenedException( + SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name)); + + throw Win32Marshal.GetExceptionForLastWin32Error(); + } + createdNew = errorCode != Interop.Errors.ERROR_ALREADY_EXISTS; + this.SafeWaitHandle = myHandle; + } + + private static OpenExistingResult OpenExistingWorker(string name, out Semaphore result) + { +#if PLATFORM_WINDOWS + if (name == null) + throw new ArgumentNullException(nameof(name)); + if (name.Length == 0) + throw new ArgumentException(SR.Argument_EmptyName, nameof(name)); + + //Pass false to OpenSemaphore to prevent inheritedHandles + SafeWaitHandle myHandle = Interop.Kernel32.OpenSemaphore(AccessRights, false, name); + + if (myHandle.IsInvalid) + { + result = null; + int errorCode = Marshal.GetLastWin32Error(); + + if (errorCode == Interop.Errors.ERROR_FILE_NOT_FOUND || errorCode == Interop.Errors.ERROR_INVALID_NAME) + return OpenExistingResult.NameNotFound; + if (errorCode == Interop.Errors.ERROR_PATH_NOT_FOUND) + return OpenExistingResult.PathNotFound; + if (name != null && name.Length != 0 && errorCode == Interop.Errors.ERROR_INVALID_HANDLE) + return OpenExistingResult.NameInvalid; + //this is for passed through NativeMethods Errors + throw Win32Marshal.GetExceptionForLastWin32Error(); + } + + result = new Semaphore(myHandle); + return OpenExistingResult.Success; +#else + throw new PlatformNotSupportedException(SR.PlatformNotSupported_NamedSynchronizationPrimitives); +#endif + } + + private int ReleaseCore(int releaseCount) + { + // If ReleaseSempahore returns false when the specified value would cause + // the semaphore's count to exceed the maximum count set when Semaphore was created + // Non-Zero return + int previousCount; + if (!Interop.Kernel32.ReleaseSemaphore(SafeWaitHandle, releaseCount, out previousCount)) + throw new SemaphoreFullException(); + + return previousCount; + } + } +} diff --git a/src/System.Private.CoreLib/shared/System/Threading/Semaphore.cs b/src/System.Private.CoreLib/shared/System/Threading/Semaphore.cs new file mode 100644 index 00000000000..8e4ad766070 --- /dev/null +++ b/src/System.Private.CoreLib/shared/System/Threading/Semaphore.cs @@ -0,0 +1,75 @@ +// Licensed to the .NET Foundation under one or more agreements. +// 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 Microsoft.Win32.SafeHandles; +using System.IO; +using System.Runtime.InteropServices; + +namespace System.Threading +{ + public sealed partial class Semaphore : WaitHandle + { + // creates a nameless semaphore object + // Win32 only takes maximum count of Int32.MaxValue + public Semaphore(int initialCount, int maximumCount) : this(initialCount, maximumCount, null) { } + + public Semaphore(int initialCount, int maximumCount, string name) + { + VerifyCounts(initialCount, maximumCount); + + bool createdNew; + CreateSemaphoreCore(initialCount, maximumCount, name, out createdNew); + } + + public Semaphore(int initialCount, int maximumCount, string name, out bool createdNew) + { + VerifyCounts(initialCount, maximumCount); + + CreateSemaphoreCore(initialCount, maximumCount, name, out createdNew); + } + + private static void VerifyCounts(int initialCount, int maximumCount) + { + if (initialCount < 0) + throw new ArgumentOutOfRangeException(nameof(initialCount), SR.ArgumentOutOfRange_NeedNonNegNum); + + if (maximumCount < 1) + throw new ArgumentOutOfRangeException(nameof(maximumCount), SR.ArgumentOutOfRange_NeedPosNum); + + if (initialCount > maximumCount) + throw new ArgumentException(SR.Argument_SemaphoreInitialMaximum); + } + + public static Semaphore OpenExisting(string name) + { + Semaphore result; + switch (OpenExistingWorker(name, out result)) + { + case OpenExistingResult.NameNotFound: + throw new WaitHandleCannotBeOpenedException(); + case OpenExistingResult.NameInvalid: + throw new WaitHandleCannotBeOpenedException(SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name)); + case OpenExistingResult.PathNotFound: + throw new IOException(SR.Format(SR.IO_PathNotFound_Path, name)); + default: + return result; + } + } + + public static bool TryOpenExisting(string name, out Semaphore result) => + OpenExistingWorker(name, out result) == OpenExistingResult.Success; + + public int Release() => ReleaseCore(1); + + // increase the count on a semaphore, returns previous count + public int Release(int releaseCount) + { + if (releaseCount < 1) + throw new ArgumentOutOfRangeException(nameof(releaseCount), SR.ArgumentOutOfRange_NeedNonNegNum); + + return ReleaseCore(releaseCount); + } + } +} From bf22f5593b79d2647d86d24b21af021707c198d2 Mon Sep 17 00:00:00 2001 From: Anipik Date: Fri, 22 Jun 2018 11:32:13 -0700 Subject: [PATCH 05/69] Non Shared Changed And feedback --- .../Windows/mincore/Interop.Threading.cs | 18 --- .../Interop/Windows/Kernel32/Interop.Mutex.cs | 4 +- .../Windows/Kernel32/Interop.Semaphore.cs | 5 +- .../System/Threading/Semaphore.Windows.cs | 11 +- .../shared/System/Threading/Semaphore.cs | 16 +-- .../src/Resources/Strings.resx | 3 - .../src/System.Private.CoreLib.csproj | 2 - .../src/System/Threading/Semaphore.Unix.cs | 22 +++- .../src/System/Threading/Semaphore.Windows.cs | 93 -------------- .../src/System/Threading/Semaphore.cs | 114 ------------------ 10 files changed, 32 insertions(+), 256 deletions(-) delete mode 100644 src/System.Private.CoreLib/src/System/Threading/Semaphore.Windows.cs delete mode 100644 src/System.Private.CoreLib/src/System/Threading/Semaphore.cs diff --git a/src/Common/src/Interop/Windows/mincore/Interop.Threading.cs b/src/Common/src/Interop/Windows/mincore/Interop.Threading.cs index 23477e361d2..5f89ed6a104 100644 --- a/src/Common/src/Interop/Windows/mincore/Interop.Threading.cs +++ b/src/Common/src/Interop/Windows/mincore/Interop.Threading.cs @@ -13,21 +13,9 @@ internal static partial class mincore [DllImport(Libraries.Kernel32, EntryPoint = "CreateEventExW", SetLastError = true, CharSet = CharSet.Unicode)] internal extern static SafeWaitHandle CreateEventEx(IntPtr lpEventAttributes, string lpName, uint dwFlags, uint dwDesiredAccess); - [DllImport(Libraries.Kernel32, EntryPoint = "CreateSemaphoreExW", SetLastError = true, CharSet = CharSet.Unicode)] - internal static extern SafeWaitHandle CreateSemaphoreEx(IntPtr lpSemaphoreAttributes, int lInitialCount, int lMaximumCount, string lpName, uint dwFlags, uint dwDesiredAccess); - - [DllImport(Libraries.Kernel32, EntryPoint = "CreateMutexExW", SetLastError = true, CharSet = CharSet.Unicode)] - internal extern static SafeWaitHandle CreateMutexEx(IntPtr lpMutexAttributes, string lpName, uint dwFlags, uint dwDesiredAccess); - [DllImport(Libraries.Kernel32, EntryPoint = "OpenEventW", SetLastError = true, CharSet = CharSet.Unicode)] internal extern static SafeWaitHandle OpenEvent(uint dwDesiredAccess, bool bInheritHandle, string lpName); - [DllImport(Libraries.Kernel32, EntryPoint = "OpenSemaphoreW", SetLastError = true, CharSet = CharSet.Unicode)] - internal extern static SafeWaitHandle OpenSemaphore(uint dwDesiredAccess, bool bInheritHandle, string lpName); - - [DllImport(Libraries.Kernel32, EntryPoint = "OpenMutexW", SetLastError = true, CharSet = CharSet.Unicode)] - internal extern static SafeWaitHandle OpenMutex(uint dwDesiredAccess, bool bInheritHandle, string lpName); - [DllImport(Libraries.Kernel32)] internal extern static bool ResetEvent(IntPtr hEvent); @@ -37,12 +25,6 @@ internal static partial class mincore [DllImport(Libraries.Kernel32)] internal extern static bool SetEvent(SafeWaitHandle hEvent); - [DllImport(Libraries.Kernel32)] - internal extern static bool ReleaseSemaphore(IntPtr hSemaphore, int lReleaseCount, out int lpPreviousCount); - - [DllImport(Libraries.Kernel32)] - internal extern static bool ReleaseMutex(IntPtr hMutex); - [DllImport(Libraries.Kernel32)] internal extern static uint WaitForMultipleObjectsEx(uint nCount, IntPtr lpHandles, bool bWaitAll, uint dwMilliseconds, bool bAlertable); diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.Mutex.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.Mutex.cs index f8585148db4..cbb306e4f71 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.Mutex.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.Mutex.cs @@ -12,10 +12,10 @@ internal static partial class Kernel32 { internal const uint CREATE_MUTEX_INITIAL_OWNER = 0x1; - [DllImport(Interop.Libraries.Kernel32, SetLastError = true, CharSet = CharSet.Unicode)] + [DllImport(Interop.Libraries.Kernel32, EntryPoint = "OpenMutexW", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern SafeWaitHandle OpenMutex(uint desiredAccess, bool inheritHandle, string name); - [DllImport(Interop.Libraries.Kernel32, SetLastError = true, CharSet = CharSet.Unicode)] + [DllImport(Interop.Libraries.Kernel32, EntryPoint = "CreateMutexExW", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern SafeWaitHandle CreateMutexEx(IntPtr lpMutexAttributes, string name, uint flags, uint desiredAccess); [DllImport(Interop.Libraries.Kernel32, SetLastError = true)] diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.Semaphore.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.Semaphore.cs index 6d1467b25dd..94648a70779 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.Semaphore.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.Semaphore.cs @@ -10,14 +10,13 @@ internal static partial class Interop { internal static partial class Kernel32 { - [DllImport(Interop.Libraries.Kernel32, SetLastError = true, CharSet = CharSet.Unicode)] + [DllImport(Interop.Libraries.Kernel32, EntryPoint = "OpenSemaphoreW", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern SafeWaitHandle OpenSemaphore(uint desiredAccess, bool inheritHandle, string name); - [DllImport(Libraries.Kernel32, SetLastError = true, CharSet = CharSet.Unicode)] + [DllImport(Libraries.Kernel32, EntryPoint = "CreateSemaphoreExW", SetLastError = true, CharSet = CharSet.Unicode)] internal static extern SafeWaitHandle CreateSemaphoreEx(IntPtr lpSecurityAttributes, int initialCount, int maximumCount, string name, uint flags, uint desiredAccess); [DllImport(Interop.Libraries.Kernel32, SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool ReleaseSemaphore(SafeWaitHandle handle, int releaseCount, out int previousCount); } } diff --git a/src/System.Private.CoreLib/shared/System/Threading/Semaphore.Windows.cs b/src/System.Private.CoreLib/shared/System/Threading/Semaphore.Windows.cs index f1015647989..8a14f5ef389 100644 --- a/src/System.Private.CoreLib/shared/System/Threading/Semaphore.Windows.cs +++ b/src/System.Private.CoreLib/shared/System/Threading/Semaphore.Windows.cs @@ -24,7 +24,7 @@ private void CreateSemaphoreCore(int initialCount, int maximumCount, string name Debug.Assert(maximumCount >= 1); Debug.Assert(initialCount <= maximumCount); -#if PLATFORM_UNIX +#if !PLATFORM_WINDOWS if (name != null) throw new PlatformNotSupportedException(SR.PlatformNotSupported_NamedSynchronizationPrimitives); #endif @@ -51,7 +51,7 @@ private static OpenExistingResult OpenExistingWorker(string name, out Semaphore if (name.Length == 0) throw new ArgumentException(SR.Argument_EmptyName, nameof(name)); - //Pass false to OpenSemaphore to prevent inheritedHandles + // Pass false to OpenSemaphore to prevent inheritedHandles SafeWaitHandle myHandle = Interop.Kernel32.OpenSemaphore(AccessRights, false, name); if (myHandle.IsInvalid) @@ -59,13 +59,13 @@ private static OpenExistingResult OpenExistingWorker(string name, out Semaphore result = null; int errorCode = Marshal.GetLastWin32Error(); - if (errorCode == Interop.Errors.ERROR_FILE_NOT_FOUND || errorCode == Interop.Errors.ERROR_INVALID_NAME) + if (errorCode == Interop.Errors.ERROR_FILE_NOT_FOUND || errorCode == Interop.Errors.ERROR_INVALID_NAME) return OpenExistingResult.NameNotFound; if (errorCode == Interop.Errors.ERROR_PATH_NOT_FOUND) return OpenExistingResult.PathNotFound; if (name != null && name.Length != 0 && errorCode == Interop.Errors.ERROR_INVALID_HANDLE) return OpenExistingResult.NameInvalid; - //this is for passed through NativeMethods Errors + // this is for passed through NativeMethods Errors throw Win32Marshal.GetExceptionForLastWin32Error(); } @@ -78,9 +78,6 @@ private static OpenExistingResult OpenExistingWorker(string name, out Semaphore private int ReleaseCore(int releaseCount) { - // If ReleaseSempahore returns false when the specified value would cause - // the semaphore's count to exceed the maximum count set when Semaphore was created - // Non-Zero return int previousCount; if (!Interop.Kernel32.ReleaseSemaphore(SafeWaitHandle, releaseCount, out previousCount)) throw new SemaphoreFullException(); diff --git a/src/System.Private.CoreLib/shared/System/Threading/Semaphore.cs b/src/System.Private.CoreLib/shared/System/Threading/Semaphore.cs index 8e4ad766070..1135a1f911a 100644 --- a/src/System.Private.CoreLib/shared/System/Threading/Semaphore.cs +++ b/src/System.Private.CoreLib/shared/System/Threading/Semaphore.cs @@ -15,22 +15,12 @@ public sealed partial class Semaphore : WaitHandle // Win32 only takes maximum count of Int32.MaxValue public Semaphore(int initialCount, int maximumCount) : this(initialCount, maximumCount, null) { } - public Semaphore(int initialCount, int maximumCount, string name) + public Semaphore(int initialCount, int maximumCount, string name) : + this(initialCount, maximumCount, name, out _) { - VerifyCounts(initialCount, maximumCount); - - bool createdNew; - CreateSemaphoreCore(initialCount, maximumCount, name, out createdNew); } public Semaphore(int initialCount, int maximumCount, string name, out bool createdNew) - { - VerifyCounts(initialCount, maximumCount); - - CreateSemaphoreCore(initialCount, maximumCount, name, out createdNew); - } - - private static void VerifyCounts(int initialCount, int maximumCount) { if (initialCount < 0) throw new ArgumentOutOfRangeException(nameof(initialCount), SR.ArgumentOutOfRange_NeedNonNegNum); @@ -40,6 +30,8 @@ private static void VerifyCounts(int initialCount, int maximumCount) if (initialCount > maximumCount) throw new ArgumentException(SR.Argument_SemaphoreInitialMaximum); + + CreateSemaphoreCore(initialCount, maximumCount, name, out createdNew); } public static Semaphore OpenExisting(string name) diff --git a/src/System.Private.CoreLib/src/Resources/Strings.resx b/src/System.Private.CoreLib/src/Resources/Strings.resx index 9043b6e4bdc..5b870d38bae 100644 --- a/src/System.Private.CoreLib/src/Resources/Strings.resx +++ b/src/System.Private.CoreLib/src/Resources/Strings.resx @@ -714,9 +714,6 @@ Non-negative number required. - - Non-negative number required. - The ID parameter must be in the range {0} through {1}. diff --git a/src/System.Private.CoreLib/src/System.Private.CoreLib.csproj b/src/System.Private.CoreLib/src/System.Private.CoreLib.csproj index 91019342b5a..7cbebfe131e 100644 --- a/src/System.Private.CoreLib/src/System.Private.CoreLib.csproj +++ b/src/System.Private.CoreLib/src/System.Private.CoreLib.csproj @@ -312,7 +312,6 @@ - @@ -499,7 +498,6 @@ - diff --git a/src/System.Private.CoreLib/src/System/Threading/Semaphore.Unix.cs b/src/System.Private.CoreLib/src/System/Threading/Semaphore.Unix.cs index 3f82294bf7e..04f34bce4bd 100644 --- a/src/System.Private.CoreLib/src/System/Threading/Semaphore.Unix.cs +++ b/src/System.Private.CoreLib/src/System/Threading/Semaphore.Unix.cs @@ -2,8 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using Microsoft.Win32.SafeHandles; using System.Diagnostics; using System.IO; +using System.Runtime.InteropServices; namespace System.Threading { @@ -25,9 +27,25 @@ private static OpenExistingResult OpenExistingWorker(string name, out Semaphore throw new PlatformNotSupportedException(SR.PlatformNotSupported_NamedSynchronizationPrimitives); } - private static int ReleaseCore(IntPtr handle, int releaseCount) + private int ReleaseCore(int releaseCount) { - return WaitSubsystem.ReleaseSemaphore(handle, releaseCount); + // The field value is modifiable via the public property, save it locally + // to ensure that one instance is used in all places in this method + SafeWaitHandle waitHandle = _waitHandle; + if (waitHandle == null) + { + ThrowInvalidHandleException(); + } + + waitHandle.DangerousAddRef(); + try + { + return WaitSubsystem.ReleaseSemaphore(waitHandle.DangerousGetHandle(), releaseCount); + } + finally + { + waitHandle.DangerousRelease(); + } } } } diff --git a/src/System.Private.CoreLib/src/System/Threading/Semaphore.Windows.cs b/src/System.Private.CoreLib/src/System/Threading/Semaphore.Windows.cs deleted file mode 100644 index 764d57ee601..00000000000 --- a/src/System.Private.CoreLib/src/System/Threading/Semaphore.Windows.cs +++ /dev/null @@ -1,93 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Diagnostics; -using System.Runtime.InteropServices; -using Microsoft.Win32.SafeHandles; - -namespace System.Threading -{ - public sealed partial class Semaphore - { - private const uint AccessRights = (uint)Interop.Kernel32.MAXIMUM_ALLOWED | Interop.Kernel32.SYNCHRONIZE | (uint)Interop.Constants.SemaphoreModifyState; - - private Semaphore(SafeWaitHandle handle) - { - SafeWaitHandle = handle; - } - - private void CreateSemaphoreCore(int initialCount, int maximumCount, string name, out bool createdNew) - { - Debug.Assert(initialCount >= 0); - Debug.Assert(maximumCount >= 1); - Debug.Assert(initialCount <= maximumCount); - - SafeWaitHandle myHandle = Interop.mincore.CreateSemaphoreEx(IntPtr.Zero, initialCount, maximumCount, name, 0, AccessRights); - - if (myHandle.IsInvalid) - { - int errorCode = Marshal.GetLastWin32Error(); - if (null != name && 0 != name.Length && Interop.Errors.ERROR_INVALID_HANDLE == errorCode) - throw new WaitHandleCannotBeOpenedException(SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name)); - throw ExceptionFromCreationError(errorCode, name); - } - else if (name != null) - { - int errorCode = Marshal.GetLastWin32Error(); - createdNew = errorCode != Interop.Errors.ERROR_ALREADY_EXISTS; - } - else - { - createdNew = true; - } - - SafeWaitHandle = myHandle; - } - - private static OpenExistingResult OpenExistingWorker(string name, out Semaphore result) - { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - if (name.Length == 0) - { - throw new ArgumentException(SR.Argument_EmptyName, nameof(name)); - } - - result = null; - - SafeWaitHandle myHandle = Interop.mincore.OpenSemaphore(AccessRights, false, name); - - if (myHandle.IsInvalid) - { - int errorCode = Marshal.GetLastWin32Error(); - - if (Interop.Errors.ERROR_FILE_NOT_FOUND == errorCode || Interop.Errors.ERROR_INVALID_NAME == errorCode) - return OpenExistingResult.NameNotFound; - if (Interop.Errors.ERROR_PATH_NOT_FOUND == errorCode) - return OpenExistingResult.PathNotFound; - if (null != name && 0 != name.Length && Interop.Errors.ERROR_INVALID_HANDLE == errorCode) - return OpenExistingResult.NameInvalid; - - throw ExceptionFromCreationError(errorCode, name); - } - result = new Semaphore(myHandle); - return OpenExistingResult.Success; - } - - private static int ReleaseCore(IntPtr handle, int releaseCount) - { - Debug.Assert(releaseCount > 0); - - int previousCount; - if (!Interop.mincore.ReleaseSemaphore(handle, releaseCount, out previousCount)) - { - ThrowSignalOrUnsignalException(); - } - - return previousCount; - } - } -} diff --git a/src/System.Private.CoreLib/src/System/Threading/Semaphore.cs b/src/System.Private.CoreLib/src/System/Threading/Semaphore.cs deleted file mode 100644 index 243cbc0da59..00000000000 --- a/src/System.Private.CoreLib/src/System/Threading/Semaphore.cs +++ /dev/null @@ -1,114 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.IO; -using Microsoft.Win32; -using Microsoft.Win32.SafeHandles; -using System.Runtime.InteropServices; -using System.Threading; -using System.Runtime.Versioning; - -namespace System.Threading -{ - public sealed partial class Semaphore : WaitHandle - { - // creates a nameless semaphore object - // Win32 only takes maximum count of Int32.MaxValue - public Semaphore(int initialCount, int maximumCount) - { - VerifyCounts(initialCount, maximumCount); - - bool createdNew; - CreateSemaphoreCore(initialCount, maximumCount, null, out createdNew); - } - - public Semaphore(int initialCount, int maximumCount, string name) - { - VerifyCounts(initialCount, maximumCount); - - bool createdNew; - CreateSemaphoreCore(initialCount, maximumCount, name, out createdNew); - } - - public Semaphore(int initialCount, int maximumCount, string name, out bool createdNew) - { - VerifyCounts(initialCount, maximumCount); - - CreateSemaphoreCore(initialCount, maximumCount, name, out createdNew); - } - - private static void VerifyCounts(int initialCount, int maximumCount) - { - if (initialCount < 0) - { - throw new ArgumentOutOfRangeException(nameof(initialCount), SR.ArgumentOutOfRange_NeedNonNegNumRequired); - } - - if (maximumCount < 1) - { - throw new ArgumentOutOfRangeException(nameof(maximumCount), SR.ArgumentOutOfRange_NeedNonNegNumRequired); - } - - if (initialCount > maximumCount) - { - throw new ArgumentException(SR.Argument_SemaphoreInitialMaximum); - } - } - - public static Semaphore OpenExisting(string name) - { - Semaphore result; - switch (OpenExistingWorker(name, out result)) - { - case OpenExistingResult.NameNotFound: - throw new WaitHandleCannotBeOpenedException(); - case OpenExistingResult.NameInvalid: - throw new WaitHandleCannotBeOpenedException(SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name)); - case OpenExistingResult.PathNotFound: - throw new IOException(SR.Format(SR.IO_PathNotFound_Path, name)); - default: - return result; - } - } - - public static bool TryOpenExisting(string name, out Semaphore result) => - OpenExistingWorker(name, out result) == OpenExistingResult.Success; - - // increase the count on a semaphore, returns previous count - public int Release() => ReleaseCore(1); - - // increase the count on a semaphore, returns previous count - public int Release(int releaseCount) - { - if (releaseCount < 1) - { - throw new ArgumentOutOfRangeException(nameof(releaseCount), SR.ArgumentOutOfRange_NeedNonNegNumRequired); - } - - return ReleaseCore(releaseCount); - } - - private int ReleaseCore(int releaseCount) - { - // The field value is modifiable via the public property, save it locally - // to ensure that one instance is used in all places in this method - SafeWaitHandle waitHandle = _waitHandle; - if (waitHandle == null) - { - ThrowInvalidHandleException(); - } - - waitHandle.DangerousAddRef(); - try - { - return ReleaseCore(waitHandle.DangerousGetHandle(), releaseCount); - } - finally - { - waitHandle.DangerousRelease(); - } - } - } -} - From a1aa613d7e694f4f9daab1155e1c8e981f93327f Mon Sep 17 00:00:00 2001 From: Jan Kotas Date: Fri, 22 Jun 2018 14:11:41 -0700 Subject: [PATCH 06/69] Fix WebApi sample (#5995) --- samples/WebApi/README.md | 4 +++- samples/WebApi/Startup.cs | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/samples/WebApi/README.md b/samples/WebApi/README.md index 48a24316447..338f4c1bd17 100644 --- a/samples/WebApi/README.md +++ b/samples/WebApi/README.md @@ -48,7 +48,9 @@ services.AddMvc(); to ```csharp -services.Add(new ServiceDescriptor(typeof(ApplicationPartManager), new ApplicationPartManager())); +var applicationPartManager = new ApplicationPartManager(); +applicationPartManager.ApplicationParts.Add(new AssemblyPart(typeof(Startup).Assembly)); +services.Add(new ServiceDescriptor(typeof(ApplicationPartManager), applicationPartManager)); services.AddMvcCore().AddJsonFormatters(); ``` diff --git a/samples/WebApi/Startup.cs b/samples/WebApi/Startup.cs index 3a18970c672..ec0db593a44 100644 --- a/samples/WebApi/Startup.cs +++ b/samples/WebApi/Startup.cs @@ -29,7 +29,9 @@ public Startup(IConfiguration configuration) public void ConfigureServices(IServiceCollection services) { // Override automatic discovery of Application parts done by MVC. It is not compatible with single file compilation. - services.Add(new ServiceDescriptor(typeof(ApplicationPartManager), new ApplicationPartManager())); + var applicationPartManager = new ApplicationPartManager(); + applicationPartManager.ApplicationParts.Add(new AssemblyPart(typeof(Startup).Assembly)); + services.Add(new ServiceDescriptor(typeof(ApplicationPartManager), applicationPartManager)); services.AddMvcCore().AddJsonFormatters(); } From 05937b1ecea034b354ab59ef890a79c4f2510b84 Mon Sep 17 00:00:00 2001 From: Jan Kotas Date: Fri, 22 Jun 2018 19:21:31 -0700 Subject: [PATCH 07/69] Fix bug in Overlapped refactoring The return value of Overlapped.Pack was freed on success path incorrectly. Thanks for Chris Ahna for catching it. [tfs-changeset: 1705363] --- .../src/System/Threading/Overlapped.cs | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/System.Private.CoreLib/src/System/Threading/Overlapped.cs b/src/System.Private.CoreLib/src/System/Threading/Overlapped.cs index be4144b52f5..0a1c2ce727b 100644 --- a/src/System.Private.CoreLib/src/System/Threading/Overlapped.cs +++ b/src/System.Private.CoreLib/src/System/Threading/Overlapped.cs @@ -136,6 +136,7 @@ internal unsafe sealed class OverlappedData { Debug.Assert(_pinnedData == null); + bool success = false; try { if (_userObject != null) @@ -157,7 +158,9 @@ internal unsafe sealed class OverlappedData } } - _pNativeOverlapped = (NativeOverlapped*)Interop.MemAlloc((UIntPtr)(sizeof(NativeOverlapped) + sizeof(GCHandle))); + NativeOverlapped* pNativeOverlapped = (NativeOverlapped*)Interop.MemAlloc((UIntPtr)(sizeof(NativeOverlapped) + sizeof(GCHandle))); + *(GCHandle*)(pNativeOverlapped + 1) = default(GCHandle); + _pNativeOverlapped = pNativeOverlapped; _pNativeOverlapped->InternalLow = default; _pNativeOverlapped->InternalHigh = default; @@ -165,16 +168,15 @@ internal unsafe sealed class OverlappedData _pNativeOverlapped->OffsetHigh = _offsetHigh; _pNativeOverlapped->EventHandle = _eventHandle; - GCHandle *pHandle = (GCHandle*)(_pNativeOverlapped + 1); - *pHandle = default(GCHandle); - - *pHandle = GCHandle.Alloc(this); + *(GCHandle*)(_pNativeOverlapped + 1) = GCHandle.Alloc(this); + success = true; return _pNativeOverlapped; } finally { - FreeNativeOverlapped(); + if (!success) + FreeNativeOverlapped(); } } From 6c2368b53687609f2fd8ce4389596f2a0d283e3f Mon Sep 17 00:00:00 2001 From: Jan Kotas Date: Sat, 23 Jun 2018 13:59:13 -0700 Subject: [PATCH 08/69] Mark a few methods with NoInline attribute (#6001) --- .../src/Internal/Runtime/Augments/RuntimeThread.cs | 3 +++ .../Internal/Runtime/CompilerHelpers/InteropHelpers.cs | 8 +++++--- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/src/System.Private.CoreLib/src/Internal/Runtime/Augments/RuntimeThread.cs b/src/System.Private.CoreLib/src/Internal/Runtime/Augments/RuntimeThread.cs index 7bfce74e924..fef6620ee44 100644 --- a/src/System.Private.CoreLib/src/Internal/Runtime/Augments/RuntimeThread.cs +++ b/src/System.Private.CoreLib/src/Internal/Runtime/Augments/RuntimeThread.cs @@ -371,6 +371,7 @@ public bool Join(int millisecondsTimeout) return JoinInternal(millisecondsTimeout); } + [MethodImpl(MethodImplOptions.NoInlining)] // Slow path method. Make sure that the caller frame does not pay for PInvoke overhead. public static void Sleep(int millisecondsTimeout) => SleepInternal(VerifyTimeoutMilliseconds(millisecondsTimeout)); /// @@ -382,6 +383,8 @@ public bool Join(int millisecondsTimeout) internal static readonly int OptimalMaxSpinWaitsPerSpinIteration = 64; public static void SpinWait(int iterations) => RuntimeImports.RhSpinWait(iterations); + + [MethodImpl(MethodImplOptions.NoInlining)] // Slow path method. Make sure that the caller frame does not pay for PInvoke overhead. public static bool Yield() => RuntimeImports.RhYield(); public void Start() => StartInternal(null); diff --git a/src/System.Private.CoreLib/src/Internal/Runtime/CompilerHelpers/InteropHelpers.cs b/src/System.Private.CoreLib/src/Internal/Runtime/CompilerHelpers/InteropHelpers.cs index 72eec5c9b1a..22af9cf0d14 100644 --- a/src/System.Private.CoreLib/src/Internal/Runtime/CompilerHelpers/InteropHelpers.cs +++ b/src/System.Private.CoreLib/src/Internal/Runtime/CompilerHelpers/InteropHelpers.cs @@ -3,10 +3,11 @@ // See the LICENSE file in the project root for more information. using System; -using System.Text; -using System.Runtime.InteropServices; using System.Diagnostics; -using Interlocked = System.Threading.Interlocked; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; namespace Internal.Runtime.CompilerHelpers { @@ -208,6 +209,7 @@ internal static unsafe IntPtr ResolvePInvoke(MethodFixupCell* pCell) return ResolvePInvokeSlow(pCell); } + [MethodImpl(MethodImplOptions.NoInlining)] internal static unsafe IntPtr ResolvePInvokeSlow(MethodFixupCell* pCell) { ModuleFixupCell* pModuleCell = pCell->Module; From c9326538e74bcb8f73760cceb84b8abcddc9812f Mon Sep 17 00:00:00 2001 From: Jan Kotas Date: Sat, 23 Jun 2018 17:19:20 -0700 Subject: [PATCH 09/69] Plumbing to generate calli PInvoke stubs (#6002) Contributes to #5587 --- .../CalliMarshallingMethodThunk.Mangling.cs | 28 ++++++ .../CalliMarshallingMethodThunk.Sorting.cs | 20 +++++ .../IL/Stubs/CalliMarshallingMethodThunk.cs | 89 +++++++++++++++++++ ...DelegateMarshallingMethodThunk.Mangling.cs | 3 - .../IL/Stubs/PInvokeLazyFixupField.cs | 8 ++ .../IL/Stubs/PInvokeTargetNativeMethod.cs | 9 ++ .../TypeSystem/Interop/InteropStateManager.cs | 44 +++++++++ .../Mangling/IPrefixMangledSignature.cs | 23 +++++ .../src/Compiler/CoreRTNameMangler.cs | 33 +++++++ .../src/IL/Stubs/PInvokeILProvider.cs | 5 ++ .../src/ILCompiler.TypeSystem.csproj | 18 +++- .../Runtime/JitSupport/JitCompilation.cs | 9 +- .../src/System.Private.Jit.csproj | 1 + 13 files changed, 281 insertions(+), 9 deletions(-) create mode 100644 src/Common/src/TypeSystem/IL/Stubs/CalliMarshallingMethodThunk.Mangling.cs create mode 100644 src/Common/src/TypeSystem/IL/Stubs/CalliMarshallingMethodThunk.Sorting.cs create mode 100644 src/Common/src/TypeSystem/IL/Stubs/CalliMarshallingMethodThunk.cs create mode 100644 src/Common/src/TypeSystem/Mangling/IPrefixMangledSignature.cs diff --git a/src/Common/src/TypeSystem/IL/Stubs/CalliMarshallingMethodThunk.Mangling.cs b/src/Common/src/TypeSystem/IL/Stubs/CalliMarshallingMethodThunk.Mangling.cs new file mode 100644 index 00000000000..5bb37b622e7 --- /dev/null +++ b/src/Common/src/TypeSystem/IL/Stubs/CalliMarshallingMethodThunk.Mangling.cs @@ -0,0 +1,28 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .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 Internal.TypeSystem; + +namespace Internal.IL.Stubs +{ + public partial class CalliMarshallingMethodThunk : IPrefixMangledSignature + { + MethodSignature IPrefixMangledSignature.BaseSignature + { + get + { + return _targetSignature; + } + } + + string IPrefixMangledSignature.Prefix + { + get + { + return "Calli"; + } + } + } +} diff --git a/src/Common/src/TypeSystem/IL/Stubs/CalliMarshallingMethodThunk.Sorting.cs b/src/Common/src/TypeSystem/IL/Stubs/CalliMarshallingMethodThunk.Sorting.cs new file mode 100644 index 00000000000..2ac126d1108 --- /dev/null +++ b/src/Common/src/TypeSystem/IL/Stubs/CalliMarshallingMethodThunk.Sorting.cs @@ -0,0 +1,20 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using Internal.TypeSystem; + +namespace Internal.IL.Stubs +{ + // Functionality related to deterministic ordering of methods + partial class CalliMarshallingMethodThunk + { + protected internal override int ClassCode => 1594107963; + + protected internal override int CompareToImpl(MethodDesc other, TypeSystemComparer comparer) + { + var otherMethod = (CalliMarshallingMethodThunk)other; + return comparer.Compare(_targetSignature, otherMethod._targetSignature); + } + } +} diff --git a/src/Common/src/TypeSystem/IL/Stubs/CalliMarshallingMethodThunk.cs b/src/Common/src/TypeSystem/IL/Stubs/CalliMarshallingMethodThunk.cs new file mode 100644 index 00000000000..a70ceb5fed5 --- /dev/null +++ b/src/Common/src/TypeSystem/IL/Stubs/CalliMarshallingMethodThunk.cs @@ -0,0 +1,89 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .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 Internal.TypeSystem; +using Internal.TypeSystem.Interop; +using Debug = System.Diagnostics.Debug; +using Internal.TypeSystem.Ecma; + +namespace Internal.IL.Stubs +{ + /// + /// Thunk to marshal calli PInvoke parameters and invoke the appropriate function pointer + /// + public partial class CalliMarshallingMethodThunk : ILStubMethod + { + private readonly MethodSignature _targetSignature; + private readonly InteropStateManager _interopStateManager; + private readonly TypeDesc _owningType; + + private MethodSignature _signature; + + public CalliMarshallingMethodThunk(MethodSignature targetSignature, TypeDesc owningType, + InteropStateManager interopStateManager) + { + _targetSignature = targetSignature; + _owningType = owningType; + _interopStateManager = interopStateManager; + } + + public MethodSignature TargetSignature + { + get + { + return _targetSignature; + } + } + + public override TypeSystemContext Context + { + get + { + return _owningType.Context; + } + } + + public override TypeDesc OwningType + { + get + { + return _owningType; + } + } + + public override MethodSignature Signature + { + get + { + if (_signature == null) + { + // Prepend fnptr argument to the signature + TypeDesc[] parameterTypes = new TypeDesc[_targetSignature.Length + 1]; + + parameterTypes[0] = Context.GetWellKnownType(WellKnownType.IntPtr); + for (int i = 0; i < _targetSignature.Length; i++) + parameterTypes[i + 1] = _targetSignature[i]; + + _signature = new MethodSignature(MethodSignatureFlags.Static, 0, _targetSignature.ReturnType, parameterTypes); + } + return _signature; + } + } + + public override string Name + { + get + { + return "CalliMarshallingMethodThunk"; + } + } + + public override MethodIL EmitIL() + { + // TODO + throw null; + } + } +} diff --git a/src/Common/src/TypeSystem/IL/Stubs/DelegateMarshallingMethodThunk.Mangling.cs b/src/Common/src/TypeSystem/IL/Stubs/DelegateMarshallingMethodThunk.Mangling.cs index 7813d0318ea..bd140239c81 100644 --- a/src/Common/src/TypeSystem/IL/Stubs/DelegateMarshallingMethodThunk.Mangling.cs +++ b/src/Common/src/TypeSystem/IL/Stubs/DelegateMarshallingMethodThunk.Mangling.cs @@ -7,9 +7,6 @@ namespace Internal.IL.Stubs { - /// - /// contains functionality related to name mangling - /// public partial class DelegateMarshallingMethodThunk : IPrefixMangledType { TypeDesc IPrefixMangledType.BaseType diff --git a/src/Common/src/TypeSystem/IL/Stubs/PInvokeLazyFixupField.cs b/src/Common/src/TypeSystem/IL/Stubs/PInvokeLazyFixupField.cs index 650b244c139..dd4f182de1e 100644 --- a/src/Common/src/TypeSystem/IL/Stubs/PInvokeLazyFixupField.cs +++ b/src/Common/src/TypeSystem/IL/Stubs/PInvokeLazyFixupField.cs @@ -109,5 +109,13 @@ public override bool HasCustomAttribute(string attributeNamespace, string attrib { return false; } + + public override string Name + { + get + { + return _targetMethod.Name; + } + } } } diff --git a/src/Common/src/TypeSystem/IL/Stubs/PInvokeTargetNativeMethod.cs b/src/Common/src/TypeSystem/IL/Stubs/PInvokeTargetNativeMethod.cs index 2a2cae4e82f..5aab575a28e 100644 --- a/src/Common/src/TypeSystem/IL/Stubs/PInvokeTargetNativeMethod.cs +++ b/src/Common/src/TypeSystem/IL/Stubs/PInvokeTargetNativeMethod.cs @@ -72,6 +72,15 @@ public override bool IsPInvoke } } + public override bool IsNoInlining + { + get + { + // This method does not have real IL body. NoInlining stops the JIT asking for it. + return true; + } + } + public override PInvokeMetadata GetPInvokeMethodMetadata() { return _declMethod.GetPInvokeMethodMetadata(); diff --git a/src/Common/src/TypeSystem/Interop/InteropStateManager.cs b/src/Common/src/TypeSystem/Interop/InteropStateManager.cs index c28ca119dda..3e71c1382c2 100644 --- a/src/Common/src/TypeSystem/Interop/InteropStateManager.cs +++ b/src/Common/src/TypeSystem/Interop/InteropStateManager.cs @@ -22,6 +22,7 @@ public sealed class InteropStateManager private readonly PInvokeDelegateWrapperHashtable _pInvokeDelegateWrapperHashtable; private readonly InlineArrayHashTable _inlineArrayHashtable; private readonly PInvokeLazyFixupFieldHashtable _pInvokeLazyFixupFieldHashtable; + private readonly PInvokeCalliHashtable _pInvokeCalliHashtable; public InteropStateManager(ModuleDesc generatedAssembly) { @@ -33,6 +34,7 @@ public InteropStateManager(ModuleDesc generatedAssembly) _pInvokeDelegateWrapperHashtable = new PInvokeDelegateWrapperHashtable(this, _generatedAssembly); _inlineArrayHashtable = new InlineArrayHashTable(this, _generatedAssembly); _pInvokeLazyFixupFieldHashtable = new PInvokeLazyFixupFieldHashtable(_generatedAssembly.GetGlobalModuleType()); + _pInvokeCalliHashtable = new PInvokeCalliHashtable(this, _generatedAssembly.GetGlobalModuleType()); } // // Delegate Marshalling Stubs @@ -185,6 +187,11 @@ public FieldDesc GetPInvokeLazyFixupField(MethodDesc method) return _pInvokeLazyFixupFieldHashtable.GetOrCreateValue(method); } + public MethodDesc GetPInvokeCalliStub(MethodSignature signature) + { + return _pInvokeCalliHashtable.GetOrCreateValue(signature); + } + private class NativeStructTypeHashtable : LockFreeReaderHashtable { protected override int GetKeyHashCode(MetadataType key) @@ -471,5 +478,42 @@ public PInvokeLazyFixupFieldHashtable(DefType owningType) _owningType = owningType; } } + + private class PInvokeCalliHashtable : LockFreeReaderHashtable + { + private readonly InteropStateManager _interopStateManager; + private readonly TypeDesc _owningType; + + protected override int GetKeyHashCode(MethodSignature key) + { + return key.GetHashCode(); + } + + protected override int GetValueHashCode(CalliMarshallingMethodThunk value) + { + return value.TargetSignature.GetHashCode(); + } + + protected override bool CompareKeyToValue(MethodSignature key, CalliMarshallingMethodThunk value) + { + return key.Equals(value.TargetSignature); + } + + protected override bool CompareValueToValue(CalliMarshallingMethodThunk value1, CalliMarshallingMethodThunk value2) + { + return value1.TargetSignature.Equals(value2.TargetSignature); + } + + protected override CalliMarshallingMethodThunk CreateValueFromKey(MethodSignature key) + { + return new CalliMarshallingMethodThunk(key, _owningType, _interopStateManager); + } + + public PInvokeCalliHashtable(InteropStateManager interopStateManager, TypeDesc owningType) + { + _interopStateManager = interopStateManager; + _owningType = owningType; + } + } } } diff --git a/src/Common/src/TypeSystem/Mangling/IPrefixMangledSignature.cs b/src/Common/src/TypeSystem/Mangling/IPrefixMangledSignature.cs new file mode 100644 index 00000000000..3dabbc53a67 --- /dev/null +++ b/src/Common/src/TypeSystem/Mangling/IPrefixMangledSignature.cs @@ -0,0 +1,23 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +namespace Internal.TypeSystem +{ + /// + /// When implemented by a , instructs a name mangler to use the same mangled name + /// as another entity while prepending a specific prefix to that mangled name. + /// + public interface IPrefixMangledSignature + { + /// + /// Signature whose mangled name to use. + /// + MethodSignature BaseSignature { get; } + + /// + /// Prefix to apply when mangling. + /// + string Prefix { get; } + } +} diff --git a/src/ILCompiler.Compiler/src/Compiler/CoreRTNameMangler.cs b/src/ILCompiler.Compiler/src/Compiler/CoreRTNameMangler.cs index 5c292f87f7b..8c5636c21a4 100644 --- a/src/ILCompiler.Compiler/src/Compiler/CoreRTNameMangler.cs +++ b/src/ILCompiler.Compiler/src/Compiler/CoreRTNameMangler.cs @@ -410,6 +410,35 @@ private Utf8String GetPrefixMangledTypeName(IPrefixMangledType prefixMangledType return sb.ToUtf8String(); } + private Utf8String GetPrefixMangledSignatureName(IPrefixMangledSignature prefixMangledSignature) + { + Utf8StringBuilder sb = new Utf8StringBuilder(); + sb.Append(EnterNameScopeSequence).Append(prefixMangledSignature.Prefix).Append(ExitNameScopeSequence); + + var signature = prefixMangledSignature.BaseSignature; + sb.Append(signature.Flags.ToStringInvariant()); + + sb.Append(EnterNameScopeSequence); + + string sigRetTypeName = GetMangledTypeName(signature.ReturnType); + if (_mangleForCplusPlus) + sigRetTypeName = sigRetTypeName.Replace("::", "_"); + sb.Append(sigRetTypeName); + + for (int i = 0; i < signature.Length; i++) + { + sb.Append("__"); + string sigArgName = GetMangledTypeName(signature[i]); + if (_mangleForCplusPlus) + sigArgName = sigArgName.Replace("::", "_"); + sb.Append(sigArgName); + } + + sb.Append(ExitNameScopeSequence); + + return sb.ToUtf8String(); + } + private Utf8String GetPrefixMangledMethodName(IPrefixMangledMethod prefixMangledMetod) { Utf8StringBuilder sb = new Utf8StringBuilder(); @@ -497,6 +526,10 @@ private Utf8String ComputeUnqualifiedMangledMethodName(MethodDesc method) { utf8MangledName = GetPrefixMangledTypeName((IPrefixMangledType)method); } + else if (method is IPrefixMangledSignature) + { + utf8MangledName = GetPrefixMangledSignatureName((IPrefixMangledSignature)method); + } else { // Assume that Name is unique for all other methods diff --git a/src/ILCompiler.Compiler/src/IL/Stubs/PInvokeILProvider.cs b/src/ILCompiler.Compiler/src/IL/Stubs/PInvokeILProvider.cs index 4aec04036d8..7ae483dbcc4 100644 --- a/src/ILCompiler.Compiler/src/IL/Stubs/PInvokeILProvider.cs +++ b/src/ILCompiler.Compiler/src/IL/Stubs/PInvokeILProvider.cs @@ -29,5 +29,10 @@ public MethodIL EmitIL(MethodDesc method) { return PInvokeILEmitter.EmitIL(method, _pInvokeILEmitterConfiguration, _interopStateManager); } + + public MethodDesc GetCalliStub(MethodSignature signature) + { + return _interopStateManager.GetPInvokeCalliStub(signature); + } } } diff --git a/src/ILCompiler.TypeSystem/src/ILCompiler.TypeSystem.csproj b/src/ILCompiler.TypeSystem/src/ILCompiler.TypeSystem.csproj index aab6301a4b4..ec7b134e6ec 100644 --- a/src/ILCompiler.TypeSystem/src/ILCompiler.TypeSystem.csproj +++ b/src/ILCompiler.TypeSystem/src/ILCompiler.TypeSystem.csproj @@ -358,9 +358,6 @@ IL\DelegateInfo.cs - - IL\Stubs\DelegateMarshallingMethodThunk.Sorting.cs - IL\Stubs\DelegateThunks.Sorting.cs @@ -475,12 +472,24 @@ IL\Stubs\DebuggerSteppingHelpers.cs + + IL\Stubs\CalliMarshallingMethodThunk.cs + + + IL\Stubs\CalliMarshallingMethodThunk.Mangling.cs + + + IL\Stubs\CalliMarshallingMethodThunk.Sorting.cs + IL\Stubs\DelegateMarshallingMethodThunk.cs IL\Stubs\DelegateMarshallingMethodThunk.Mangling.cs + + IL\Stubs\DelegateMarshallingMethodThunk.Sorting.cs + IL\Stubs\ForwardDelegateCreationThunk.cs @@ -562,6 +571,9 @@ TypeSystem\Mangling\IPrefixMangledType.cs + + TypeSystem\Mangling\IPrefixMangledSignature.cs + Utilities\ArrayBuilder.cs diff --git a/src/System.Private.Jit/src/Internal/Runtime/JitSupport/JitCompilation.cs b/src/System.Private.Jit/src/Internal/Runtime/JitSupport/JitCompilation.cs index e628978b9ee..2c5f06f72e5 100644 --- a/src/System.Private.Jit/src/Internal/Runtime/JitSupport/JitCompilation.cs +++ b/src/System.Private.Jit/src/Internal/Runtime/JitSupport/JitCompilation.cs @@ -21,7 +21,8 @@ public Compilation(TypeSystemContext context) { _typeSystemContext = context; _typeGetTypeMethodThunks = new TypeGetTypeMethodThunkCache(context.GetWellKnownType(WellKnownType.Object)); - _methodILCache = new ILProvider(new PInvokeILProvider(new PInvokeILEmitterConfiguration(forceLazyResolution: true), null)); + _pInvokeILProvider = new PInvokeILProvider(new PInvokeILEmitterConfiguration(forceLazyResolution: true), null); + _methodILCache = new ILProvider(_pInvokeILProvider); _nodeFactory = new NodeFactory(context); _devirtualizationManager = new DevirtualizationManager(); } @@ -31,9 +32,11 @@ public Compilation(TypeSystemContext context) protected readonly Logger _logger = Logger.Null; private readonly TypeGetTypeMethodThunkCache _typeGetTypeMethodThunks; private ILProvider _methodILCache; + private PInvokeILProvider _pInvokeILProvider; private readonly DevirtualizationManager _devirtualizationManager; internal Logger Logger => _logger; + internal PInvokeILProvider PInvokeILProvider => _pInvokeILProvider; public TypeSystemContext TypeSystemContext { get { return _typeSystemContext; } } public NodeFactory NodeFactory { get { return _nodeFactory; } } @@ -51,7 +54,7 @@ internal MethodIL GetMethodIL(MethodDesc method) { // Flush the cache when it grows too big if (_methodILCache.Count > 1000) - _methodILCache = new ILProvider(new PInvokeILProvider(new PInvokeILEmitterConfiguration(forceLazyResolution: true), null)); + _methodILCache = new ILProvider(_pInvokeILProvider); return _methodILCache.GetMethodIL(method); } @@ -142,4 +145,4 @@ public DelegateCreationInfo GetDelegateCtor(TypeDesc delegateType, MethodDesc ta return DelegateCreationInfo.Create(delegateType, target, NodeFactory, followVirtualDispatch); } } -} \ No newline at end of file +} diff --git a/src/System.Private.Jit/src/System.Private.Jit.csproj b/src/System.Private.Jit/src/System.Private.Jit.csproj index 662339fa586..39cb058ccf8 100644 --- a/src/System.Private.Jit/src/System.Private.Jit.csproj +++ b/src/System.Private.Jit/src/System.Private.Jit.csproj @@ -69,6 +69,7 @@ + From 3f5611a769a13a5e3ea7e322d640b9abac948c31 Mon Sep 17 00:00:00 2001 From: Anirudh Agnihotry Date: Fri, 22 Jun 2018 21:12:42 -0700 Subject: [PATCH 10/69] Moved EventWaitHandle.cs to shared (dotnet/coreclr#18612) * Removed AccessControl Unused arguments * moving common code to CreateEventCore and using constructor chaining * Moving Functions to eventwaithandles.windows * EventWaitHandle matched with corert * eventwaithandle.windwos matched with corert * Addding interop functions * moved files to shared * Minor changes * fixing build for corert unix * Removing Comment Signed-off-by: dotnet-bot --- .../Windows/Kernel32/Interop.Constants.cs | 1 + .../Kernel32/Interop.EventWaitHandle.cs | 28 ++++++ .../System.Private.CoreLib.Shared.projitems | 3 + .../Threading/EventWaitHandle.Windows.cs | 95 +++++++++++++++++++ .../System/Threading/EventWaitHandle.cs | 51 ++++++++++ 5 files changed, 178 insertions(+) create mode 100644 src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.EventWaitHandle.cs create mode 100644 src/System.Private.CoreLib/shared/System/Threading/EventWaitHandle.Windows.cs create mode 100644 src/System.Private.CoreLib/shared/System/Threading/EventWaitHandle.cs diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.Constants.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.Constants.cs index 59dace98e04..b13cdfd03fe 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.Constants.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.Constants.cs @@ -10,5 +10,6 @@ internal static partial class Kernel32 internal const int SYNCHRONIZE = 0x00100000; internal const int MUTEX_MODIFY_STATE = 0x00000001; internal const int SEMAPHORE_MODIFY_STATE = 0x00000002; + internal const int EVENT_MODIFY_STATE = 0x00000002; } } diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.EventWaitHandle.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.EventWaitHandle.cs new file mode 100644 index 00000000000..b562e527e71 --- /dev/null +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.EventWaitHandle.cs @@ -0,0 +1,28 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using Microsoft.Win32.SafeHandles; +using System; +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static partial class Kernel32 + { + internal const uint CREATE_EVENT_INITIAL_SET = 0x2; + internal const uint CREATE_EVENT_MANUAL_RESET = 0x1; + + [DllImport(Interop.Libraries.Kernel32, SetLastError = true)] + internal static extern bool SetEvent(SafeWaitHandle handle); + + [DllImport(Interop.Libraries.Kernel32, SetLastError = true)] + internal static extern bool ResetEvent(SafeWaitHandle handle); + + [DllImport(Interop.Libraries.Kernel32, EntryPoint = "CreateEventExW", SetLastError = true, CharSet = CharSet.Unicode)] + internal static extern SafeWaitHandle CreateEventEx(IntPtr lpSecurityAttributes, string name, uint flags, uint desiredAccess); + + [DllImport(Interop.Libraries.Kernel32, EntryPoint = "OpenEventW", SetLastError = true, CharSet = CharSet.Unicode)] + internal static extern SafeWaitHandle OpenEvent(uint desiredAccess, bool inheritHandle, string name); + } +} diff --git a/src/System.Private.CoreLib/shared/System.Private.CoreLib.Shared.projitems b/src/System.Private.CoreLib/shared/System.Private.CoreLib.Shared.projitems index eeef09bc67c..da36623eaff 100644 --- a/src/System.Private.CoreLib/shared/System.Private.CoreLib.Shared.projitems +++ b/src/System.Private.CoreLib/shared/System.Private.CoreLib.Shared.projitems @@ -582,6 +582,7 @@ + @@ -814,9 +815,11 @@ + + diff --git a/src/System.Private.CoreLib/shared/System/Threading/EventWaitHandle.Windows.cs b/src/System.Private.CoreLib/shared/System/Threading/EventWaitHandle.Windows.cs new file mode 100644 index 00000000000..f1865510d1b --- /dev/null +++ b/src/System.Private.CoreLib/shared/System/Threading/EventWaitHandle.Windows.cs @@ -0,0 +1,95 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.IO; +using System.Runtime.InteropServices; +using Microsoft.Win32.SafeHandles; + +namespace System.Threading +{ + public partial class EventWaitHandle + { + private const uint AccessRights = (uint)Interop.Kernel32.MAXIMUM_ALLOWED | Interop.Kernel32.SYNCHRONIZE | Interop.Kernel32.EVENT_MODIFY_STATE; + + private EventWaitHandle(SafeWaitHandle handle) + { + SafeWaitHandle = handle; + } + + private void CreateEventCore(bool initialState, EventResetMode mode, string name, out bool createdNew) + { +#if !PLATFORM_WINDOWS + if (name != null) + throw new PlatformNotSupportedException(SR.PlatformNotSupported_NamedSynchronizationPrimitives); +#endif + uint eventFlags = initialState ? Interop.Kernel32.CREATE_EVENT_INITIAL_SET : 0; + if (mode == EventResetMode.ManualReset) + eventFlags |= (uint)Interop.Kernel32.CREATE_EVENT_MANUAL_RESET; + + SafeWaitHandle handle = Interop.Kernel32.CreateEventEx(IntPtr.Zero, name, eventFlags, AccessRights); + + int errorCode = Marshal.GetLastWin32Error(); + if (handle.IsInvalid) + { + handle.SetHandleAsInvalid(); + if (name != null && name.Length != 0 && errorCode == Interop.Errors.ERROR_INVALID_HANDLE) + throw new WaitHandleCannotBeOpenedException(SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name)); + + throw Win32Marshal.GetExceptionForWin32Error(errorCode, name); + } + createdNew = errorCode != Interop.Errors.ERROR_ALREADY_EXISTS; + SafeWaitHandle = handle; + } + + private static OpenExistingResult OpenExistingWorker(string name, out EventWaitHandle result) + { +#if PLATFORM_WINDOWS + if (name == null) + throw new ArgumentNullException(nameof(name)); + if (name.Length == 0) + throw new ArgumentException(SR.Argument_EmptyName, nameof(name)); + + result = null; + SafeWaitHandle myHandle = Interop.Kernel32.OpenEvent(AccessRights, false, name); + + if (myHandle.IsInvalid) + { + int errorCode = Marshal.GetLastWin32Error(); + + if (errorCode == Interop.Errors.ERROR_FILE_NOT_FOUND || errorCode == Interop.Errors.ERROR_INVALID_NAME) + return OpenExistingResult.NameNotFound; + if (errorCode == Interop.Errors.ERROR_PATH_NOT_FOUND) + return OpenExistingResult.PathNotFound; + if (name != null && name.Length != 0 && errorCode == Interop.Errors.ERROR_INVALID_HANDLE) + return OpenExistingResult.NameInvalid; + + throw Win32Marshal.GetExceptionForWin32Error(errorCode, name); + } + result = new EventWaitHandle(myHandle); + return OpenExistingResult.Success; +#else + throw new PlatformNotSupportedException(SR.PlatformNotSupported_NamedSynchronizationPrimitives); +#endif + } + + public bool Reset() + { + bool res = Interop.Kernel32.ResetEvent(_waitHandle); + if (!res) + throw Win32Marshal.GetExceptionForLastWin32Error(); + return res; + } + + public bool Set() => Set(_waitHandle); + + internal bool Set(SafeWaitHandle handle) + { + bool res = Interop.Kernel32.SetEvent(_waitHandle); + if (!res) + throw Win32Marshal.GetExceptionForLastWin32Error(); + return res; + } + } +} diff --git a/src/System.Private.CoreLib/shared/System/Threading/EventWaitHandle.cs b/src/System.Private.CoreLib/shared/System/Threading/EventWaitHandle.cs new file mode 100644 index 00000000000..2542d8199fb --- /dev/null +++ b/src/System.Private.CoreLib/shared/System/Threading/EventWaitHandle.cs @@ -0,0 +1,51 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.IO; + +namespace System.Threading +{ + public partial class EventWaitHandle : WaitHandle + { + public EventWaitHandle(bool initialState, EventResetMode mode) : + this(initialState, mode, null, out _) + { + } + + public EventWaitHandle(bool initialState, EventResetMode mode, string name) : + this(initialState, mode, name, out _) + { + } + + public EventWaitHandle(bool initialState, EventResetMode mode, string name, out bool createdNew) + { + if (mode != EventResetMode.AutoReset && mode != EventResetMode.ManualReset) + throw new ArgumentException(SR.Argument_InvalidFlag, nameof(mode)); + + CreateEventCore(initialState, mode, name, out createdNew); + } + + public static EventWaitHandle OpenExisting(string name) + { + EventWaitHandle result; + switch (OpenExistingWorker(name, out result)) + { + case OpenExistingResult.NameNotFound: + throw new WaitHandleCannotBeOpenedException(); + case OpenExistingResult.NameInvalid: + throw new WaitHandleCannotBeOpenedException(SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name)); + case OpenExistingResult.PathNotFound: + throw new DirectoryNotFoundException(SR.Format(SR.IO_PathNotFound_Path, name)); + default: + return result; + } + } + + public static bool TryOpenExisting(string name, out EventWaitHandle result) + { + return OpenExistingWorker(name, out result) == OpenExistingResult.Success; + } + } +} From 450de75f4eb620ac676414563311c29ddab00d76 Mon Sep 17 00:00:00 2001 From: Anipik Date: Sat, 23 Jun 2018 21:29:23 -0700 Subject: [PATCH 11/69] non shared changes and disabling tests --- .../Windows/mincore/Interop.Threading.cs | 15 -- .../Threading/EventWaitHandle.Windows.cs | 4 +- .../src/System.Private.CoreLib.csproj | 2 - .../System/Threading/EventWaitHandle.Unix.cs | 47 +++++-- .../Threading/EventWaitHandle.Windows.cs | 103 -------------- .../src/System/Threading/EventWaitHandle.cs | 128 ------------------ .../System/Threading/ThreadPool.Portable.cs | 3 +- .../System/Threading/ThreadPool.Windows.cs | 2 +- .../src/System/Threading/Timer.Windows.cs | 2 +- tests/TopN.CoreFX.Windows.issues.json | 24 ++++ 10 files changed, 68 insertions(+), 262 deletions(-) delete mode 100644 src/System.Private.CoreLib/src/System/Threading/EventWaitHandle.Windows.cs delete mode 100644 src/System.Private.CoreLib/src/System/Threading/EventWaitHandle.cs diff --git a/src/Common/src/Interop/Windows/mincore/Interop.Threading.cs b/src/Common/src/Interop/Windows/mincore/Interop.Threading.cs index 5f89ed6a104..a08c62c819e 100644 --- a/src/Common/src/Interop/Windows/mincore/Interop.Threading.cs +++ b/src/Common/src/Interop/Windows/mincore/Interop.Threading.cs @@ -10,21 +10,6 @@ internal static partial class Interop { internal static partial class mincore { - [DllImport(Libraries.Kernel32, EntryPoint = "CreateEventExW", SetLastError = true, CharSet = CharSet.Unicode)] - internal extern static SafeWaitHandle CreateEventEx(IntPtr lpEventAttributes, string lpName, uint dwFlags, uint dwDesiredAccess); - - [DllImport(Libraries.Kernel32, EntryPoint = "OpenEventW", SetLastError = true, CharSet = CharSet.Unicode)] - internal extern static SafeWaitHandle OpenEvent(uint dwDesiredAccess, bool bInheritHandle, string lpName); - - [DllImport(Libraries.Kernel32)] - internal extern static bool ResetEvent(IntPtr hEvent); - - [DllImport(Libraries.Kernel32)] - internal extern static bool SetEvent(IntPtr hEvent); - - [DllImport(Libraries.Kernel32)] - internal extern static bool SetEvent(SafeWaitHandle hEvent); - [DllImport(Libraries.Kernel32)] internal extern static uint WaitForMultipleObjectsEx(uint nCount, IntPtr lpHandles, bool bWaitAll, uint dwMilliseconds, bool bAlertable); diff --git a/src/System.Private.CoreLib/shared/System/Threading/EventWaitHandle.Windows.cs b/src/System.Private.CoreLib/shared/System/Threading/EventWaitHandle.Windows.cs index f1865510d1b..2da53b2b80b 100644 --- a/src/System.Private.CoreLib/shared/System/Threading/EventWaitHandle.Windows.cs +++ b/src/System.Private.CoreLib/shared/System/Threading/EventWaitHandle.Windows.cs @@ -82,9 +82,7 @@ public bool Reset() return res; } - public bool Set() => Set(_waitHandle); - - internal bool Set(SafeWaitHandle handle) + public bool Set() { bool res = Interop.Kernel32.SetEvent(_waitHandle); if (!res) diff --git a/src/System.Private.CoreLib/src/System.Private.CoreLib.csproj b/src/System.Private.CoreLib/src/System.Private.CoreLib.csproj index 7cbebfe131e..f7618ebe1ba 100644 --- a/src/System.Private.CoreLib/src/System.Private.CoreLib.csproj +++ b/src/System.Private.CoreLib/src/System.Private.CoreLib.csproj @@ -301,7 +301,6 @@ - @@ -495,7 +494,6 @@ Interop\Windows\mincore\Interop.DynamicLoad.cs - diff --git a/src/System.Private.CoreLib/src/System/Threading/EventWaitHandle.Unix.cs b/src/System.Private.CoreLib/src/System/Threading/EventWaitHandle.Unix.cs index 40e69ab1223..5f1aeb3e40b 100644 --- a/src/System.Private.CoreLib/src/System/Threading/EventWaitHandle.Unix.cs +++ b/src/System.Private.CoreLib/src/System/Threading/EventWaitHandle.Unix.cs @@ -2,7 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using Microsoft.Win32.SafeHandles; using System.Diagnostics; +using System.IO; +using System.Runtime.InteropServices; namespace System.Threading { @@ -11,9 +14,7 @@ public partial class EventWaitHandle private void CreateEventCore(bool initialState, EventResetMode mode, string name, out bool createdNew) { if (name != null) - { throw new PlatformNotSupportedException(SR.PlatformNotSupported_NamedSynchronizationPrimitives); - } SafeWaitHandle = WaitSubsystem.NewEvent(initialState, mode); createdNew = true; @@ -24,16 +25,46 @@ private static OpenExistingResult OpenExistingWorker(string name, out EventWaitH throw new PlatformNotSupportedException(SR.PlatformNotSupported_NamedSynchronizationPrimitives); } - private static bool ResetCore(IntPtr handle) + public bool Reset() + { + SafeWaitHandle waitHandle = ValidateHandle(); + try + { + WaitSubsystem.ResetEvent(waitHandle.DangerousGetHandle()); + return true; + } + finally + { + waitHandle.DangerousRelease(); + } + } + + public bool Set() { - WaitSubsystem.ResetEvent(handle); - return true; + SafeWaitHandle waitHandle = ValidateHandle(); + try + { + WaitSubsystem.SetEvent(waitHandle.DangerousGetHandle()); + return true; + } + finally + { + waitHandle.DangerousRelease(); + } } - private static bool SetCore(IntPtr handle) + private SafeWaitHandle ValidateHandle() { - WaitSubsystem.SetEvent(handle); - return true; + // The field value is modifiable via the public property, save it locally + // to ensure that one instance is used in all places in this method + SafeWaitHandle waitHandle = _waitHandle; + if (waitHandle == null) + { + ThrowInvalidHandleException(); + } + + waitHandle.DangerousAddRef(); + return waitHandle; } } } diff --git a/src/System.Private.CoreLib/src/System/Threading/EventWaitHandle.Windows.cs b/src/System.Private.CoreLib/src/System/Threading/EventWaitHandle.Windows.cs deleted file mode 100644 index ad9ed1c58e6..00000000000 --- a/src/System.Private.CoreLib/src/System/Threading/EventWaitHandle.Windows.cs +++ /dev/null @@ -1,103 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System.Diagnostics; -using System.Runtime.InteropServices; -using Microsoft.Win32.SafeHandles; - -namespace System.Threading -{ - public partial class EventWaitHandle - { - private const uint AccessRights = Interop.Kernel32.MAXIMUM_ALLOWED | Interop.Kernel32.SYNCHRONIZE | (uint)Interop.Constants.EventModifyState; - - private EventWaitHandle(SafeWaitHandle handle) - { - SafeWaitHandle = handle; - } - - private void CreateEventCore(bool initialState, EventResetMode mode, string name, out bool createdNew) - { - Debug.Assert((mode == EventResetMode.AutoReset) || (mode == EventResetMode.ManualReset)); - Debug.Assert(name == null || name.Length <= Interop.Kernel32.MAX_PATH); - - uint eventFlags = initialState ? (uint)Interop.Constants.CreateEventInitialSet : 0; - if (mode == EventResetMode.ManualReset) - { - eventFlags |= (uint)Interop.Constants.CreateEventManualReset; - } - - SafeWaitHandle _handle = Interop.mincore.CreateEventEx(IntPtr.Zero, name, eventFlags, AccessRights); - - if (_handle.IsInvalid) - { - int errorCode = Marshal.GetLastWin32Error(); - _handle.SetHandleAsInvalid(); - if (null != name && 0 != name.Length && Interop.Errors.ERROR_INVALID_HANDLE == errorCode) - throw new WaitHandleCannotBeOpenedException(SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name)); - throw ExceptionFromCreationError(errorCode, name); - } - else if (name != null) - { - int errorCode = Marshal.GetLastWin32Error(); - createdNew = errorCode != Interop.Errors.ERROR_ALREADY_EXISTS; - } - else - { - createdNew = true; - } - - SafeWaitHandle = _handle; - } - - private static OpenExistingResult OpenExistingWorker(string name, out EventWaitHandle result) - { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - - if (name.Length == 0) - { - throw new ArgumentException(SR.Argument_EmptyName, nameof(name)); - } - - result = null; - - SafeWaitHandle myHandle = Interop.mincore.OpenEvent(AccessRights, false, name); - - if (myHandle.IsInvalid) - { - int errorCode = Marshal.GetLastWin32Error(); - - if (Interop.Errors.ERROR_FILE_NOT_FOUND == errorCode || Interop.Errors.ERROR_INVALID_NAME == errorCode) - return OpenExistingResult.NameNotFound; - if (Interop.Errors.ERROR_PATH_NOT_FOUND == errorCode) - return OpenExistingResult.PathNotFound; - if (null != name && 0 != name.Length && Interop.Errors.ERROR_INVALID_HANDLE == errorCode) - return OpenExistingResult.NameInvalid; - - throw ExceptionFromCreationError(errorCode, name); - } - result = new EventWaitHandle(myHandle); - return OpenExistingResult.Success; - } - - private static bool ResetCore(IntPtr handle) - { - bool res = Interop.mincore.ResetEvent(handle); - if (!res) - ThrowSignalOrUnsignalException(); - return res; - } - - private static bool SetCore(IntPtr handle) - { - bool res = Interop.mincore.SetEvent(handle); - if (!res) - ThrowSignalOrUnsignalException(); - return res; - } - } -} diff --git a/src/System.Private.CoreLib/src/System/Threading/EventWaitHandle.cs b/src/System.Private.CoreLib/src/System/Threading/EventWaitHandle.cs deleted file mode 100644 index a03d00e1196..00000000000 --- a/src/System.Private.CoreLib/src/System/Threading/EventWaitHandle.cs +++ /dev/null @@ -1,128 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -// - -/*============================================================================= -** -** -** -** Purpose: Base class for representing Events -** -** -=============================================================================*/ - -using System; -using System.Runtime.InteropServices; -using Microsoft.Win32.SafeHandles; -using System.IO; -using System.Diagnostics; - -namespace System.Threading -{ - public partial class EventWaitHandle : WaitHandle - { - public EventWaitHandle(bool initialState, EventResetMode mode) - { - VerifyMode(mode); - - bool createdNew; - CreateEventCore(initialState, mode, null, out createdNew); - } - - public EventWaitHandle(bool initialState, EventResetMode mode, string name) - { - VerifyMode(mode); - - bool createdNew; - CreateEventCore(initialState, mode, name, out createdNew); - } - - public EventWaitHandle(bool initialState, EventResetMode mode, string name, out bool createdNew) - { - VerifyMode(mode); - - CreateEventCore(initialState, mode, name, out createdNew); - } - - private static void VerifyMode(EventResetMode mode) - { - if (mode != EventResetMode.AutoReset && mode != EventResetMode.ManualReset) - { - throw new ArgumentException(SR.Argument_InvalidFlag, nameof(mode)); - } - } - - public static EventWaitHandle OpenExisting(string name) - { - EventWaitHandle result; - switch (OpenExistingWorker(name, out result)) - { - case OpenExistingResult.NameNotFound: - throw new WaitHandleCannotBeOpenedException(); - - case OpenExistingResult.NameInvalid: - throw new WaitHandleCannotBeOpenedException(SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name)); - - case OpenExistingResult.PathNotFound: - throw new IOException(SR.Format(SR.IO_PathNotFound_Path, name)); - - default: - return result; - } - } - - public static bool TryOpenExisting(string name, out EventWaitHandle result) - { - return OpenExistingWorker(name, out result) == OpenExistingResult.Success; - } - - public bool Reset() - { - // The field value is modifiable via , save it locally to ensure that ref modification - // is done on the same instance - SafeWaitHandle waitHandle = _waitHandle; - if (waitHandle == null) - { - ThrowInvalidHandleException(); - } - - waitHandle.DangerousAddRef(); - try - { - return ResetCore(_waitHandle.DangerousGetHandle()); - } - finally - { - waitHandle.DangerousRelease(); - } - } - - public bool Set() - { - // The field value is modifiable via the public property, save it locally - // to ensure that one instance is used in all places in this method - SafeWaitHandle waitHandle = _waitHandle; - if (waitHandle == null) - { - ThrowInvalidHandleException(); - } - - waitHandle.DangerousAddRef(); - try - { - return SetCore(waitHandle.DangerousGetHandle()); - } - finally - { - waitHandle.DangerousRelease(); - } - } - - internal static bool Set(IntPtr handle) - { - return SetCore(handle); - } - } -} diff --git a/src/System.Private.CoreLib/src/System/Threading/ThreadPool.Portable.cs b/src/System.Private.CoreLib/src/System/Threading/ThreadPool.Portable.cs index f7dff9475ea..2dbb6a2d20b 100644 --- a/src/System.Private.CoreLib/src/System/Threading/ThreadPool.Portable.cs +++ b/src/System.Private.CoreLib/src/System/Threading/ThreadPool.Portable.cs @@ -206,7 +206,8 @@ private void SignalUserWaitHandle() { if (handleValue != IntPtr.Zero && handleValue != (IntPtr)(-1)) { - EventWaitHandle.Set(handleValue); + Debug.Assert(handleValue == handle.DangerousGetHandle()); + WaitSubsystem.SetEvent(handleValue); } } finally diff --git a/src/System.Private.CoreLib/src/System/Threading/ThreadPool.Windows.cs b/src/System.Private.CoreLib/src/System/Threading/ThreadPool.Windows.cs index 5ca0604b4e1..a15a38437fa 100644 --- a/src/System.Private.CoreLib/src/System/Threading/ThreadPool.Windows.cs +++ b/src/System.Private.CoreLib/src/System/Threading/ThreadPool.Windows.cs @@ -186,7 +186,7 @@ private void FinishUnregisteringAsync(object waitObject) if ((safeWaitHandle != null) && !safeWaitHandle.IsInvalid) { - Interop.mincore.SetEvent(safeWaitHandle); + Interop.Kernel32.SetEvent(safeWaitHandle); } } diff --git a/src/System.Private.CoreLib/src/System/Threading/Timer.Windows.cs b/src/System.Private.CoreLib/src/System/Threading/Timer.Windows.cs index 7020e1a2ce3..a3bea70888e 100644 --- a/src/System.Private.CoreLib/src/System/Threading/Timer.Windows.cs +++ b/src/System.Private.CoreLib/src/System/Threading/Timer.Windows.cs @@ -66,7 +66,7 @@ internal sealed partial class TimerQueueTimer { private void SignalNoCallbacksRunning() { - Interop.mincore.SetEvent(_notifyWhenNoCallbacksRunning.SafeWaitHandle); + Interop.Kernel32.SetEvent(_notifyWhenNoCallbacksRunning.SafeWaitHandle); } } } diff --git a/tests/TopN.CoreFX.Windows.issues.json b/tests/TopN.CoreFX.Windows.issues.json index e63d173c5b2..c1511d85bff 100644 --- a/tests/TopN.CoreFX.Windows.issues.json +++ b/tests/TopN.CoreFX.Windows.issues.json @@ -1929,6 +1929,14 @@ "name": "System.Threading.Tests.EventWaitHandleTests.Ctor_InvalidMode", "reason": "Xunit.Sdk.EqualException" }, + { + "name": "System.Threading.Tests.EventWaitHandleTests.OpenExisting_InvalidNames_Windows", + "reason": "Xunit.Sdk.EqualException" + }, + { + "name": "System.Threading.Tests.EventWaitHandleTests.Ctor_InvalidNames", + "reason": "Xunit.Sdk.EqualException" + }, { "name": "System.Threading.Tests.MonitorTests.PulseAll_Invalid", "reason": "Xunit.Sdk.EqualException" @@ -1948,6 +1956,22 @@ { "name": "System.Threading.Tests.SemaphoreTests.PingPong", "reason": "System.TypeInitializationException" + }, + { + "name": "System.Threading.Tests.MutexTests.Ctor_InvalidName", + "reason": "Xunit.Sdk.EqualException" + }, + { + "name": "System.Threading.Tests.MutexTests.OpenExisting_InvalidNames", + "reason": "Xunit.Sdk.EqualException" + }, + { + "name": "System.Threading.Tests.SemaphoreTests.OpenExisting_InvalidNames_Windows", + "reason": "Xunit.Sdk.EqualException" + }, + { + "name": "System.Threading.Tests.SemaphoreTests.Ctor_InvalidNames", + "reason": "Xunit.Sdk.EqualException" } ] } From c7cae6d5246d3aaf3f7ea6d100ee792ff796a0ce Mon Sep 17 00:00:00 2001 From: Stephen Toub Date: Sun, 24 Jun 2018 08:22:35 -0400 Subject: [PATCH 12/69] Simply type names in Corelib (dotnet-maestro-bot/coreclr#18623) Signed-off-by: dotnet-bot --- .../Interop/Windows/Kernel32/Interop.MUI.cs | 2 +- .../OleAut32/Interop.SysAllocStringLen.cs | 2 +- .../shared/System/AccessViolationException.cs | 4 +- .../shared/System/ApplicationException.cs | 4 +- .../shared/System/ArgumentNullException.cs | 6 +- .../System/ArgumentOutOfRangeException.cs | 18 +- .../shared/System/ArithmeticException.cs | 4 +- .../shared/System/ArraySegment.cs | 2 +- .../System/ArrayTypeMismatchException.cs | 4 +- .../shared/System/BadImageFormatException.cs | 22 +- .../shared/System/BitConverter.cs | 2 +- .../shared/System/Boolean.cs | 42 +- .../shared/System/Byte.cs | 44 +- .../shared/System/Char.cs | 86 +- .../shared/System/CharEnumerator.cs | 6 +- .../shared/System/Collections/Comparer.cs | 2 +- .../System/Collections/DictionaryEntry.cs | 10 +- .../Collections/Generic/ArraySortHelper.cs | 2 +- .../System/Collections/Generic/Dictionary.cs | 2 +- .../Generic/KeyNotFoundException.cs | 4 +- .../shared/System/Collections/Hashtable.cs | 124 +- .../shared/System/Collections/ICollection.cs | 2 +- .../shared/System/Collections/IComparer.cs | 2 +- .../shared/System/Collections/IDictionary.cs | 8 +- .../Collections/IDictionaryEnumerator.cs | 4 +- .../shared/System/Collections/IEnumerator.cs | 2 +- .../System/Collections/IEqualityComparer.cs | 4 +- .../shared/System/Collections/IList.cs | 12 +- .../Collections/IStructuralComparable.cs | 2 +- .../Collections/IStructuralEquatable.cs | 2 +- .../Collections/ListDictionaryInternal.cs | 28 +- .../Collections/ObjectModel/Collection.cs | 4 +- .../ObjectModel/ReadOnlyCollection.cs | 4 +- .../shared/System/Convert.cs | 362 +- .../shared/System/CurrentSystemTimeZone.cs | 18 +- .../shared/System/DataMisalignedException.cs | 4 +- .../shared/System/DateTime.cs | 200 +- .../shared/System/DateTimeOffset.cs | 62 +- .../shared/System/Diagnostics/Debug.Unix.cs | 4 +- .../Diagnostics/Tracing/EventProvider.cs | 8 +- .../System/Diagnostics/Tracing/EventSource.cs | 8 +- .../Diagnostics/Tracing/IEventProvider.cs | 2 +- .../Tracing/TraceLogging/PropertyValue.cs | 104 +- .../Tracing/TraceLogging/SimpleTypeInfos.cs | 52 +- .../Tracing/TraceLogging/Statics.cs | 52 +- .../shared/System/DivideByZeroException.cs | 4 +- .../shared/System/DllNotFoundException.cs | 4 +- .../shared/System/Double.cs | 52 +- .../System/DuplicateWaitObjectException.cs | 10 +- .../System/EntryPointNotFoundException.cs | 4 +- .../shared/System/EventHandler.cs | 4 +- .../shared/System/ExecutionEngineException.cs | 4 +- .../shared/System/FieldAccessException.cs | 4 +- .../shared/System/FormatException.cs | 4 +- .../shared/System/Globalization/Calendar.cs | 2 +- .../Globalization/CalendarData.Windows.cs | 8 +- .../System/Globalization/CharUnicodeInfo.cs | 22 +- .../System/Globalization/CompareInfo.Unix.cs | 8 +- .../Globalization/CompareInfo.Windows.cs | 4 +- .../System/Globalization/CompareInfo.cs | 16 +- .../System/Globalization/CultureData.Unix.cs | 4 +- .../System/Globalization/DateTimeFormat.cs | 8 +- .../Globalization/DateTimeFormatInfo.cs | 318 +- .../DateTimeFormatInfoScanner.cs | 8 +- .../System/Globalization/DateTimeParse.cs | 116 +- .../System/Globalization/HebrewNumber.cs | 2 +- .../Globalization/HijriCalendar.Win32.cs | 6 +- .../System/Globalization/HijriCalendar.cs | 4 +- .../shared/System/Globalization/IdnMapping.cs | 16 +- .../InternalGlobalizationHelper.cs | 12 +- .../Globalization/JapaneseCalendar.Win32.cs | 14 +- .../Globalization/KoreanLunisolarCalendar.cs | 4 +- .../System/Globalization/NumberFormatInfo.cs | 10 +- .../shared/System/Globalization/RegionInfo.cs | 2 +- .../shared/System/Globalization/SortKey.cs | 8 +- .../shared/System/Globalization/StringInfo.cs | 2 +- .../Globalization/TextElementEnumerator.cs | 8 +- .../shared/System/Globalization/TextInfo.cs | 4 +- .../shared/System/IAsyncResult.cs | 2 +- .../shared/System/IComparable.cs | 2 +- .../shared/System/IConvertible.cs | 6 +- .../shared/System/ICustomFormatter.cs | 2 +- .../shared/System/IFormatProvider.cs | 2 +- .../shared/System/IFormattable.cs | 2 +- .../shared/System/IO/BinaryWriter.cs | 6 +- .../shared/System/IO/IOException.cs | 6 +- .../shared/System/IO/MemoryStream.cs | 4 +- .../shared/System/IO/Stream.cs | 30 +- .../shared/System/IO/StreamReader.cs | 4 +- .../shared/System/IO/StreamWriter.cs | 2 +- .../shared/System/IO/TextReader.cs | 2 +- .../shared/System/IO/TextWriter.cs | 26 +- .../shared/System/IO/UnmanagedMemoryStream.cs | 14 +- .../System/IO/UnmanagedMemoryStreamWrapper.cs | 8 +- .../shared/System/IndexOutOfRangeException.cs | 4 +- .../InsufficientExecutionStackException.cs | 4 +- .../System/InsufficientMemoryException.cs | 4 +- .../shared/System/Int16.cs | 52 +- .../shared/System/Int32.cs | 38 +- .../shared/System/Int64.cs | 40 +- .../shared/System/IntPtr.cs | 2 +- .../shared/System/InvalidCastException.cs | 6 +- .../System/InvalidOperationException.cs | 4 +- .../shared/System/InvalidProgramException.cs | 4 +- .../shared/System/InvalidTimeZoneException.cs | 4 +- .../shared/System/MemberAccessException.cs | 4 +- .../shared/System/MethodAccessException.cs | 4 +- .../shared/System/MissingFieldException.cs | 4 +- .../shared/System/MissingMemberException.cs | 4 +- .../System/MulticastNotSupportedException.cs | 4 +- .../shared/System/NotImplementedException.cs | 4 +- .../shared/System/NotSupportedException.cs | 4 +- .../shared/System/NullReferenceException.cs | 4 +- .../shared/System/Nullable.cs | 2 +- .../shared/System/Numerics/ConstantHelper.cs | 60 +- .../shared/System/Numerics/Register.cs | 132 +- .../shared/System/Numerics/Vector.cs | 4256 ++++++++--------- .../System/Numerics/Vector_Operations.cs | 64 +- .../shared/System/ObsoleteAttribute.cs | 8 +- .../System/OperationCanceledException.cs | 8 +- .../shared/System/OutOfMemoryException.cs | 4 +- .../shared/System/OverflowException.cs | 4 +- .../System/PlatformNotSupportedException.cs | 4 +- .../shared/System/Random.cs | 4 +- .../shared/System/RankException.cs | 4 +- .../shared/System/Reflection/Assembly.cs | 2 +- .../shared/System/Reflection/Emit/Label.cs | 2 +- .../shared/System/Reflection/Emit/Opcode.cs | 10 +- .../System/Resources/FastResourceComparer.cs | 6 +- .../MissingSatelliteAssemblyException.cs | 6 +- .../System/Resources/RuntimeResourceSet.cs | 42 +- .../SatelliteContractVersionAttribute.cs | 4 +- .../CustomConstantAttribute.cs | 2 +- .../DateTimeConstantAttribute.cs | 2 +- .../DecimalConstantAttribute.cs | 8 +- .../CompilerServices/DependencyAttribute.cs | 4 +- .../CompilerServices/IndexerNameAttribute.cs | 2 +- .../ReferenceAssemblyAttribute.cs | 4 +- .../MarshalDirectiveException.cs | 4 +- .../InteropServices/MemoryMarshal.Fast.cs | 4 +- .../Runtime/InteropServices/SafeBuffer.cs | 6 +- .../Serialization/SerializationException.cs | 6 +- .../Versioning/TargetFrameworkAttribute.cs | 10 +- .../shared/System/SByte.cs | 50 +- .../shared/System/Security/SecureString.cs | 2 +- .../shared/System/Single.cs | 54 +- .../shared/System/StackOverflowException.cs | 4 +- .../shared/System/String.Manipulation.cs | 6 +- .../shared/System/String.cs | 12 +- .../shared/System/StringComparer.cs | 14 +- .../shared/System/SystemException.cs | 4 +- .../shared/System/Text/ASCIIEncoding.cs | 10 +- .../System/Text/DecoderBestFitFallback.cs | 10 +- .../System/Text/DecoderExceptionFallback.cs | 8 +- .../shared/System/Text/DecoderFallback.cs | 8 +- .../System/Text/DecoderReplacementFallback.cs | 14 +- .../System/Text/EncoderBestFitFallback.cs | 14 +- .../System/Text/EncoderExceptionFallback.cs | 20 +- .../shared/System/Text/EncoderFallback.cs | 6 +- .../System/Text/EncoderReplacementFallback.cs | 22 +- .../shared/System/Text/Encoding.cs | 8 +- .../shared/System/Text/EncodingInfo.cs | 2 +- .../shared/System/Text/EncodingNLS.cs | 4 +- .../shared/System/Text/EncodingProvider.cs | 2 +- .../shared/System/Text/Latin1Encoding.cs | 4 +- .../shared/System/Text/StringBuilder.cs | 22 +- .../shared/System/Text/UTF32Encoding.cs | 18 +- .../shared/System/Text/UTF7Encoding.cs | 4 +- .../shared/System/Text/UTF8Encoding.cs | 6 +- .../shared/System/Text/UnicodeEncoding.cs | 8 +- .../Threading/AbandonedMutexException.cs | 8 +- .../System/Threading/ExecutionContext.cs | 6 +- .../System/Threading/ReaderWriterLockSlim.cs | 2 +- .../shared/System/Threading/Semaphore.cs | 2 +- .../Threading/SemaphoreFullException.cs | 4 +- .../System/Threading/SendOrPostCallback.cs | 2 +- .../shared/System/Threading/SpinWait.cs | 2 +- .../Threading/SynchronizationLockException.cs | 4 +- .../Tasks/ConcurrentExclusiveSchedulerPair.cs | 6 +- .../Threading/ThreadInterruptedException.cs | 4 +- .../System/Threading/ThreadStateException.cs | 4 +- .../WaitHandleCannotBeOpenedException.cs | 4 +- .../shared/System/TimeSpan.cs | 54 +- .../shared/System/TimeZone.cs | 18 +- .../System/TimeZoneNotFoundException.cs | 4 +- .../shared/System/TimeoutException.cs | 4 +- .../shared/System/Tuple.cs | 144 +- .../shared/System/UInt16.cs | 48 +- .../shared/System/UInt32.cs | 40 +- .../shared/System/UInt64.cs | 38 +- .../shared/System/UIntPtr.cs | 2 +- .../System/UnauthorizedAccessException.cs | 4 +- .../System/UnhandledExceptionEventArgs.cs | 6 +- .../System/UnhandledExceptionEventHandler.cs | 2 +- .../shared/System/Version.cs | 10 +- 195 files changed, 3891 insertions(+), 3891 deletions(-) diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.MUI.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.MUI.cs index 6ed7aa2dc41..8d97c03546a 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.MUI.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.MUI.cs @@ -13,6 +13,6 @@ internal static partial class Kernel32 internal const uint MUI_PREFERRED_UI_LANGUAGES = 0x10; [DllImport(Libraries.Kernel32, CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)] - internal static extern bool GetFileMUIPath(uint flags, String filePath, [Out] StringBuilder language, ref int languageLength, [Out] StringBuilder fileMuiPath, ref int fileMuiPathLength, ref Int64 enumerator); + internal static extern bool GetFileMUIPath(uint flags, string filePath, [Out] StringBuilder language, ref int languageLength, [Out] StringBuilder fileMuiPath, ref int fileMuiPathLength, ref long enumerator); } } diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/OleAut32/Interop.SysAllocStringLen.cs b/src/System.Private.CoreLib/shared/Interop/Windows/OleAut32/Interop.SysAllocStringLen.cs index 1af2b3fce96..be902b0c582 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/OleAut32/Interop.SysAllocStringLen.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/OleAut32/Interop.SysAllocStringLen.cs @@ -14,6 +14,6 @@ internal partial class OleAut32 internal static extern SafeBSTRHandle SysAllocStringLen(IntPtr src, uint len); [DllImport(Libraries.OleAut32, CharSet = CharSet.Unicode)] - internal static extern IntPtr SysAllocStringLen(String src, int len); + internal static extern IntPtr SysAllocStringLen(string src, int len); } } diff --git a/src/System.Private.CoreLib/shared/System/AccessViolationException.cs b/src/System.Private.CoreLib/shared/System/AccessViolationException.cs index 280d9b8a979..a66f2a892e7 100644 --- a/src/System.Private.CoreLib/shared/System/AccessViolationException.cs +++ b/src/System.Private.CoreLib/shared/System/AccessViolationException.cs @@ -26,13 +26,13 @@ public AccessViolationException() HResult = HResults.E_POINTER; } - public AccessViolationException(String message) + public AccessViolationException(string message) : base(message) { HResult = HResults.E_POINTER; } - public AccessViolationException(String message, Exception innerException) + public AccessViolationException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.E_POINTER; diff --git a/src/System.Private.CoreLib/shared/System/ApplicationException.cs b/src/System.Private.CoreLib/shared/System/ApplicationException.cs index f36e2c1274e..cac29196bff 100644 --- a/src/System.Private.CoreLib/shared/System/ApplicationException.cs +++ b/src/System.Private.CoreLib/shared/System/ApplicationException.cs @@ -39,13 +39,13 @@ public ApplicationException() // message, its HRESULT set to COR_E_APPLICATION, // and its ExceptionInfo reference set to null. // - public ApplicationException(String message) + public ApplicationException(string message) : base(message) { HResult = HResults.COR_E_APPLICATION; } - public ApplicationException(String message, Exception innerException) + public ApplicationException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_APPLICATION; diff --git a/src/System.Private.CoreLib/shared/System/ArgumentNullException.cs b/src/System.Private.CoreLib/shared/System/ArgumentNullException.cs index 80e43cc2659..edc38f2a4c5 100644 --- a/src/System.Private.CoreLib/shared/System/ArgumentNullException.cs +++ b/src/System.Private.CoreLib/shared/System/ArgumentNullException.cs @@ -30,19 +30,19 @@ public ArgumentNullException() HResult = HResults.E_POINTER; } - public ArgumentNullException(String paramName) + public ArgumentNullException(string paramName) : base(SR.ArgumentNull_Generic, paramName) { HResult = HResults.E_POINTER; } - public ArgumentNullException(String message, Exception innerException) + public ArgumentNullException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.E_POINTER; } - public ArgumentNullException(String paramName, String message) + public ArgumentNullException(string paramName, string message) : base(message, paramName) { HResult = HResults.E_POINTER; diff --git a/src/System.Private.CoreLib/shared/System/ArgumentOutOfRangeException.cs b/src/System.Private.CoreLib/shared/System/ArgumentOutOfRangeException.cs index 604caa8ee87..8d91561ce46 100644 --- a/src/System.Private.CoreLib/shared/System/ArgumentOutOfRangeException.cs +++ b/src/System.Private.CoreLib/shared/System/ArgumentOutOfRangeException.cs @@ -22,7 +22,7 @@ namespace System [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class ArgumentOutOfRangeException : ArgumentException { - private Object _actualValue; + private object _actualValue; // Creates a new ArgumentOutOfRangeException with its message // string set to a default message explaining an argument was out of range. @@ -32,19 +32,19 @@ public ArgumentOutOfRangeException() HResult = HResults.COR_E_ARGUMENTOUTOFRANGE; } - public ArgumentOutOfRangeException(String paramName) + public ArgumentOutOfRangeException(string paramName) : base(SR.Arg_ArgumentOutOfRangeException, paramName) { HResult = HResults.COR_E_ARGUMENTOUTOFRANGE; } - public ArgumentOutOfRangeException(String paramName, String message) + public ArgumentOutOfRangeException(string paramName, string message) : base(message, paramName) { HResult = HResults.COR_E_ARGUMENTOUTOFRANGE; } - public ArgumentOutOfRangeException(String message, Exception innerException) + public ArgumentOutOfRangeException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_ARGUMENTOUTOFRANGE; @@ -53,7 +53,7 @@ public ArgumentOutOfRangeException(String message, Exception innerException) // 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) + public ArgumentOutOfRangeException(string paramName, object actualValue, string message) : base(message, paramName) { _actualValue = actualValue; @@ -72,14 +72,14 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont info.AddValue("ActualValue", _actualValue, typeof(object)); } - public override String Message + public override string Message { get { - String s = base.Message; + string s = base.Message; if (_actualValue != null) { - String valueMessage = SR.Format(SR.ArgumentOutOfRange_ActualValue, _actualValue.ToString()); + string valueMessage = SR.Format(SR.ArgumentOutOfRange_ActualValue, _actualValue.ToString()); if (s == null) return valueMessage; return s + Environment.NewLine + valueMessage; @@ -92,7 +92,7 @@ public override String Message // 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 _actualValue; } } diff --git a/src/System.Private.CoreLib/shared/System/ArithmeticException.cs b/src/System.Private.CoreLib/shared/System/ArithmeticException.cs index 606f1debfd8..46492cab566 100644 --- a/src/System.Private.CoreLib/shared/System/ArithmeticException.cs +++ b/src/System.Private.CoreLib/shared/System/ArithmeticException.cs @@ -34,13 +34,13 @@ public ArithmeticException() // message, its HRESULT set to COR_E_ARITHMETIC, // and its ExceptionInfo reference set to null. // - public ArithmeticException(String message) + public ArithmeticException(string message) : base(message) { HResult = HResults.COR_E_ARITHMETIC; } - public ArithmeticException(String message, Exception innerException) + public ArithmeticException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_ARITHMETIC; diff --git a/src/System.Private.CoreLib/shared/System/ArraySegment.cs b/src/System.Private.CoreLib/shared/System/ArraySegment.cs index 81cf7706756..b2bd4178061 100644 --- a/src/System.Private.CoreLib/shared/System/ArraySegment.cs +++ b/src/System.Private.CoreLib/shared/System/ArraySegment.cs @@ -131,7 +131,7 @@ public void CopyTo(ArraySegment destination) System.Array.Copy(_array, _offset, destination._array, destination._offset, _count); } - public override bool Equals(Object obj) + public override bool Equals(object obj) { if (obj is ArraySegment) return Equals((ArraySegment)obj); diff --git a/src/System.Private.CoreLib/shared/System/ArrayTypeMismatchException.cs b/src/System.Private.CoreLib/shared/System/ArrayTypeMismatchException.cs index 49820f58f57..2f60fd4ea51 100644 --- a/src/System.Private.CoreLib/shared/System/ArrayTypeMismatchException.cs +++ b/src/System.Private.CoreLib/shared/System/ArrayTypeMismatchException.cs @@ -34,13 +34,13 @@ public ArrayTypeMismatchException() // message, its HRESULT set to COR_E_ARRAYTYPEMISMATCH, // and its ExceptionInfo reference set to null. // - public ArrayTypeMismatchException(String message) + public ArrayTypeMismatchException(string message) : base(message) { HResult = HResults.COR_E_ARRAYTYPEMISMATCH; } - public ArrayTypeMismatchException(String message, Exception innerException) + public ArrayTypeMismatchException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_ARRAYTYPEMISMATCH; diff --git a/src/System.Private.CoreLib/shared/System/BadImageFormatException.cs b/src/System.Private.CoreLib/shared/System/BadImageFormatException.cs index 1743075a6fd..c8cb65c64a3 100644 --- a/src/System.Private.CoreLib/shared/System/BadImageFormatException.cs +++ b/src/System.Private.CoreLib/shared/System/BadImageFormatException.cs @@ -21,8 +21,8 @@ namespace System [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public partial class BadImageFormatException : SystemException { - private String _fileName; // The name of the corrupt PE file. - private String _fusionLog = null; // fusion log (when applicable) + private string _fileName; // The name of the corrupt PE file. + private string _fusionLog = null; // fusion log (when applicable) public BadImageFormatException() : base(SR.Arg_BadImageFormatException) @@ -30,25 +30,25 @@ public BadImageFormatException() HResult = HResults.COR_E_BADIMAGEFORMAT; } - public BadImageFormatException(String message) + public BadImageFormatException(string message) : base(message) { HResult = HResults.COR_E_BADIMAGEFORMAT; } - public BadImageFormatException(String message, Exception inner) + public BadImageFormatException(string message, Exception inner) : base(message, inner) { HResult = HResults.COR_E_BADIMAGEFORMAT; } - public BadImageFormatException(String message, String fileName) : base(message) + public BadImageFormatException(string message, string fileName) : base(message) { HResult = HResults.COR_E_BADIMAGEFORMAT; _fileName = fileName; } - public BadImageFormatException(String message, String fileName, Exception inner) + public BadImageFormatException(string message, string fileName, Exception inner) : base(message, inner) { HResult = HResults.COR_E_BADIMAGEFORMAT; @@ -69,7 +69,7 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont info.AddValue("BadImageFormat_FusionLog", _fusionLog, typeof(string)); } - public override String Message + public override string Message { get { @@ -91,14 +91,14 @@ private void SetMessageField() } } - public String FileName + public string FileName { get { return _fileName; } } - public override String ToString() + public override string ToString() { - String s = GetType().ToString() + ": " + Message; + string s = GetType().ToString() + ": " + Message; if (_fileName != null && _fileName.Length != 0) s += Environment.NewLine + SR.Format(SR.IO_FileName_Name, _fileName); @@ -121,7 +121,7 @@ public override String ToString() return s; } - public String FusionLog + public string FusionLog { get { return _fusionLog; } } diff --git a/src/System.Private.CoreLib/shared/System/BitConverter.cs b/src/System.Private.CoreLib/shared/System/BitConverter.cs index e3cf20eb6a8..8a8101ddce2 100644 --- a/src/System.Private.CoreLib/shared/System/BitConverter.cs +++ b/src/System.Private.CoreLib/shared/System/BitConverter.cs @@ -376,7 +376,7 @@ public static string ToString(byte[] value, int startIndex, int length) if (length > (int.MaxValue / 3)) { - // (Int32.MaxValue / 3) == 715,827,882 Bytes == 699 MB + // (int.MaxValue / 3) == 715,827,882 Bytes == 699 MB throw new ArgumentOutOfRangeException(nameof(length), SR.Format(SR.ArgumentOutOfRange_LengthTooLarge, (int.MaxValue / 3))); } diff --git a/src/System.Private.CoreLib/shared/System/Boolean.cs b/src/System.Private.CoreLib/shared/System/Boolean.cs index c55fc65ccbc..dbc7bd75ee5 100644 --- a/src/System.Private.CoreLib/shared/System/Boolean.cs +++ b/src/System.Private.CoreLib/shared/System/Boolean.cs @@ -19,7 +19,7 @@ namespace System { [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] - public struct Boolean : IComparable, IConvertible, IComparable, IEquatable + public struct Boolean : IComparable, IConvertible, IComparable, IEquatable { // // Member Variables @@ -41,11 +41,11 @@ public struct Boolean : IComparable, IConvertible, IComparable, IEquata // The internal string representation of true. // - internal const String TrueLiteral = "True"; + internal const string TrueLiteral = "True"; // The internal string representation of false. // - internal const String FalseLiteral = "False"; + internal const string FalseLiteral = "False"; // @@ -54,11 +54,11 @@ public struct Boolean : IComparable, IConvertible, IComparable, IEquata // The public string representation of true. // - public static readonly String TrueString = TrueLiteral; + public static readonly string TrueString = TrueLiteral; // The public string representation of false. // - public static readonly String FalseString = FalseLiteral; + public static readonly string FalseString = FalseLiteral; // // Overriden Instance Methods @@ -81,7 +81,7 @@ public override int GetHashCode() **Exceptions: None. ==============================================================================*/ // Converts the boolean value of this instance to a String. - public override String ToString() + public override string ToString() { if (false == m_value) { @@ -90,7 +90,7 @@ public override String ToString() return TrueLiteral; } - public String ToString(IFormatProvider provider) + public string ToString(IFormatProvider provider) { return ToString(); } @@ -112,19 +112,19 @@ public bool TryFormat(Span destination, out int charsWritten) } // Determines whether two Boolean objects are equal. - public override bool Equals(Object obj) + public override bool Equals(object obj) { //If it's not a boolean, we're definitely not equal - if (!(obj is Boolean)) + if (!(obj is bool)) { return false; } - return (m_value == ((Boolean)obj).m_value); + return (m_value == ((bool)obj).m_value); } [NonVersionable] - public bool Equals(Boolean obj) + public bool Equals(bool obj) { return m_value == obj; } @@ -136,18 +136,18 @@ public bool Equals(Boolean obj) // // Returns a value less than zero if this object // - public int CompareTo(Object obj) + public int CompareTo(object obj) { if (obj == null) { return 1; } - if (!(obj is Boolean)) + if (!(obj is bool)) { throw new ArgumentException(SR.Arg_MustBeBoolean); } - if (m_value == ((Boolean)obj).m_value) + if (m_value == ((bool)obj).m_value) { return 0; } @@ -158,7 +158,7 @@ public int CompareTo(Object obj) return 1; } - public int CompareTo(Boolean value) + public int CompareTo(bool value) { if (m_value == value) { @@ -198,7 +198,7 @@ internal static bool IsFalseStringIgnoreCase(ReadOnlySpan value) // Determines whether a String represents true or false. // - public static Boolean Parse(String value) + public static bool Parse(string value) { if (value == null) throw new ArgumentNullException(nameof(value)); return Parse(value.AsSpan()); @@ -209,7 +209,7 @@ public static Boolean Parse(String value) // Determines whether a String represents true or false. // - public static Boolean TryParse(String value, out Boolean result) + public static bool TryParse(string value, out bool result) { if (value == null) { @@ -260,7 +260,7 @@ private static ReadOnlySpan TrimWhiteSpaceAndNull(ReadOnlySpan value int start = 0; while (start < value.Length) { - if (!Char.IsWhiteSpace(value[start]) && value[start] != nullChar) + if (!char.IsWhiteSpace(value[start]) && value[start] != nullChar) { break; } @@ -270,7 +270,7 @@ private static ReadOnlySpan TrimWhiteSpaceAndNull(ReadOnlySpan value int end = value.Length - 1; while (end >= start) { - if (!Char.IsWhiteSpace(value[end]) && value[end] != nullChar) + if (!char.IsWhiteSpace(value[end]) && value[end] != nullChar) { break; } @@ -350,7 +350,7 @@ float IConvertible.ToSingle(IFormatProvider provider) return Convert.ToDouble(m_value); } - Decimal IConvertible.ToDecimal(IFormatProvider provider) + decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } @@ -360,7 +360,7 @@ DateTime IConvertible.ToDateTime(IFormatProvider provider) throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Boolean", "DateTime")); } - 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/System.Private.CoreLib/shared/System/Byte.cs b/src/System.Private.CoreLib/shared/System/Byte.cs index 31185f0ed02..64512b0feed 100644 --- a/src/System.Private.CoreLib/shared/System/Byte.cs +++ b/src/System.Private.CoreLib/shared/System/Byte.cs @@ -12,7 +12,7 @@ namespace System [Serializable] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] - public struct Byte : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable + public struct Byte : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable { private byte m_value; // Do not rename (binary serialization) @@ -29,37 +29,37 @@ public struct Byte : IComparable, IConvertible, IFormattable, IComparable, // 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) + public int CompareTo(object value) { if (value == null) { return 1; } - if (!(value is Byte)) + if (!(value is byte)) { throw new ArgumentException(SR.Arg_MustBeByte); } - return m_value - (((Byte)value).m_value); + 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) + public override bool Equals(object obj) { - if (!(obj is Byte)) + if (!(obj is byte)) { return false; } - return m_value == ((Byte)obj).m_value; + return m_value == ((byte)obj).m_value; } [NonVersionable] - public bool Equals(Byte obj) + public bool Equals(byte obj) { return m_value == obj; } @@ -70,20 +70,20 @@ public override int GetHashCode() return m_value; } - public static byte Parse(String s) + public static byte Parse(string s) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan)s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } - public static byte Parse(String s, NumberStyles style) + public static byte Parse(string s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan)s, style, NumberFormatInfo.CurrentInfo); } - public static byte Parse(String s, IFormatProvider provider) + public static byte Parse(string s, IFormatProvider provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan)s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); @@ -92,7 +92,7 @@ public static byte Parse(String s, IFormatProvider 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. - public static byte Parse(String s, NumberStyles style, IFormatProvider provider) + public static byte Parse(string s, NumberStyles style, IFormatProvider provider) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); @@ -121,7 +121,7 @@ private static byte Parse(ReadOnlySpan s, NumberStyles style, NumberFormat return (byte)i; } - public static bool TryParse(String s, out Byte result) + public static bool TryParse(string s, out byte result) { if (s == null) { @@ -137,7 +137,7 @@ public static bool TryParse(ReadOnlySpan 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); @@ -156,7 +156,7 @@ public static bool TryParse(ReadOnlySpan s, NumberStyles style, IFormatPro return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result); } - private static bool TryParse(ReadOnlySpan s, NumberStyles style, NumberFormatInfo info, out Byte result) + private static bool TryParse(ReadOnlySpan s, NumberStyles style, NumberFormatInfo info, out byte result) { result = 0; int i; @@ -172,22 +172,22 @@ private static bool TryParse(ReadOnlySpan s, NumberStyles style, NumberFor return true; } - public override String ToString() + public override string ToString() { return Number.FormatInt32(m_value, null, null); } - public String ToString(String format) + public string ToString(string format) { return Number.FormatInt32(m_value, format, null); } - public String ToString(IFormatProvider provider) + public string ToString(IFormatProvider provider) { return Number.FormatInt32(m_value, null, provider); } - public String ToString(String format, IFormatProvider provider) + public string ToString(string format, IFormatProvider provider) { return Number.FormatInt32(m_value, format, provider); } @@ -266,7 +266,7 @@ float IConvertible.ToSingle(IFormatProvider provider) return Convert.ToDouble(m_value); } - Decimal IConvertible.ToDecimal(IFormatProvider provider) + decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } @@ -276,7 +276,7 @@ DateTime IConvertible.ToDateTime(IFormatProvider provider) throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Byte", "DateTime")); } - 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/System.Private.CoreLib/shared/System/Char.cs b/src/System.Private.CoreLib/shared/System/Char.cs index d3ed1f5b683..a3d29634020 100644 --- a/src/System.Private.CoreLib/shared/System/Char.cs +++ b/src/System.Private.CoreLib/shared/System/Char.cs @@ -21,7 +21,7 @@ namespace System [Serializable] [StructLayout(LayoutKind.Sequential)] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] - public struct Char : IComparable, IComparable, IEquatable, IConvertible + public struct Char : IComparable, IComparable, IEquatable, IConvertible { // // Member Variables @@ -87,7 +87,7 @@ private static bool IsAscii(char ch) // Return the Unicode category for Unicode character <= 0x00ff. private static UnicodeCategory GetLatin1UnicodeCategory(char ch) { - Debug.Assert(IsLatin1(ch), "Char.GetLatin1UnicodeCategory(): ch should be <= 007f"); + Debug.Assert(IsLatin1(ch), "char.GetLatin1UnicodeCategory(): ch should be <= 007f"); return (UnicodeCategory)(s_categoryForLatin1[(int)ch]); } @@ -107,17 +107,17 @@ public override int GetHashCode() // Used for comparing two boxed Char objects. // - public override bool Equals(Object obj) + public override bool Equals(object obj) { - if (!(obj is Char)) + if (!(obj is char)) { return false; } - return (m_value == ((Char)obj).m_value); + return (m_value == ((char)obj).m_value); } [System.Runtime.Versioning.NonVersionable] - public bool Equals(Char obj) + public bool Equals(char obj) { return m_value == obj; } @@ -128,34 +128,34 @@ public bool Equals(Char obj) // null is considered to be less than any instance. // If object is not of type Char, this method throws an ArgumentException. // - public int CompareTo(Object value) + public int CompareTo(object value) { if (value == null) { return 1; } - if (!(value is Char)) + if (!(value is char)) { throw new ArgumentException(SR.Arg_MustBeChar); } - return (m_value - ((Char)value).m_value); + return (m_value - ((char)value).m_value); } - public int CompareTo(Char value) + public int CompareTo(char value) { return (m_value - value); } // Overrides System.Object.ToString. - public override String ToString() + public override string ToString() { - return Char.ToString(m_value); + return char.ToString(m_value); } - public String ToString(IFormatProvider provider) + public string ToString(IFormatProvider provider) { - return Char.ToString(m_value); + return char.ToString(m_value); } // @@ -168,7 +168,7 @@ public String ToString(IFormatProvider provider) // Provides a string representation of a character. public static string ToString(char c) => string.CreateFromChar(c); - public static char Parse(String s) + public static char Parse(string s) { if (s == null) { @@ -182,7 +182,7 @@ public static char Parse(String s) return s[0]; } - public static bool TryParse(String s, out Char result) + public static bool TryParse(string s, out char result) { result = '\0'; if (s == null) @@ -201,7 +201,7 @@ public static bool TryParse(String s, out Char result) // Static Methods // /*=================================ISDIGIT====================================== - **A wrapper for Char. Returns a boolean indicating whether ** + **A wrapper for char. Returns a boolean indicating whether ** **character c is considered to be a digit. ** ==============================================================================*/ // Determines whether a character is a digit. @@ -233,7 +233,7 @@ internal static bool CheckLetter(UnicodeCategory uc) } /*=================================ISLETTER===================================== - **A wrapper for Char. Returns a boolean indicating whether ** + **A wrapper for char. Returns a boolean indicating whether ** **character c is considered to be a letter. ** ==============================================================================*/ // Determines whether a character is a letter. @@ -271,7 +271,7 @@ private static bool IsWhiteSpaceLatin1(char c) } /*===============================ISWHITESPACE=================================== - **A wrapper for Char. Returns a boolean indicating whether ** + **A wrapper for char. Returns a boolean indicating whether ** **character c is considered to be a whitespace character. ** ==============================================================================*/ // Determines whether a character is whitespace. @@ -393,7 +393,7 @@ public static char ToUpper(char c, CultureInfo culture) } /*=================================TOUPPER====================================== - **A wrapper for Char.toUpperCase. Converts character c to its ** + **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. ** ==============================================================================*/ @@ -425,7 +425,7 @@ public static char ToLower(char c, CultureInfo culture) } /*=================================TOLOWER====================================== - **A wrapper for Char.toLowerCase. Converts character c to its ** + **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. ** ==============================================================================*/ @@ -512,7 +512,7 @@ float IConvertible.ToSingle(IFormatProvider provider) throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Char", "Double")); } - Decimal IConvertible.ToDecimal(IFormatProvider provider) + decimal IConvertible.ToDecimal(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Char", "Decimal")); } @@ -522,7 +522,7 @@ DateTime IConvertible.ToDateTime(IFormatProvider provider) throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Char", "DateTime")); } - Object IConvertible.ToType(Type type, IFormatProvider provider) + object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } @@ -535,7 +535,7 @@ public static bool IsControl(char c) return (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.Control); } - public static bool IsControl(String s, int index) + public static bool IsControl(string s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); @@ -552,7 +552,7 @@ public static bool IsControl(String s, int index) } - public static bool IsDigit(String s, int index) + public static bool IsDigit(string s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); @@ -568,7 +568,7 @@ public static bool IsDigit(String s, int index) return (CharUnicodeInfo.GetUnicodeCategory(s, index) == UnicodeCategory.DecimalDigitNumber); } - public static bool IsLetter(String s, int index) + public static bool IsLetter(string s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); @@ -589,7 +589,7 @@ public static bool IsLetter(String s, int index) return (CheckLetter(CharUnicodeInfo.GetUnicodeCategory(s, index))); } - public static bool IsLetterOrDigit(String s, int index) + public static bool IsLetterOrDigit(string s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); @@ -605,7 +605,7 @@ public static bool IsLetterOrDigit(String s, int index) return CheckLetterOrDigit(CharUnicodeInfo.GetUnicodeCategory(s, index)); } - public static bool IsLower(String s, int index) + public static bool IsLower(string s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); @@ -655,7 +655,7 @@ public static bool IsNumber(char c) return (CheckNumber(CharUnicodeInfo.GetUnicodeCategory(c))); } - public static bool IsNumber(String s, int index) + public static bool IsNumber(string s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); @@ -683,7 +683,7 @@ public static bool IsNumber(String s, int index) // //////////////////////////////////////////////////////////////////////// - public static bool IsPunctuation(String s, int index) + public static bool IsPunctuation(string s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); @@ -732,7 +732,7 @@ public static bool IsSeparator(char c) return (CheckSeparator(CharUnicodeInfo.GetUnicodeCategory(c))); } - public static bool IsSeparator(String s, int index) + public static bool IsSeparator(string s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); @@ -753,7 +753,7 @@ public static bool IsSurrogate(char c) return (c >= HIGH_SURROGATE_START && c <= LOW_SURROGATE_END); } - public static bool IsSurrogate(String s, int index) + public static bool IsSurrogate(string s, int index) { if (s == null) { @@ -792,7 +792,7 @@ public static bool IsSymbol(char c) return (CheckSymbol(CharUnicodeInfo.GetUnicodeCategory(c))); } - public static bool IsSymbol(String s, int index) + public static bool IsSymbol(string s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); @@ -809,7 +809,7 @@ public static bool IsSymbol(String s, int index) } - public static bool IsUpper(String s, int index) + public static bool IsUpper(string s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); @@ -830,7 +830,7 @@ public static bool IsUpper(String s, int index) return (CharUnicodeInfo.GetUnicodeCategory(s, index) == UnicodeCategory.UppercaseLetter); } - public static bool IsWhiteSpace(String s, int index) + public static bool IsWhiteSpace(string s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); @@ -856,7 +856,7 @@ public static UnicodeCategory GetUnicodeCategory(char c) return CharUnicodeInfo.GetUnicodeCategory((int)c); } - public static UnicodeCategory GetUnicodeCategory(String s, int index) + public static UnicodeCategory GetUnicodeCategory(string s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); @@ -876,7 +876,7 @@ public static double GetNumericValue(char c) return CharUnicodeInfo.GetNumericValue(c); } - public static double GetNumericValue(String s, int index) + public static double GetNumericValue(string s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); @@ -896,7 +896,7 @@ public static bool IsHighSurrogate(char c) return ((c >= CharUnicodeInfo.HIGH_SURROGATE_START) && (c <= CharUnicodeInfo.HIGH_SURROGATE_END)); } - public static bool IsHighSurrogate(String s, int index) + public static bool IsHighSurrogate(string s, int index) { if (s == null) { @@ -917,7 +917,7 @@ public static bool IsLowSurrogate(char c) return ((c >= CharUnicodeInfo.LOW_SURROGATE_START) && (c <= CharUnicodeInfo.LOW_SURROGATE_END)); } - public static bool IsLowSurrogate(String s, int index) + public static bool IsLowSurrogate(string s, int index) { if (s == null) { @@ -933,7 +933,7 @@ public static bool IsLowSurrogate(String s, int index) /*================================= IsSurrogatePair ============================ ** Check if the string specified by the index starts with a surrogate pair. ==============================================================================*/ - public static bool IsSurrogatePair(String s, int index) + public static bool IsSurrogatePair(string s, int index) { if (s == null) { @@ -972,7 +972,7 @@ public static bool IsSurrogatePair(char highSurrogate, char lowSurrogate) ** Convert an UTF32 value into a surrogate pair. ==============================================================================*/ - public static String ConvertFromUtf32(int utf32) + 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. @@ -984,7 +984,7 @@ public static String ConvertFromUtf32(int utf32) if (utf32 < UNICODE_PLANE01_START) { // This is a BMP character. - return (Char.ToString((char)utf32)); + return (char.ToString((char)utf32)); } unsafe @@ -1025,7 +1025,7 @@ public static int ConvertToUtf32(char highSurrogate, char lowSurrogate) ** This method throws if a low surrogate is seen without preceding a high-surrogate. ==============================================================================*/ - public static int ConvertToUtf32(String s, int index) + public static int ConvertToUtf32(string s, int index) { if (s == null) { diff --git a/src/System.Private.CoreLib/shared/System/CharEnumerator.cs b/src/System.Private.CoreLib/shared/System/CharEnumerator.cs index ea9915a7c4f..ca60705d991 100644 --- a/src/System.Private.CoreLib/shared/System/CharEnumerator.cs +++ b/src/System.Private.CoreLib/shared/System/CharEnumerator.cs @@ -19,11 +19,11 @@ namespace System { public sealed class CharEnumerator : IEnumerator, IEnumerator, IDisposable, ICloneable { - private String _str; + private string _str; private int _index; private char _currentElement; - internal CharEnumerator(String str) + internal CharEnumerator(string str) { _str = str; _index = -1; @@ -54,7 +54,7 @@ public void Dispose() _str = null; } - Object IEnumerator.Current + object IEnumerator.Current { get { return Current; } } diff --git a/src/System.Private.CoreLib/shared/System/Collections/Comparer.cs b/src/System.Private.CoreLib/shared/System/Collections/Comparer.cs index 6fcedc09ab0..e22fb5bb91b 100644 --- a/src/System.Private.CoreLib/shared/System/Collections/Comparer.cs +++ b/src/System.Private.CoreLib/shared/System/Collections/Comparer.cs @@ -52,7 +52,7 @@ public void GetObjectData(SerializationInfo info, StreamingContext context) // If a doesn't implement IComparable and b does, -(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; diff --git a/src/System.Private.CoreLib/shared/System/Collections/DictionaryEntry.cs b/src/System.Private.CoreLib/shared/System/Collections/DictionaryEntry.cs index 3c1c0befa39..187301a08f4 100644 --- a/src/System.Private.CoreLib/shared/System/Collections/DictionaryEntry.cs +++ b/src/System.Private.CoreLib/shared/System/Collections/DictionaryEntry.cs @@ -12,18 +12,18 @@ namespace System.Collections [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public struct DictionaryEntry { - private Object _key; // Do not rename (binary serialization) - private Object _value; // Do not rename (binary serialization) + private object _key; // Do not rename (binary serialization) + private object _value; // Do not rename (binary serialization) // 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 + public object Key { get { @@ -36,7 +36,7 @@ public Object Key } } - public Object Value + public object Value { get { diff --git a/src/System.Private.CoreLib/shared/System/Collections/Generic/ArraySortHelper.cs b/src/System.Private.CoreLib/shared/System/Collections/Generic/ArraySortHelper.cs index 8ee3004f2ef..b717bd76219 100644 --- a/src/System.Private.CoreLib/shared/System/Collections/Generic/ArraySortHelper.cs +++ b/src/System.Private.CoreLib/shared/System/Collections/Generic/ArraySortHelper.cs @@ -38,7 +38,7 @@ internal static int FloorLog2PlusOne(int n) return result; } - internal static void ThrowOrIgnoreBadComparer(Object comparer) + internal static void ThrowOrIgnoreBadComparer(object comparer) { throw new ArgumentException(SR.Format(SR.Arg_BogusIComparer, comparer)); } diff --git a/src/System.Private.CoreLib/shared/System/Collections/Generic/Dictionary.cs b/src/System.Private.CoreLib/shared/System/Collections/Generic/Dictionary.cs index a7f64f4c402..ece6f44f33b 100644 --- a/src/System.Private.CoreLib/shared/System/Collections/Generic/Dictionary.cs +++ b/src/System.Private.CoreLib/shared/System/Collections/Generic/Dictionary.cs @@ -1183,7 +1183,7 @@ public bool MoveNext() } // 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 + // dictionary.count+1 could be negative if dictionary.count is int.MaxValue while ((uint)_index < (uint)_dictionary._count) { ref Entry entry = ref _dictionary._entries[_index++]; diff --git a/src/System.Private.CoreLib/shared/System/Collections/Generic/KeyNotFoundException.cs b/src/System.Private.CoreLib/shared/System/Collections/Generic/KeyNotFoundException.cs index 48eddb87454..3990e13784b 100644 --- a/src/System.Private.CoreLib/shared/System/Collections/Generic/KeyNotFoundException.cs +++ b/src/System.Private.CoreLib/shared/System/Collections/Generic/KeyNotFoundException.cs @@ -17,13 +17,13 @@ public KeyNotFoundException() HResult = HResults.COR_E_KEYNOTFOUND; } - public KeyNotFoundException(String message) + public KeyNotFoundException(string message) : base(message) { HResult = HResults.COR_E_KEYNOTFOUND; } - public KeyNotFoundException(String message, Exception innerException) + public KeyNotFoundException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_KEYNOTFOUND; diff --git a/src/System.Private.CoreLib/shared/System/Collections/Hashtable.cs b/src/System.Private.CoreLib/shared/System/Collections/Hashtable.cs index 1ee12138f87..1c3139d2718 100644 --- a/src/System.Private.CoreLib/shared/System/Collections/Hashtable.cs +++ b/src/System.Private.CoreLib/shared/System/Collections/Hashtable.cs @@ -110,16 +110,16 @@ public class Hashtable : IDictionary, ISerializable, IDeserializationCallback, I -- */ - private const Int32 InitialSize = 3; + private const int InitialSize = 3; - private const String LoadFactorName = "LoadFactor"; // Do not rename (binary serialization) - private const String VersionName = "Version"; // Do not rename (binary serialization) - private const String ComparerName = "Comparer"; // Do not rename (binary serialization) - private const String HashCodeProviderName = "HashCodeProvider"; // Do not rename (binary serialization) - private const String HashSizeName = "HashSize"; // Must save buckets.Length. Do not rename (binary serialization) - private const String KeysName = "Keys"; // Do not rename (binary serialization) - private const String ValuesName = "Values"; // Do not rename (binary serialization) - private const String KeyComparerName = "KeyComparer"; // Do not rename (binary serialization) + private const string LoadFactorName = "LoadFactor"; // Do not rename (binary serialization) + private const string VersionName = "Version"; // Do not rename (binary serialization) + private const string ComparerName = "Comparer"; // Do not rename (binary serialization) + private const string HashCodeProviderName = "HashCodeProvider"; // Do not rename (binary serialization) + private const string HashSizeName = "HashSize"; // Must save buckets.Length. Do not rename (binary serialization) + private const string KeysName = "Keys"; // Do not rename (binary serialization) + private const string ValuesName = "Values"; // Do not rename (binary serialization) + private const string KeyComparerName = "KeyComparer"; // Do not rename (binary serialization) // Deleted entries have their key set to buckets @@ -127,8 +127,8 @@ public class Hashtable : IDictionary, ISerializable, IDeserializationCallback, I // This cannot be serialized private struct bucket { - public Object key; - public Object val; + public object key; + public object val; public int hash_coll; // Store hash code; sign bit means there was a collision. } @@ -150,7 +150,7 @@ private struct bucket private ICollection _values; private IEqualityComparer _keycomparer; - private Object _syncRoot; + private object _syncRoot; [Obsolete("Please use EqualityComparer property.")] protected IHashCodeProvider hcp @@ -278,7 +278,7 @@ public Hashtable(int capacity, float loadFactor) _loadFactor = 0.72f * loadFactor; double rawsize = capacity / _loadFactor; - if (rawsize > Int32.MaxValue) + if (rawsize > int.MaxValue) throw new ArgumentException(SR.Arg_HTCapacityOverflow, nameof(capacity)); // Avoid awfully small sizes @@ -404,7 +404,7 @@ protected Hashtable(SerializationInfo info, StreamingContext context) // 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. @@ -423,7 +423,7 @@ private uint InitHash(Object key, int hashsize, out uint seed, out uint incr) // 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); } @@ -453,7 +453,7 @@ public virtual void Clear() // 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() + public virtual object Clone() { bucket[] lbuckets = _buckets; Hashtable ht = new Hashtable(_count, _keycomparer); @@ -465,7 +465,7 @@ public virtual Object Clone() while (bucket > 0) { bucket--; - Object keyv = lbuckets[bucket].key; + object keyv = lbuckets[bucket].key; if ((keyv != null) && (keyv != lbuckets)) { ht[keyv] = lbuckets[bucket].val; @@ -476,7 +476,7 @@ public virtual Object Clone() } // Checks if this hashtable contains the given key. - public virtual bool Contains(Object key) + public virtual bool Contains(object key) { return ContainsKey(key); } @@ -484,7 +484,7 @@ public virtual bool Contains(Object key) // Checks if this hashtable contains an entry with the given key. This is // an O(1) operation. // - public virtual bool ContainsKey(Object key) + public virtual bool ContainsKey(object key) { if (key == null) { @@ -523,7 +523,7 @@ public virtual bool ContainsKey(Object key) // search and is thus be substantially slower than the ContainsKey // method. // - public virtual bool ContainsValue(Object value) + public virtual bool ContainsValue(object value) { if (value == null) { @@ -537,7 +537,7 @@ public virtual bool ContainsValue(Object value) { for (int i = _buckets.Length; --i >= 0;) { - Object val = _buckets[i].val; + object val = _buckets[i].val; if (val != null && val.Equals(value)) return true; } @@ -556,7 +556,7 @@ private void CopyKeys(Array array, int arrayIndex) bucket[] lbuckets = _buckets; for (int i = lbuckets.Length; --i >= 0;) { - Object keyv = lbuckets[i].key; + object keyv = lbuckets[i].key; if ((keyv != null) && (keyv != _buckets)) { array.SetValue(keyv, arrayIndex++); @@ -575,7 +575,7 @@ private void CopyEntries(Array array, int arrayIndex) bucket[] lbuckets = _buckets; for (int i = lbuckets.Length; --i >= 0;) { - Object keyv = lbuckets[i].key; + object keyv = lbuckets[i].key; if ((keyv != null) && (keyv != _buckets)) { DictionaryEntry entry = new DictionaryEntry(keyv, lbuckets[i].val); @@ -611,7 +611,7 @@ internal virtual KeyValuePairs[] ToKeyValuePairsArray() bucket[] lbuckets = _buckets; for (int i = lbuckets.Length; --i >= 0;) { - Object keyv = lbuckets[i].key; + object keyv = lbuckets[i].key; if ((keyv != null) && (keyv != _buckets)) { array[index++] = new KeyValuePairs(keyv, lbuckets[i].val); @@ -633,7 +633,7 @@ private void CopyValues(Array array, int arrayIndex) bucket[] lbuckets = _buckets; for (int i = lbuckets.Length; --i >= 0;) { - Object keyv = lbuckets[i].key; + object keyv = lbuckets[i].key; if ((keyv != null) && (keyv != _buckets)) { array.SetValue(lbuckets[i].val, arrayIndex++); @@ -644,7 +644,7 @@ private void CopyValues(Array array, int 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] + public virtual object this[object key] { get { @@ -736,7 +736,7 @@ private void rehash() private void UpdateVersion() { - // Version might become negative when version is Int32.MaxValue, but the oddity will be still be correct. + // Version might become negative when version is int.MaxValue, but the oddity will be still be correct. // So we don't need to special case this. _version++; } @@ -799,7 +799,7 @@ public virtual IDictionaryEnumerator GetEnumerator() // 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). - protected virtual int GetHash(Object key) + protected virtual int GetHash(object key) { if (_keycomparer != null) return _keycomparer.GetHashCode(key); @@ -827,15 +827,15 @@ public virtual bool IsSynchronized // instance in the constructor, this method will call comparer.Compare(item, key). // Otherwise, it will call item.Equals(key). // - protected virtual bool KeyEquals(Object item, Object key) + 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) @@ -885,7 +885,7 @@ public virtual ICollection 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) + private void Insert(object key, object nvalue, bool add) { if (key == null) { @@ -998,7 +998,7 @@ private void Insert(Object key, Object nvalue, bool add) throw new InvalidOperationException(SR.InvalidOperation_HashInsertFailed); } - private void putEntry(bucket[] newBuckets, Object key, Object nvalue, int hashcode) + private void putEntry(bucket[] newBuckets, object key, object nvalue, int hashcode) { Debug.Assert(hashcode >= 0, "hashcode >= 0"); // make sure collision bit (sign bit) wasn't set. @@ -1028,7 +1028,7 @@ private void putEntry(bucket[] newBuckets, Object key, Object nvalue, int hashco // key exists in the hashtable, it is removed. An ArgumentException is // thrown if the key is null. // - public virtual void Remove(Object key) + public virtual void Remove(object key) { if (key == null) { @@ -1073,13 +1073,13 @@ public virtual void Remove(Object key) } // Returns the object to synchronize on for this hash table. - public virtual Object SyncRoot + public virtual object SyncRoot { get { if (_syncRoot == null) { - System.Threading.Interlocked.CompareExchange(ref _syncRoot, new Object(), null); + System.Threading.Interlocked.CompareExchange(ref _syncRoot, new object(), null); } return _syncRoot; } @@ -1145,12 +1145,12 @@ public virtual void GetObjectData(SerializationInfo info, StreamingContext conte #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]; + 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(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 in their code. @@ -1164,7 +1164,7 @@ public virtual void GetObjectData(SerializationInfo info, StreamingContext conte // // DeserializationEvent Listener // - public virtual void OnDeserialization(Object sender) + public virtual void OnDeserialization(object sender) { if (_buckets != null) { @@ -1187,8 +1187,8 @@ public virtual void OnDeserialization(Object sender) IHashCodeProvider hcp = null; #pragma warning restore 618 - Object[] serKeys = null; - Object[] serValues = null; + object[] serKeys = null; + object[] serValues = null; SerializationInfoEnumerator enumerator = siInfo.GetEnumerator(); @@ -1214,10 +1214,10 @@ public virtual void OnDeserialization(Object sender) #pragma warning restore 618 break; case KeysName: - serKeys = (Object[])siInfo.GetValue(KeysName, typeof(Object[])); + serKeys = (object[])siInfo.GetValue(KeysName, typeof(object[])); break; case ValuesName: - serValues = (Object[])siInfo.GetValue(ValuesName, typeof(Object[])); + serValues = (object[])siInfo.GetValue(ValuesName, typeof(object[])); break; } } @@ -1292,7 +1292,7 @@ public virtual bool IsSynchronized get { return _hashtable.IsSynchronized; } } - public virtual Object SyncRoot + public virtual object SyncRoot { get { return _hashtable.SyncRoot; } } @@ -1337,7 +1337,7 @@ public virtual bool IsSynchronized get { return _hashtable.IsSynchronized; } } - public virtual Object SyncRoot + public virtual object SyncRoot { get { return _hashtable.SyncRoot; } } @@ -1388,7 +1388,7 @@ public override bool IsSynchronized get { return true; } } - public override Object this[Object key] + public override object this[object key] { get { @@ -1403,12 +1403,12 @@ public override bool IsSynchronized } } - public override Object SyncRoot + public override object SyncRoot { get { return _table.SyncRoot; } } - public override void Add(Object key, Object value) + public override void Add(object key, object value) { lock (_table.SyncRoot) { @@ -1424,12 +1424,12 @@ public override void Clear() } } - public override bool Contains(Object key) + public override bool Contains(object key) { return _table.Contains(key); } - public override bool ContainsKey(Object key) + public override bool ContainsKey(object key) { if (key == null) { @@ -1438,7 +1438,7 @@ public override bool ContainsKey(Object key) return _table.ContainsKey(key); } - public override bool ContainsValue(Object key) + public override bool ContainsValue(object key) { lock (_table.SyncRoot) { @@ -1454,7 +1454,7 @@ public override void CopyTo(Array array, int arrayIndex) } } - public override Object Clone() + public override object Clone() { lock (_table.SyncRoot) { @@ -1494,7 +1494,7 @@ public override ICollection Values } } - public override void Remove(Object key) + public override void Remove(object key) { lock (_table.SyncRoot) { @@ -1502,7 +1502,7 @@ public override void Remove(Object key) } } - public override void OnDeserialization(Object sender) + public override void OnDeserialization(object sender) { // 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 @@ -1526,8 +1526,8 @@ private class HashtableEnumerator : IDictionaryEnumerator, ICloneable private int _version; private bool _current; private int _getObjectRetType; // What should GetObject return? - private Object _currentKey; - private Object _currentValue; + private object _currentKey; + private object _currentValue; internal const int Keys = 1; internal const int Values = 2; @@ -1544,7 +1544,7 @@ internal HashtableEnumerator(Hashtable hashtable, int getObjRetType) public object Clone() => MemberwiseClone(); - public virtual Object Key + public virtual object Key { get { @@ -1561,7 +1561,7 @@ public virtual bool MoveNext() while (_bucket > 0) { _bucket--; - Object keyv = _hashtable._buckets[_bucket].key; + object keyv = _hashtable._buckets[_bucket].key; if ((keyv != null) && (keyv != _hashtable._buckets)) { _currentKey = keyv; @@ -1585,7 +1585,7 @@ public virtual DictionaryEntry Entry } - public virtual Object Current + public virtual object Current { get { @@ -1601,7 +1601,7 @@ public virtual Object Current } } - public virtual Object Value + public virtual object Value { get { diff --git a/src/System.Private.CoreLib/shared/System/Collections/ICollection.cs b/src/System.Private.CoreLib/shared/System/Collections/ICollection.cs index b8eba71c240..65e37c73813 100644 --- a/src/System.Private.CoreLib/shared/System/Collections/ICollection.cs +++ b/src/System.Private.CoreLib/shared/System/Collections/ICollection.cs @@ -54,7 +54,7 @@ int Count // that the this pointer may not be sufficient for collections that // wrap other collections; those should return the underlying // collection's SyncRoot property. - Object SyncRoot + object SyncRoot { get; } // Is this collection synchronized (i.e., thread-safe)? If you want a diff --git a/src/System.Private.CoreLib/shared/System/Collections/IComparer.cs b/src/System.Private.CoreLib/shared/System/Collections/IComparer.cs index cef91c3ffa2..38bab78b3c4 100644 --- a/src/System.Private.CoreLib/shared/System/Collections/IComparer.cs +++ b/src/System.Private.CoreLib/shared/System/Collections/IComparer.cs @@ -17,6 +17,6 @@ public interface IComparer // value less than zero if x is less than y, zero if x is equal to y, or a // value greater than zero if x is greater than y. // - int Compare(Object x, Object y); + int Compare(object x, object y); } } diff --git a/src/System.Private.CoreLib/shared/System/Collections/IDictionary.cs b/src/System.Private.CoreLib/shared/System/Collections/IDictionary.cs index b934c2399cf..b077c919275 100644 --- a/src/System.Private.CoreLib/shared/System/Collections/IDictionary.cs +++ b/src/System.Private.CoreLib/shared/System/Collections/IDictionary.cs @@ -15,7 +15,7 @@ public interface IDictionary : ICollection // Interfaces are not serializable // The Item property provides methods to read and edit entries // in the Dictionary. - Object this[Object key] + object this[object key] { get; set; @@ -35,11 +35,11 @@ ICollection Values // Returns whether this dictionary contains a particular key. // - bool Contains(Object key); + bool Contains(object key); // Adds a key-value pair to the dictionary. // - void Add(Object key, Object value); + void Add(object key, object value); // Removes all pairs from the dictionary. void Clear(); @@ -55,6 +55,6 @@ bool IsFixedSize // Removes a particular key from the dictionary. // - void Remove(Object key); + void Remove(object key); } } diff --git a/src/System.Private.CoreLib/shared/System/Collections/IDictionaryEnumerator.cs b/src/System.Private.CoreLib/shared/System/Collections/IDictionaryEnumerator.cs index 451cf68976e..0cf6aaa1545 100644 --- a/src/System.Private.CoreLib/shared/System/Collections/IDictionaryEnumerator.cs +++ b/src/System.Private.CoreLib/shared/System/Collections/IDictionaryEnumerator.cs @@ -39,7 +39,7 @@ public interface IDictionaryEnumerator : IEnumerator // GetKey with no intervening calls to GetNext will return // the same object. // - Object Key + object Key { get; } @@ -50,7 +50,7 @@ Object Key // to GetValue with no intervening calls to GetNext will // return the same object. // - Object Value + object Value { get; } diff --git a/src/System.Private.CoreLib/shared/System/Collections/IEnumerator.cs b/src/System.Private.CoreLib/shared/System/Collections/IEnumerator.cs index 2c2c2e4a97d..29a6f475bfe 100644 --- a/src/System.Private.CoreLib/shared/System/Collections/IEnumerator.cs +++ b/src/System.Private.CoreLib/shared/System/Collections/IEnumerator.cs @@ -25,7 +25,7 @@ public interface IEnumerator // GetCurrent with no intervening calls to MoveNext // will return the same object. // - Object Current + object Current { get; } diff --git a/src/System.Private.CoreLib/shared/System/Collections/IEqualityComparer.cs b/src/System.Private.CoreLib/shared/System/Collections/IEqualityComparer.cs index 35513f577d8..9b5476896ce 100644 --- a/src/System.Private.CoreLib/shared/System/Collections/IEqualityComparer.cs +++ b/src/System.Private.CoreLib/shared/System/Collections/IEqualityComparer.cs @@ -10,7 +10,7 @@ namespace System.Collections // that can be consumed by some of the common collections. public interface IEqualityComparer { - bool Equals(Object x, Object y); - int GetHashCode(Object obj); + bool Equals(object x, object y); + int GetHashCode(object obj); } } diff --git a/src/System.Private.CoreLib/shared/System/Collections/IList.cs b/src/System.Private.CoreLib/shared/System/Collections/IList.cs index 0110eca1f5e..25d3b192269 100644 --- a/src/System.Private.CoreLib/shared/System/Collections/IList.cs +++ b/src/System.Private.CoreLib/shared/System/Collections/IList.cs @@ -12,7 +12,7 @@ namespace System.Collections 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; @@ -22,10 +22,10 @@ public interface IList : ICollection // 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); + int Add(object value); // Returns whether the list contains a particular item. - bool Contains(Object value); + bool Contains(object value); // Removes all items from the list. void Clear(); @@ -42,16 +42,16 @@ bool IsFixedSize // 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); + 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); + void Insert(int index, object value); // Removes an item from the list. - void Remove(Object value); + void Remove(object value); // Removes the item at position index. void RemoveAt(int index); diff --git a/src/System.Private.CoreLib/shared/System/Collections/IStructuralComparable.cs b/src/System.Private.CoreLib/shared/System/Collections/IStructuralComparable.cs index a5e4834b9bb..9041e0d5ff2 100644 --- a/src/System.Private.CoreLib/shared/System/Collections/IStructuralComparable.cs +++ b/src/System.Private.CoreLib/shared/System/Collections/IStructuralComparable.cs @@ -8,6 +8,6 @@ namespace System.Collections { public interface IStructuralComparable { - Int32 CompareTo(Object other, IComparer comparer); + int CompareTo(object other, IComparer comparer); } } diff --git a/src/System.Private.CoreLib/shared/System/Collections/IStructuralEquatable.cs b/src/System.Private.CoreLib/shared/System/Collections/IStructuralEquatable.cs index 4e61d5e75f6..1784da58cb0 100644 --- a/src/System.Private.CoreLib/shared/System/Collections/IStructuralEquatable.cs +++ b/src/System.Private.CoreLib/shared/System/Collections/IStructuralEquatable.cs @@ -6,7 +6,7 @@ namespace System.Collections { public interface IStructuralEquatable { - Boolean Equals(Object other, IEqualityComparer comparer); + bool Equals(object other, IEqualityComparer comparer); int GetHashCode(IEqualityComparer comparer); } } diff --git a/src/System.Private.CoreLib/shared/System/Collections/ListDictionaryInternal.cs b/src/System.Private.CoreLib/shared/System/Collections/ListDictionaryInternal.cs index eccb9f03470..6045778abfe 100644 --- a/src/System.Private.CoreLib/shared/System/Collections/ListDictionaryInternal.cs +++ b/src/System.Private.CoreLib/shared/System/Collections/ListDictionaryInternal.cs @@ -27,13 +27,13 @@ public class ListDictionaryInternal : IDictionary private int version; // Do not rename (binary serialization) private int count; // Do not rename (binary serialization) [NonSerialized] - private Object _syncRoot; + private object _syncRoot; public ListDictionaryInternal() { } - public Object this[Object key] + public object this[object key] { get { @@ -134,13 +134,13 @@ public bool IsSynchronized } } - public Object SyncRoot + public object SyncRoot { get { if (_syncRoot == null) { - System.Threading.Interlocked.CompareExchange(ref _syncRoot, new Object(), null); + System.Threading.Interlocked.CompareExchange(ref _syncRoot, new object(), null); } return _syncRoot; } @@ -154,7 +154,7 @@ public ICollection Values } } - public void Add(Object key, Object value) + public void Add(object key, object value) { if (key == null) { @@ -201,7 +201,7 @@ public void Clear() version++; } - public bool Contains(Object key) + public bool Contains(object key) { if (key == null) { @@ -248,7 +248,7 @@ IEnumerator IEnumerable.GetEnumerator() return new NodeEnumerator(this); } - public void Remove(Object key) + public void Remove(object key) { if (key == null) { @@ -296,7 +296,7 @@ public NodeEnumerator(ListDictionaryInternal list) current = null; } - public Object Current + public object Current { get { @@ -316,7 +316,7 @@ public DictionaryEntry Entry } } - public Object Key + public object Key { get { @@ -328,7 +328,7 @@ public Object Key } } - public Object Value + public object Value { get { @@ -422,7 +422,7 @@ bool ICollection.IsSynchronized } } - Object ICollection.SyncRoot + object ICollection.SyncRoot { get { @@ -453,7 +453,7 @@ public NodeKeyValueEnumerator(ListDictionaryInternal list, bool isKeys) current = null; } - public Object Current + public object Current { get { @@ -501,8 +501,8 @@ public void Reset() [Serializable] private class DictionaryNode { - public Object key; - public Object value; + public object key; + public object value; public DictionaryNode next; } } diff --git a/src/System.Private.CoreLib/shared/System/Collections/ObjectModel/Collection.cs b/src/System.Private.CoreLib/shared/System/Collections/ObjectModel/Collection.cs index 1e1b2c7959b..53272b386a4 100644 --- a/src/System.Private.CoreLib/shared/System/Collections/ObjectModel/Collection.cs +++ b/src/System.Private.CoreLib/shared/System/Collections/ObjectModel/Collection.cs @@ -15,7 +15,7 @@ public class Collection : IList, IList, IReadOnlyList { private IList items; // Do not rename (binary serialization) [NonSerialized] - private Object _syncRoot; + private object _syncRoot; public Collection() { @@ -195,7 +195,7 @@ object ICollection.SyncRoot } else { - System.Threading.Interlocked.CompareExchange(ref _syncRoot, new Object(), null); + System.Threading.Interlocked.CompareExchange(ref _syncRoot, new object(), null); } } return _syncRoot; diff --git a/src/System.Private.CoreLib/shared/System/Collections/ObjectModel/ReadOnlyCollection.cs b/src/System.Private.CoreLib/shared/System/Collections/ObjectModel/ReadOnlyCollection.cs index dbf88d8b8d8..3c4eda20484 100644 --- a/src/System.Private.CoreLib/shared/System/Collections/ObjectModel/ReadOnlyCollection.cs +++ b/src/System.Private.CoreLib/shared/System/Collections/ObjectModel/ReadOnlyCollection.cs @@ -15,7 +15,7 @@ public class ReadOnlyCollection : IList, IList, IReadOnlyList { private IList list; // Do not rename (binary serialization) [NonSerialized] - private Object _syncRoot; + private object _syncRoot; public ReadOnlyCollection(IList list) { @@ -127,7 +127,7 @@ object ICollection.SyncRoot } else { - System.Threading.Interlocked.CompareExchange(ref _syncRoot, new Object(), null); + System.Threading.Interlocked.CompareExchange(ref _syncRoot, new object(), null); } } return _syncRoot; diff --git a/src/System.Private.CoreLib/shared/System/Convert.cs b/src/System.Private.CoreLib/shared/System/Convert.cs index c72b5401c7a..1c303d24810 100644 --- a/src/System.Private.CoreLib/shared/System/Convert.cs +++ b/src/System.Private.CoreLib/shared/System/Convert.cs @@ -100,27 +100,27 @@ public static partial 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. + //will give you the type of an short. internal static readonly Type[] ConvertTypes = { typeof(System.Empty), - typeof(Object), + typeof(object), typeof(System.DBNull), - typeof(Boolean), - typeof(Char), - typeof(SByte), - typeof(Byte), - typeof(Int16), - typeof(UInt16), - typeof(Int32), - typeof(UInt32), - typeof(Int64), - typeof(UInt64), - typeof(Single), - typeof(Double), - typeof(Decimal), + typeof(bool), + typeof(char), + typeof(sbyte), + typeof(byte), + typeof(short), + typeof(ushort), + typeof(int), + typeof(uint), + typeof(long), + typeof(ulong), + typeof(float), + typeof(double), + typeof(decimal), typeof(DateTime), - typeof(Object), //TypeCode is discontinuous so we need a placeholder. - typeof(String) + typeof(object), //TypeCode is discontinuous so we need a placeholder. + typeof(string) }; // Need to special case Enum because typecode will be underlying type, e.g. Int32 @@ -132,7 +132,7 @@ public static partial class Convert 't','u','v','w','x','y','z','0','1','2','3','4','5','6','7', '8','9','+','/','=' }; - private const Int32 base64LineBreakPosition = 76; + private const int base64LineBreakPosition = 76; #if DEBUG private static bool TriggerAsserts = DoAsserts(); @@ -142,7 +142,7 @@ private static bool DoAsserts() Debug.Assert(ConvertTypes.Length == ((int)TypeCode.String + 1), "[Convert.cctor]ConvertTypes.Length == ((int)TypeCode.String + 1)"); Debug.Assert(ConvertTypes[(int)TypeCode.Empty] == typeof(System.Empty), "[Convert.cctor]ConvertTypes[(int)TypeCode.Empty]==typeof(System.Empty)"); - Debug.Assert(ConvertTypes[(int)TypeCode.String] == typeof(String), + Debug.Assert(ConvertTypes[(int)TypeCode.String] == typeof(string), "[Convert.cctor]ConvertTypes[(int)TypeCode.String]==typeof(System.String)"); Debug.Assert(ConvertTypes[(int)TypeCode.Int32] == typeof(int), "[Convert.cctor]ConvertTypes[(int)TypeCode.Int32]==typeof(int)"); @@ -150,7 +150,7 @@ private static bool DoAsserts() } #endif - public static readonly Object DBNull = System.DBNull.Value; + public static readonly object DBNull = System.DBNull.Value; // Returns the type code for the given object. If the argument is null, // the result is TypeCode.Empty. If the argument is not a value (i.e. if @@ -189,12 +189,12 @@ public static bool IsDBNull(object value) // 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, CultureInfo.CurrentCulture); } - public static Object ChangeType(Object value, TypeCode typeCode, IFormatProvider provider) + public static object ChangeType(object value, TypeCode typeCode, IFormatProvider provider) { if (value == null && (typeCode == TypeCode.Empty || typeCode == TypeCode.String || typeCode == TypeCode.Object)) { @@ -208,7 +208,7 @@ public static Object ChangeType(Object value, TypeCode typeCode, IFormatProvider } // 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. + // of int, but the object can't actually be cast to an int. // if (v.GetTypeCode() == typeCode) return value; switch (typeCode) { @@ -253,7 +253,7 @@ public static Object ChangeType(Object value, TypeCode typeCode, IFormatProvider } } - internal static Object DefaultToType(IConvertible value, Type targetType, IFormatProvider provider) + internal static object DefaultToType(IConvertible value, Type targetType, IFormatProvider provider) { Debug.Assert(value != null, "[Convert.DefaultToType]value!=null"); if (targetType == null) @@ -297,7 +297,7 @@ internal static Object DefaultToType(IConvertible value, Type targetType, IForma if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.String])) return value.ToString(provider); if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.Object])) - return (Object)value; + return (object)value; // Need to special case Enum because typecode will be underlying type, e.g. Int32 if (ReferenceEquals(targetType, EnumType)) return (Enum)value; @@ -309,12 +309,12 @@ internal static Object DefaultToType(IConvertible value, Type targetType, IForma throw new InvalidCastException(string.Format(SR.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, CultureInfo.CurrentCulture); } - public static Object ChangeType(Object value, Type conversionType, IFormatProvider provider) + public static object ChangeType(object value, Type conversionType, IFormatProvider provider) { if (conversionType is null) { @@ -371,7 +371,7 @@ public static Object ChangeType(Object value, Type conversionType, IFormatProvid if (ReferenceEquals(conversionType, ConvertTypes[(int)TypeCode.String])) return ic.ToString(provider); if (ReferenceEquals(conversionType, ConvertTypes[(int)TypeCode.Object])) - return (Object)value; + return (object)value; return ic.ToType(conversionType, provider); } @@ -395,12 +395,12 @@ public static Object ChangeType(Object value, Type conversionType, IFormatProvid private static void ThrowUInt64OverflowException() { throw new OverflowException(SR.Overflow_UInt64); } // Conversions to Boolean - public static bool ToBoolean(Object value) + public static bool ToBoolean(object value) { return value == null ? false : ((IConvertible)value).ToBoolean(null); } - public static bool ToBoolean(Object value, IFormatProvider provider) + public static bool ToBoolean(object value, IFormatProvider provider) { return value == null ? false : ((IConvertible)value).ToBoolean(provider); } @@ -463,18 +463,18 @@ 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); + return bool.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); + return bool.Parse(value); } public static bool ToBoolean(float value) @@ -549,27 +549,27 @@ public static char ToChar(ushort value) public static char ToChar(int value) { - if (value < 0 || value > Char.MaxValue) ThrowCharOverflowException(); + if (value < 0 || value > char.MaxValue) ThrowCharOverflowException(); return (char)value; } [CLSCompliant(false)] public static char ToChar(uint value) { - if (value > Char.MaxValue) ThrowCharOverflowException(); + if (value > char.MaxValue) ThrowCharOverflowException(); return (char)value; } public static char ToChar(long value) { - if (value < 0 || value > Char.MaxValue) ThrowCharOverflowException(); + if (value < 0 || value > char.MaxValue) ThrowCharOverflowException(); return (char)value; } [CLSCompliant(false)] public static char ToChar(ulong value) { - if (value > Char.MaxValue) ThrowCharOverflowException(); + if (value > char.MaxValue) ThrowCharOverflowException(); return (char)value; } @@ -577,12 +577,12 @@ public static char ToChar(ulong value) // @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) + public static char ToChar(string value, IFormatProvider provider) { if (value == null) throw new ArgumentNullException(nameof(value)); @@ -640,7 +640,7 @@ public static sbyte ToSByte(object value, IFormatProvider provider) [CLSCompliant(false)] public static sbyte ToSByte(bool value) { - return value ? (sbyte)Boolean.True : (sbyte)Boolean.False; + return value ? (sbyte)bool.True : (sbyte)bool.False; } [CLSCompliant(false)] @@ -652,56 +652,56 @@ public static sbyte ToSByte(sbyte value) [CLSCompliant(false)] public static sbyte ToSByte(char value) { - if (value > SByte.MaxValue) ThrowSByteOverflowException(); + if (value > sbyte.MaxValue) ThrowSByteOverflowException(); return (sbyte)value; } [CLSCompliant(false)] public static sbyte ToSByte(byte value) { - if (value > SByte.MaxValue) ThrowSByteOverflowException(); + if (value > sbyte.MaxValue) ThrowSByteOverflowException(); return (sbyte)value; } [CLSCompliant(false)] public static sbyte ToSByte(short value) { - if (value < SByte.MinValue || value > SByte.MaxValue) ThrowSByteOverflowException(); + if (value < sbyte.MinValue || value > sbyte.MaxValue) ThrowSByteOverflowException(); return (sbyte)value; } [CLSCompliant(false)] public static sbyte ToSByte(ushort value) { - if (value > SByte.MaxValue) ThrowSByteOverflowException(); + if (value > sbyte.MaxValue) ThrowSByteOverflowException(); return (sbyte)value; } [CLSCompliant(false)] public static sbyte ToSByte(int value) { - if (value < SByte.MinValue || value > SByte.MaxValue) ThrowSByteOverflowException(); + if (value < sbyte.MinValue || value > sbyte.MaxValue) ThrowSByteOverflowException(); return (sbyte)value; } [CLSCompliant(false)] public static sbyte ToSByte(uint value) { - if (value > SByte.MaxValue) ThrowSByteOverflowException(); + if (value > sbyte.MaxValue) ThrowSByteOverflowException(); return (sbyte)value; } [CLSCompliant(false)] public static sbyte ToSByte(long value) { - if (value < SByte.MinValue || value > SByte.MaxValue) ThrowSByteOverflowException(); + if (value < sbyte.MinValue || value > sbyte.MaxValue) ThrowSByteOverflowException(); return (sbyte)value; } [CLSCompliant(false)] public static sbyte ToSByte(ulong value) { - if (value > (ulong)SByte.MaxValue) ThrowSByteOverflowException(); + if (value > (ulong)sbyte.MaxValue) ThrowSByteOverflowException(); return (sbyte)value; } @@ -720,21 +720,21 @@ public static sbyte ToSByte(double value) [CLSCompliant(false)] public static sbyte ToSByte(decimal value) { - return Decimal.ToSByte(Decimal.Round(value, 0)); + 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); + 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); + return sbyte.Parse(value, NumberStyles.Integer, provider); } [CLSCompliant(false)] @@ -760,7 +760,7 @@ public static byte ToByte(object value, IFormatProvider provider) public static byte ToByte(bool value) { - return value ? (byte)Boolean.True : (byte)Boolean.False; + return value ? (byte)bool.True : (byte)bool.False; } public static byte ToByte(byte value) @@ -770,53 +770,53 @@ public static byte ToByte(byte value) public static byte ToByte(char value) { - if (value > Byte.MaxValue) ThrowByteOverflowException(); + if (value > byte.MaxValue) ThrowByteOverflowException(); return (byte)value; } [CLSCompliant(false)] public static byte ToByte(sbyte value) { - if (value < Byte.MinValue) ThrowByteOverflowException(); + if (value < byte.MinValue) ThrowByteOverflowException(); return (byte)value; } public static byte ToByte(short value) { - if (value < Byte.MinValue || value > Byte.MaxValue) ThrowByteOverflowException(); + if (value < byte.MinValue || value > byte.MaxValue) ThrowByteOverflowException(); return (byte)value; } [CLSCompliant(false)] public static byte ToByte(ushort value) { - if (value > Byte.MaxValue) ThrowByteOverflowException(); + if (value > byte.MaxValue) ThrowByteOverflowException(); return (byte)value; } public static byte ToByte(int value) { - if (value < Byte.MinValue || value > Byte.MaxValue) ThrowByteOverflowException(); + if (value < byte.MinValue || value > byte.MaxValue) ThrowByteOverflowException(); return (byte)value; } [CLSCompliant(false)] public static byte ToByte(uint value) { - if (value > Byte.MaxValue) ThrowByteOverflowException(); + if (value > byte.MaxValue) ThrowByteOverflowException(); return (byte)value; } public static byte ToByte(long value) { - if (value < Byte.MinValue || value > Byte.MaxValue) ThrowByteOverflowException(); + if (value < byte.MinValue || value > byte.MaxValue) ThrowByteOverflowException(); return (byte)value; } [CLSCompliant(false)] public static byte ToByte(ulong value) { - if (value > Byte.MaxValue) ThrowByteOverflowException(); + if (value > byte.MaxValue) ThrowByteOverflowException(); return (byte)value; } @@ -832,21 +832,21 @@ public static byte ToByte(double value) public static byte ToByte(decimal value) { - return Decimal.ToByte(Decimal.Round(value, 0)); + 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); + 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); + return byte.Parse(value, NumberStyles.Integer, provider); } public static byte ToByte(DateTime value) @@ -872,12 +872,12 @@ public static short ToInt16(object value, IFormatProvider provider) public static short ToInt16(bool value) { - return value ? (short)Boolean.True : (short)Boolean.False; + return value ? (short)bool.True : (short)bool.False; } public static short ToInt16(char value) { - if (value > Int16.MaxValue) ThrowInt16OverflowException(); + if (value > short.MaxValue) ThrowInt16OverflowException(); return (short)value; } @@ -895,20 +895,20 @@ public static short ToInt16(byte value) [CLSCompliant(false)] public static short ToInt16(ushort value) { - if (value > Int16.MaxValue) ThrowInt16OverflowException(); + if (value > short.MaxValue) ThrowInt16OverflowException(); return (short)value; } public static short ToInt16(int value) { - if (value < Int16.MinValue || value > Int16.MaxValue) ThrowInt16OverflowException(); + if (value < short.MinValue || value > short.MaxValue) ThrowInt16OverflowException(); return (short)value; } [CLSCompliant(false)] public static short ToInt16(uint value) { - if (value > Int16.MaxValue) ThrowInt16OverflowException(); + if (value > short.MaxValue) ThrowInt16OverflowException(); return (short)value; } @@ -919,14 +919,14 @@ public static short ToInt16(short value) public static short ToInt16(long value) { - if (value < Int16.MinValue || value > Int16.MaxValue) ThrowInt16OverflowException(); + if (value < short.MinValue || value > short.MaxValue) ThrowInt16OverflowException(); return (short)value; } [CLSCompliant(false)] public static short ToInt16(ulong value) { - if (value > (ulong)Int16.MaxValue) ThrowInt16OverflowException(); + if (value > (ulong)short.MaxValue) ThrowInt16OverflowException(); return (short)value; } @@ -942,21 +942,21 @@ public static short ToInt16(double value) public static short ToInt16(decimal value) { - return Decimal.ToInt16(Decimal.Round(value, 0)); + 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); + return short.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); + return short.Parse(value, NumberStyles.Integer, provider); } public static short ToInt16(DateTime value) @@ -986,7 +986,7 @@ public static ushort ToUInt16(object value, IFormatProvider provider) [CLSCompliant(false)] public static ushort ToUInt16(bool value) { - return value ? (ushort)Boolean.True : (ushort)Boolean.False; + return value ? (ushort)bool.True : (ushort)bool.False; } [CLSCompliant(false)] @@ -1018,7 +1018,7 @@ public static ushort ToUInt16(short value) [CLSCompliant(false)] public static ushort ToUInt16(int value) { - if (value < 0 || value > UInt16.MaxValue) ThrowUInt16OverflowException(); + if (value < 0 || value > ushort.MaxValue) ThrowUInt16OverflowException(); return (ushort)value; } @@ -1031,7 +1031,7 @@ public static ushort ToUInt16(ushort value) [CLSCompliant(false)] public static ushort ToUInt16(uint value) { - if (value > UInt16.MaxValue) ThrowUInt16OverflowException(); + if (value > ushort.MaxValue) ThrowUInt16OverflowException(); return (ushort)value; } @@ -1039,14 +1039,14 @@ public static ushort ToUInt16(uint value) [CLSCompliant(false)] public static ushort ToUInt16(long value) { - if (value < 0 || value > UInt16.MaxValue) ThrowUInt16OverflowException(); + if (value < 0 || value > ushort.MaxValue) ThrowUInt16OverflowException(); return (ushort)value; } [CLSCompliant(false)] public static ushort ToUInt16(ulong value) { - if (value > UInt16.MaxValue) ThrowUInt16OverflowException(); + if (value > ushort.MaxValue) ThrowUInt16OverflowException(); return (ushort)value; } @@ -1065,23 +1065,23 @@ public static ushort ToUInt16(double value) [CLSCompliant(false)] public static ushort ToUInt16(decimal value) { - return Decimal.ToUInt16(Decimal.Round(value, 0)); + return decimal.ToUInt16(decimal.Round(value, 0)); } [CLSCompliant(false)] - public static ushort ToUInt16(String value) + public static ushort ToUInt16(string value) { if (value == null) return 0; - return UInt16.Parse(value, CultureInfo.CurrentCulture); + return ushort.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); + return ushort.Parse(value, NumberStyles.Integer, provider); } [CLSCompliant(false)] @@ -1108,7 +1108,7 @@ public static int ToInt32(object value, IFormatProvider provider) public static int ToInt32(bool value) { - return value ? Boolean.True : Boolean.False; + return value ? bool.True : bool.False; } public static int ToInt32(char value) @@ -1141,7 +1141,7 @@ public static int ToInt32(ushort value) [CLSCompliant(false)] public static int ToInt32(uint value) { - if (value > Int32.MaxValue) ThrowInt32OverflowException(); + if (value > int.MaxValue) ThrowInt32OverflowException(); return (int)value; } @@ -1152,14 +1152,14 @@ public static int ToInt32(int value) public static int ToInt32(long value) { - if (value < Int32.MinValue || value > Int32.MaxValue) ThrowInt32OverflowException(); + if (value < int.MinValue || value > int.MaxValue) ThrowInt32OverflowException(); return (int)value; } [CLSCompliant(false)] public static int ToInt32(ulong value) { - if (value > Int32.MaxValue) ThrowInt32OverflowException(); + if (value > int.MaxValue) ThrowInt32OverflowException(); return (int)value; } @@ -1195,21 +1195,21 @@ public static int ToInt32(double value) public static int ToInt32(decimal value) { - return Decimal.ToInt32(Decimal.Round(value, 0)); + return decimal.ToInt32(decimal.Round(value, 0)); } - public static int ToInt32(String value) + public static int ToInt32(string value) { if (value == null) return 0; - return Int32.Parse(value, CultureInfo.CurrentCulture); + return int.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); + return int.Parse(value, NumberStyles.Integer, provider); } public static int ToInt32(DateTime value) @@ -1239,7 +1239,7 @@ public static uint ToUInt32(object value, IFormatProvider provider) [CLSCompliant(false)] public static uint ToUInt32(bool value) { - return value ? (uint)Boolean.True : (uint)Boolean.False; + return value ? (uint)bool.True : (uint)bool.False; } [CLSCompliant(false)] @@ -1290,14 +1290,14 @@ public static uint ToUInt32(uint value) [CLSCompliant(false)] public static uint ToUInt32(long value) { - if (value < 0 || value > UInt32.MaxValue) ThrowUInt32OverflowException(); + if (value < 0 || value > uint.MaxValue) ThrowUInt32OverflowException(); return (uint)value; } [CLSCompliant(false)] public static uint ToUInt32(ulong value) { - if (value > UInt32.MaxValue) ThrowUInt32OverflowException(); + if (value > uint.MaxValue) ThrowUInt32OverflowException(); return (uint)value; } @@ -1323,23 +1323,23 @@ public static uint ToUInt32(double value) [CLSCompliant(false)] public static uint ToUInt32(decimal value) { - return Decimal.ToUInt32(Decimal.Round(value, 0)); + return decimal.ToUInt32(decimal.Round(value, 0)); } [CLSCompliant(false)] - public static uint ToUInt32(String value) + public static uint ToUInt32(string value) { if (value == null) return 0; - return UInt32.Parse(value, CultureInfo.CurrentCulture); + return uint.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); + return uint.Parse(value, NumberStyles.Integer, provider); } [CLSCompliant(false)] @@ -1366,7 +1366,7 @@ public static long ToInt64(object value, IFormatProvider provider) public static long ToInt64(bool value) { - return value ? Boolean.True : Boolean.False; + return value ? bool.True : bool.False; } public static long ToInt64(char value) @@ -1410,7 +1410,7 @@ public static long ToInt64(uint value) [CLSCompliant(false)] public static long ToInt64(ulong value) { - if (value > Int64.MaxValue) ThrowInt64OverflowException(); + if (value > long.MaxValue) ThrowInt64OverflowException(); return (long)value; } @@ -1432,21 +1432,21 @@ public static long ToInt64(double value) public static long ToInt64(decimal value) { - return Decimal.ToInt64(Decimal.Round(value, 0)); + return decimal.ToInt64(decimal.Round(value, 0)); } public static long ToInt64(string value) { if (value == null) return 0; - return Int64.Parse(value, CultureInfo.CurrentCulture); + return long.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); + return long.Parse(value, NumberStyles.Integer, provider); } public static long ToInt64(DateTime value) @@ -1474,7 +1474,7 @@ public static ulong ToUInt64(object value, IFormatProvider provider) [CLSCompliant(false)] public static ulong ToUInt64(bool value) { - return value ? (ulong)Boolean.True : (ulong)Boolean.False; + return value ? (ulong)bool.True : (ulong)bool.False; } [CLSCompliant(false)] @@ -1531,7 +1531,7 @@ public static ulong ToUInt64(long value) } [CLSCompliant(false)] - public static ulong ToUInt64(UInt64 value) + public static ulong ToUInt64(ulong value) { return value; } @@ -1551,23 +1551,23 @@ public static ulong ToUInt64(double value) [CLSCompliant(false)] public static ulong ToUInt64(decimal value) { - return Decimal.ToUInt64(Decimal.Round(value, 0)); + return decimal.ToUInt64(decimal.Round(value, 0)); } [CLSCompliant(false)] - public static ulong ToUInt64(String value) + public static ulong ToUInt64(string value) { if (value == null) return 0; - return UInt64.Parse(value, CultureInfo.CurrentCulture); + return ulong.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); + return ulong.Parse(value, NumberStyles.Integer, provider); } [CLSCompliant(false)] @@ -1655,24 +1655,24 @@ 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); + return float.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); + return float.Parse(value, NumberStyles.Float | NumberStyles.AllowThousands, provider); } public static float ToSingle(bool value) { - return value ? Boolean.True : Boolean.False; + return value ? bool.True : bool.False; } public static float ToSingle(DateTime value) @@ -1760,23 +1760,23 @@ 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); + 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); + return double.Parse(value, NumberStyles.Float | NumberStyles.AllowThousands, provider); } public static double ToDouble(bool value) { - return value ? Boolean.True : Boolean.False; + return value ? bool.True : bool.False; } public static double ToDouble(DateTime value) @@ -1858,18 +1858,18 @@ 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); + 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); + return decimal.Parse(value, NumberStyles.Number, provider); } public static decimal ToDecimal(decimal value) @@ -1879,7 +1879,7 @@ public static decimal ToDecimal(decimal value) public static decimal ToDecimal(bool value) { - return value ? Boolean.True : Boolean.False; + return value ? bool.True : bool.False; } public static decimal ToDecimal(DateTime value) @@ -1907,14 +1907,14 @@ 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); @@ -1995,12 +1995,12 @@ public static DateTime ToDateTime(decimal value) // Conversions to String - public static string ToString(Object value) + 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) @@ -2023,7 +2023,7 @@ public static string ToString(bool value, IFormatProvider provider) public static string ToString(char value) { - return Char.ToString(value); + return char.ToString(value); } public static string ToString(char value, IFormatProvider provider) @@ -2144,7 +2144,7 @@ public static string ToString(decimal value) return value.ToString(CultureInfo.CurrentCulture); } - public static string ToString(Decimal value, IFormatProvider provider) + public static string ToString(decimal value, IFormatProvider provider) { return value.ToString(provider); } @@ -2159,12 +2159,12 @@ public static string ToString(DateTime value, IFormatProvider provider) return value.ToString(provider); } - public static String ToString(String value) + public static string ToString(string value) { return value; } - public static String ToString(String value, IFormatProvider provider) + public static string ToString(string value, IFormatProvider provider) { return value; // avoid the null check } @@ -2177,7 +2177,7 @@ public static String ToString(String value, IFormatProvider provider) // 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) + public static byte ToByte(string value, int fromBase) { if (fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16) { @@ -2190,7 +2190,7 @@ public static byte ToByte(String value, int fromBase) } int r = ParseNumbers.StringToInt(value.AsSpan(), fromBase, ParseNumbers.IsTight | ParseNumbers.TreatAsUnsigned); - if (r < Byte.MinValue || r > Byte.MaxValue) + if (r < byte.MinValue || r > byte.MaxValue) ThrowByteOverflowException(); return (byte)r; } @@ -2200,7 +2200,7 @@ public static byte ToByte(String value, int fromBase) // by 0x; any other leading or trailing characters cause an error. // [CLSCompliant(false)] - public static sbyte ToSByte(String value, int fromBase) + public static sbyte ToSByte(string value, int fromBase) { if (fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16) { @@ -2213,10 +2213,10 @@ public static sbyte ToSByte(String value, int fromBase) } int r = ParseNumbers.StringToInt(value.AsSpan(), fromBase, ParseNumbers.IsTight | ParseNumbers.TreatAsI1); - if (fromBase != 10 && r <= Byte.MaxValue) + if (fromBase != 10 && r <= byte.MaxValue) return (sbyte)r; - if (r < SByte.MinValue || r > SByte.MaxValue) + if (r < sbyte.MinValue || r > sbyte.MaxValue) ThrowSByteOverflowException(); return (sbyte)r; } @@ -2225,7 +2225,7 @@ public static sbyte ToSByte(String value, int fromBase) // 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) + public static short ToInt16(string value, int fromBase) { if (fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16) { @@ -2238,10 +2238,10 @@ public static short ToInt16(String value, int fromBase) } int r = ParseNumbers.StringToInt(value.AsSpan(), fromBase, ParseNumbers.IsTight | ParseNumbers.TreatAsI2); - if (fromBase != 10 && r <= UInt16.MaxValue) + if (fromBase != 10 && r <= ushort.MaxValue) return (short)r; - if (r < Int16.MinValue || r > Int16.MaxValue) + if (r < short.MinValue || r > short.MaxValue) ThrowInt16OverflowException(); return (short)r; } @@ -2251,7 +2251,7 @@ public static short ToInt16(String value, int fromBase) // by 0x; any other leading or trailing characters cause an error. // [CLSCompliant(false)] - public static ushort ToUInt16(String value, int fromBase) + public static ushort ToUInt16(string value, int fromBase) { if (fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16) { @@ -2264,7 +2264,7 @@ public static ushort ToUInt16(String value, int fromBase) } int r = ParseNumbers.StringToInt(value.AsSpan(), fromBase, ParseNumbers.IsTight | ParseNumbers.TreatAsUnsigned); - if (r < UInt16.MinValue || r > UInt16.MaxValue) + if (r < ushort.MinValue || r > ushort.MaxValue) ThrowUInt16OverflowException(); return (ushort)r; } @@ -2273,7 +2273,7 @@ public static ushort ToUInt16(String value, int fromBase) // 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) + public static int ToInt32(string value, int fromBase) { if (fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16) { @@ -2289,7 +2289,7 @@ public static int ToInt32(String value, int fromBase) // by 0x; any other leading or trailing characters cause an error. // [CLSCompliant(false)] - public static uint ToUInt32(String value, int fromBase) + public static uint ToUInt32(string value, int fromBase) { if (fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16) { @@ -2304,7 +2304,7 @@ public static uint ToUInt32(String value, int fromBase) // 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) + public static long ToInt64(string value, int fromBase) { if (fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16) { @@ -2320,7 +2320,7 @@ public static long ToInt64(String value, int fromBase) // by 0x; any other leading or trailing characters cause an error. // [CLSCompliant(false)] - public static ulong ToUInt64(String value, int fromBase) + public static ulong ToUInt64(string value, int fromBase) { if (fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16) { @@ -2332,7 +2332,7 @@ public static ulong ToUInt64(String value, int fromBase) } // Convert the byte value to a string in base fromBase - public static String ToString(byte value, int toBase) + public static string ToString(byte value, int toBase) { if (toBase != 2 && toBase != 8 && toBase != 10 && toBase != 16) { @@ -2342,7 +2342,7 @@ public static String ToString(byte value, int toBase) } // Convert the Int16 value to a string in base fromBase - public static String ToString(short value, int toBase) + public static string ToString(short value, int toBase) { if (toBase != 2 && toBase != 8 && toBase != 10 && toBase != 16) { @@ -2352,7 +2352,7 @@ public static String ToString(short value, int toBase) } // Convert the Int32 value to a string in base toBase - public static String ToString(int value, int toBase) + public static string ToString(int value, int toBase) { if (toBase != 2 && toBase != 8 && toBase != 10 && toBase != 16) { @@ -2362,7 +2362,7 @@ public static String ToString(int value, int toBase) } // Convert the Int64 value to a string in base toBase - public static String ToString(long value, int toBase) + public static string ToString(long value, int toBase) { if (toBase != 2 && toBase != 8 && toBase != 10 && toBase != 16) { @@ -2371,7 +2371,7 @@ public static String ToString(long value, int toBase) return ParseNumbers.LongToString(value, toBase, -1, ' ', 0); } - public static String ToBase64String(byte[] inArray) + public static string ToBase64String(byte[] inArray) { if (inArray == null) { @@ -2380,7 +2380,7 @@ public static String ToBase64String(byte[] inArray) return ToBase64String(new ReadOnlySpan(inArray), Base64FormattingOptions.None); } - public static String ToBase64String(byte[] inArray, Base64FormattingOptions options) + public static string ToBase64String(byte[] inArray, Base64FormattingOptions options) { if (inArray == null) { @@ -2389,12 +2389,12 @@ public static String ToBase64String(byte[] inArray, Base64FormattingOptions opti return ToBase64String(new ReadOnlySpan(inArray), 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 String ToBase64String(byte[] inArray, int offset, int length, Base64FormattingOptions options) + public static string ToBase64String(byte[] inArray, int offset, int length, Base64FormattingOptions options) { if (inArray == null) throw new ArgumentNullException(nameof(inArray)); @@ -2620,7 +2620,7 @@ private static int ToBase64_CalculateAndValidateOutputLength(int inputLength, bo /// /// The string to convert /// The array of bytes represented by the specified Base64 string. - 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. @@ -2630,7 +2630,7 @@ public static Byte[] FromBase64String(String s) unsafe { - fixed (Char* sPtr = s) + fixed (char* sPtr = s) { return FromBase64CharPtr(sPtr, s.Length); } @@ -2772,7 +2772,7 @@ private static void CopyToTempBufferWithoutWhiteSpace(ReadOnlySpan chars, /// A position within the input array. /// Number of element to convert. /// The array of bytes represented by the specified Base64 encoding characters. - public static Byte[] FromBase64CharArray(Char[] inArray, Int32 offset, Int32 length) + public static byte[] FromBase64CharArray(char[] inArray, int offset, int length) { if (inArray == null) throw new ArgumentNullException(nameof(inArray)); @@ -2794,7 +2794,7 @@ public static Byte[] FromBase64CharArray(Char[] inArray, Int32 offset, Int32 len unsafe { - fixed (Char* inArrayPtr = &inArray[0]) + fixed (char* inArrayPtr = &inArray[0]) { return FromBase64CharPtr(inArrayPtr + offset, length); } @@ -2810,7 +2810,7 @@ public static Byte[] FromBase64CharArray(Char[] inArray, Int32 offset, Int32 len /// Pointer to the first input char /// Number of input chars /// - private static unsafe Byte[] FromBase64CharPtr(Char* inputPtr, Int32 inputLength) + private static unsafe byte[] FromBase64CharPtr(char* inputPtr, int inputLength) { // The validity of parameters much be checked by callers, thus we are Critical here. @@ -2820,14 +2820,14 @@ private static unsafe Byte[] FromBase64CharPtr(Char* inputPtr, Int32 inputLength // 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') + int lastChar = inputPtr[inputLength - 1]; + if (lastChar != (int)' ' && lastChar != (int)'\n' && lastChar != (int)'\r' && lastChar != (int)'\t') break; inputLength--; } // Compute the output length: - Int32 resultLength = FromBase64_ComputeResultLength(inputPtr, inputLength); + int resultLength = FromBase64_ComputeResultLength(inputPtr, inputLength); Debug.Assert(0 <= resultLength); @@ -2835,7 +2835,7 @@ private static unsafe Byte[] FromBase64CharPtr(Char* inputPtr, Int32 inputLength // 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]; + byte[] decodedBytes = new byte[resultLength]; // Convert Base64 chars into bytes: if (!TryFromBase64Chars(new ReadOnlySpan(inputPtr, inputLength), decodedBytes, out int _)) @@ -2854,20 +2854,20 @@ private static unsafe Byte[] FromBase64CharPtr(Char* inputPtr, Int32 inputLength /// Walk the entire input counting white spaces and padding chars, then compute result length /// based on 3 bytes per 4 chars. /// - private static unsafe Int32 FromBase64_ComputeResultLength(Char* inputPtr, Int32 inputLength) + private static unsafe int FromBase64_ComputeResultLength(char* inputPtr, int inputLength) { - const UInt32 intEq = (UInt32)'='; - const UInt32 intSpace = (UInt32)' '; + const uint intEq = (uint)'='; + const uint intSpace = (uint)' '; Debug.Assert(0 <= inputLength); - Char* inputEndPtr = inputPtr + inputLength; - Int32 usefulInputLength = inputLength; - Int32 padding = 0; + char* inputEndPtr = inputPtr + inputLength; + int usefulInputLength = inputLength; + int padding = 0; while (inputPtr < inputEndPtr) { - UInt32 c = (UInt32)(*inputPtr); + uint c = (uint)(*inputPtr); inputPtr++; // We want to be as fast as possible and filter out spaces with as few comparisons as possible. diff --git a/src/System.Private.CoreLib/shared/System/CurrentSystemTimeZone.cs b/src/System.Private.CoreLib/shared/System/CurrentSystemTimeZone.cs index 062080c2199..0112c81abfa 100644 --- a/src/System.Private.CoreLib/shared/System/CurrentSystemTimeZone.cs +++ b/src/System.Private.CoreLib/shared/System/CurrentSystemTimeZone.cs @@ -30,8 +30,8 @@ internal class CurrentSystemTimeZone : TimeZone // E.g. the offset for PST (Pacific Standard time) should be -8 * 60 * 60 * 1000 * 10000. // (1 millisecond = 10000 ticks) private long m_ticksOffset; - private String m_standardName; - private String m_daylightName; + private string m_standardName; + private string m_daylightName; internal CurrentSystemTimeZone() { @@ -42,7 +42,7 @@ internal CurrentSystemTimeZone() m_daylightName = local.DaylightName; } - public override String StandardName + public override string StandardName { get { @@ -50,7 +50,7 @@ public override String StandardName } } - public override String DaylightName + public override string DaylightName { get { @@ -58,7 +58,7 @@ public override String DaylightName } } - internal long GetUtcOffsetFromUniversalTime(DateTime time, ref Boolean isAmbiguousLocalDst) + internal long GetUtcOffsetFromUniversalTime(DateTime time, ref bool isAmbiguousLocalDst) { // Get the daylight changes for the year of the specified time. TimeSpan offset = new TimeSpan(m_ticksOffset); @@ -89,7 +89,7 @@ internal long GetUtcOffsetFromUniversalTime(DateTime time, ref Boolean isAmbiguo ambiguousEnd = startTime - daylightTime.Delta; } - Boolean isDst = false; + bool isDst = false; if (startTime > endTime) { // In southern hemisphere, the daylight saving time starts later in the year, and ends in the beginning of next year. @@ -122,8 +122,8 @@ public override DateTime ToLocalTime(DateTime time) { return time; } - Boolean isAmbiguousLocalDst = false; - Int64 offset = GetUtcOffsetFromUniversalTime(time, ref isAmbiguousLocalDst); + bool isAmbiguousLocalDst = false; + long offset = GetUtcOffsetFromUniversalTime(time, ref isAmbiguousLocalDst); long tick = time.Ticks + offset; if (tick > DateTime.MaxTicks) { @@ -192,7 +192,7 @@ public override TimeSpan GetUtcOffset(DateTime time) private DaylightTime GetCachedDaylightChanges(int year) { - Object objYear = (Object)year; + object objYear = (object)year; if (!m_CachedDaylightChanges.Contains(objYear)) { diff --git a/src/System.Private.CoreLib/shared/System/DataMisalignedException.cs b/src/System.Private.CoreLib/shared/System/DataMisalignedException.cs index 2a245b6ef78..940407fc579 100644 --- a/src/System.Private.CoreLib/shared/System/DataMisalignedException.cs +++ b/src/System.Private.CoreLib/shared/System/DataMisalignedException.cs @@ -23,13 +23,13 @@ public DataMisalignedException() HResult = HResults.COR_E_DATAMISALIGNED; } - public DataMisalignedException(String message) + public DataMisalignedException(string message) : base(message) { HResult = HResults.COR_E_DATAMISALIGNED; } - public DataMisalignedException(String message, Exception innerException) + public DataMisalignedException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_DATAMISALIGNED; diff --git a/src/System.Private.CoreLib/shared/System/DateTime.cs b/src/System.Private.CoreLib/shared/System/DateTime.cs index 9c3b3989e4a..5b76f609253 100644 --- a/src/System.Private.CoreLib/shared/System/DateTime.cs +++ b/src/System.Private.CoreLib/shared/System/DateTime.cs @@ -115,18 +115,18 @@ namespace System public static readonly DateTime MaxValue = new DateTime(MaxTicks, DateTimeKind.Unspecified); public static readonly DateTime UnixEpoch = new DateTime(UnixEpochTicks, DateTimeKind.Utc); - 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"; // Do not rename (binary serialization) - private const String DateDataField = "dateData"; // Do not rename (binary serialization) + private const ulong TicksMask = 0x3FFFFFFFFFFFFFFF; + private const ulong FlagsMask = 0xC000000000000000; + private const ulong LocalMask = 0x8000000000000000; + private const long TicksCeiling = 0x4000000000000000; + private const ulong KindUnspecified = 0x0000000000000000; + private const ulong KindUtc = 0x4000000000000000; + private const ulong KindLocal = 0x8000000000000000; + private const ulong KindLocalAmbiguousDst = 0xC000000000000000; + private const int KindShift = 62; + + private const string TicksField = "ticks"; // Do not rename (binary serialization) + private const string DateDataField = "dateData"; // Do not rename (binary serialization) // The data is stored as an unsigned 64-bit integer // Bits 01-62: The value of 100-nanosecond ticks where 0 represents 1/1/0001 12:00am, up until the value @@ -136,7 +136,7 @@ namespace System // savings time hour and it is in daylight savings time. This allows distinction of these // otherwise ambiguous local times and prevents data loss when round tripping from Local to // UTC time. - private readonly UInt64 _dateData; + private readonly ulong _dateData; // Constructs a DateTime from a tick count. The ticks // argument specifies the date as the number of 100-nanosecond intervals @@ -146,10 +146,10 @@ public DateTime(long ticks) { if (ticks < MinTicks || ticks > MaxTicks) throw new ArgumentOutOfRangeException(nameof(ticks), SR.ArgumentOutOfRange_DateTimeBadTicks); - _dateData = (UInt64)ticks; + _dateData = (ulong)ticks; } - private DateTime(UInt64 dateData) + private DateTime(ulong dateData) { this._dateData = dateData; } @@ -164,17 +164,17 @@ public DateTime(long ticks, DateTimeKind kind) { throw new ArgumentException(SR.Argument_InvalidDateTimeKind, nameof(kind)); } - _dateData = ((UInt64)ticks | ((UInt64)kind << KindShift)); + _dateData = ((ulong)ticks | ((ulong)kind << KindShift)); } - internal DateTime(long ticks, DateTimeKind kind, Boolean isAmbiguousDst) + internal DateTime(long ticks, DateTimeKind kind, bool isAmbiguousDst) { if (ticks < MinTicks || ticks > MaxTicks) { throw new ArgumentOutOfRangeException(nameof(ticks), SR.ArgumentOutOfRange_DateTimeBadTicks); } Debug.Assert(kind == DateTimeKind.Local, "Internal Constructor is for local times only"); - _dateData = ((UInt64)ticks | (isAmbiguousDst ? KindLocalAmbiguousDst : KindLocal)); + _dateData = ((ulong)ticks | (isAmbiguousDst ? KindLocalAmbiguousDst : KindLocal)); } // Constructs a DateTime from a given year, month, and day. The @@ -182,7 +182,7 @@ internal DateTime(long ticks, DateTimeKind kind, Boolean isAmbiguousDst) // public DateTime(int year, int month, int day) { - _dateData = (UInt64)DateToTicks(year, month, day); + _dateData = (ulong)DateToTicks(year, month, day); } // Constructs a DateTime from a given year, month, and day for @@ -199,7 +199,7 @@ public DateTime(int year, int month, int day, Calendar calendar) // public DateTime(int year, int month, int day, int hour, int minute, int second) { - _dateData = (UInt64)(DateToTicks(year, month, day) + TimeToTicks(hour, minute, second)); + _dateData = (ulong)(DateToTicks(year, month, day) + TimeToTicks(hour, minute, second)); } public DateTime(int year, int month, int day, int hour, int minute, int second, DateTimeKind kind) @@ -208,8 +208,8 @@ public DateTime(int year, int month, int day, int hour, int minute, int second, { throw new ArgumentException(SR.Argument_InvalidDateTimeKind, nameof(kind)); } - Int64 ticks = DateToTicks(year, month, day) + TimeToTicks(hour, minute, second); - _dateData = ((UInt64)ticks | ((UInt64)kind << KindShift)); + long ticks = DateToTicks(year, month, day) + TimeToTicks(hour, minute, second); + _dateData = ((ulong)ticks | ((ulong)kind << KindShift)); } // Constructs a DateTime from a given year, month, day, hour, @@ -219,7 +219,7 @@ public DateTime(int year, int month, int day, int hour, int minute, int second, { if (calendar == null) throw new ArgumentNullException(nameof(calendar)); - _dateData = (UInt64)calendar.ToDateTime(year, month, day, hour, minute, second, 0).Ticks; + _dateData = (ulong)calendar.ToDateTime(year, month, day, hour, minute, second, 0).Ticks; } // Constructs a DateTime from a given year, month, day, hour, @@ -231,11 +231,11 @@ public DateTime(int year, int month, int day, int hour, int minute, int second, { throw new ArgumentOutOfRangeException(nameof(millisecond), SR.Format(SR.ArgumentOutOfRange_Range, 0, MillisPerSecond - 1)); } - Int64 ticks = DateToTicks(year, month, day) + TimeToTicks(hour, minute, second); + long ticks = DateToTicks(year, month, day) + TimeToTicks(hour, minute, second); ticks += millisecond * TicksPerMillisecond; if (ticks < MinTicks || ticks > MaxTicks) throw new ArgumentException(SR.Arg_DateTimeRange); - _dateData = (UInt64)ticks; + _dateData = (ulong)ticks; } public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, DateTimeKind kind) @@ -248,11 +248,11 @@ public DateTime(int year, int month, int day, int hour, int minute, int second, { throw new ArgumentException(SR.Argument_InvalidDateTimeKind, nameof(kind)); } - Int64 ticks = DateToTicks(year, month, day) + TimeToTicks(hour, minute, second); + long ticks = DateToTicks(year, month, day) + TimeToTicks(hour, minute, second); ticks += millisecond * TicksPerMillisecond; if (ticks < MinTicks || ticks > MaxTicks) throw new ArgumentException(SR.Arg_DateTimeRange); - _dateData = ((UInt64)ticks | ((UInt64)kind << KindShift)); + _dateData = ((ulong)ticks | ((ulong)kind << KindShift)); } // Constructs a DateTime from a given year, month, day, hour, @@ -266,11 +266,11 @@ public DateTime(int year, int month, int day, int hour, int minute, int second, { throw new ArgumentOutOfRangeException(nameof(millisecond), SR.Format(SR.ArgumentOutOfRange_Range, 0, MillisPerSecond - 1)); } - Int64 ticks = calendar.ToDateTime(year, month, day, hour, minute, second, 0).Ticks; + long ticks = calendar.ToDateTime(year, month, day, hour, minute, second, 0).Ticks; ticks += millisecond * TicksPerMillisecond; if (ticks < MinTicks || ticks > MaxTicks) throw new ArgumentException(SR.Arg_DateTimeRange); - _dateData = (UInt64)ticks; + _dateData = (ulong)ticks; } public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, Calendar calendar, DateTimeKind kind) @@ -285,11 +285,11 @@ public DateTime(int year, int month, int day, int hour, int minute, int second, { throw new ArgumentException(SR.Argument_InvalidDateTimeKind, nameof(kind)); } - Int64 ticks = calendar.ToDateTime(year, month, day, hour, minute, second, 0).Ticks; + long ticks = calendar.ToDateTime(year, month, day, hour, minute, second, 0).Ticks; ticks += millisecond * TicksPerMillisecond; if (ticks < MinTicks || ticks > MaxTicks) throw new ArgumentException(SR.Arg_DateTimeRange); - _dateData = ((UInt64)ticks | ((UInt64)kind << KindShift)); + _dateData = ((ulong)ticks | ((ulong)kind << KindShift)); } private DateTime(SerializationInfo info, StreamingContext context) @@ -297,10 +297,10 @@ private DateTime(SerializationInfo info, StreamingContext context) if (info == null) throw new ArgumentNullException(nameof(info)); - Boolean foundTicks = false; - Boolean foundDateData = false; - Int64 serializedTicks = 0; - UInt64 serializedDateData = 0; + bool foundTicks = false; + bool foundDateData = false; + long serializedTicks = 0; + ulong serializedDateData = 0; // Get the data @@ -328,13 +328,13 @@ private DateTime(SerializationInfo info, StreamingContext context) } else if (foundTicks) { - _dateData = (UInt64)serializedTicks; + _dateData = (ulong)serializedTicks; } else { throw new SerializationException(SR.Serialization_MissingDateTimeData); } - Int64 ticks = InternalTicks; + long ticks = InternalTicks; if (ticks < MinTicks || ticks > MaxTicks) { throw new SerializationException(SR.Serialization_DateTimeTicksOutOfRange); @@ -343,15 +343,15 @@ private DateTime(SerializationInfo info, StreamingContext context) - internal Int64 InternalTicks + internal long InternalTicks { get { - return (Int64)(_dateData & TicksMask); + return (long)(_dateData & TicksMask); } } - private UInt64 InternalKind + private ulong InternalKind { get { @@ -459,7 +459,7 @@ public DateTime AddMonths(int months) } int days = DaysInMonth(y, m); if (d > days) d = days; - return new DateTime((UInt64)(DateToTicks(y, m, d) + InternalTicks % TicksPerDay) | InternalKind); + return new DateTime((ulong)(DateToTicks(y, m, d) + InternalTicks % TicksPerDay) | InternalKind); } // Returns the DateTime resulting from adding a fractional number of @@ -484,7 +484,7 @@ public DateTime AddTicks(long value) { throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_DateArithmetic); } - return new DateTime((UInt64)(ticks + value) | InternalKind); + return new DateTime((ulong)(ticks + value) | InternalKind); } // Returns the DateTime resulting from adding the given number of @@ -511,8 +511,8 @@ public DateTime AddYears(int value) // public static int Compare(DateTime t1, DateTime t2) { - Int64 ticks1 = t1.InternalTicks; - Int64 ticks2 = t2.InternalTicks; + long ticks1 = t1.InternalTicks; + long ticks2 = t2.InternalTicks; if (ticks1 > ticks2) return 1; if (ticks1 < ticks2) return -1; return 0; @@ -524,7 +524,7 @@ public static int Compare(DateTime t1, DateTime t2) // 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)) @@ -610,7 +610,7 @@ internal static long DoubleDateToTicks(double value) // is equal to the value of this DateTime. Returns false // otherwise. // - public override bool Equals(Object value) + public override bool Equals(object value) { if (value is DateTime) { @@ -633,15 +633,15 @@ public static bool Equals(DateTime t1, DateTime t2) return t1.InternalTicks == t2.InternalTicks; } - public static DateTime FromBinary(Int64 dateData) + public static DateTime FromBinary(long dateData) { - if ((dateData & (unchecked((Int64)LocalMask))) != 0) + if ((dateData & (unchecked((long)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)); + long ticks = dateData & (unchecked((long)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) { @@ -649,8 +649,8 @@ public static DateTime FromBinary(Int64 dateData) } // 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; + bool isAmbiguousLocalDst = false; + long offsetTicks; if (ticks < MinTicks) { offsetTicks = TimeZoneInfo.GetLocalUtcOffset(DateTime.MinValue, TimeZoneInfoOptions.NoThrowOnInvalidTime).Ticks; @@ -664,7 +664,7 @@ public static DateTime FromBinary(Int64 dateData) // 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; + bool isDaylightSavings = false; offsetTicks = TimeZoneInfo.GetUtcOffsetFromUtc(utcDt, TimeZoneInfo.Local, out isDaylightSavings, out isAmbiguousLocalDst).Ticks; } ticks += offsetTicks; @@ -688,12 +688,12 @@ public static DateTime FromBinary(Int64 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(long dateData) { - Int64 ticks = dateData & (Int64)TicksMask; + long ticks = dateData & (long)TicksMask; if (ticks < MinTicks || ticks > MaxTicks) throw new ArgumentException(SR.Argument_DateTimeBadBinaryData, nameof(dateData)); - return new DateTime((UInt64)dateData); + return new DateTime((ulong)dateData); } // Creates a DateTime from a Windows filetime. A Windows filetime is @@ -736,7 +736,7 @@ void ISerializable.GetObjectData(SerializationInfo info, StreamingContext contex info.AddValue(DateDataField, _dateData); } - public Boolean IsDaylightSavingTime() + public bool IsDaylightSavingTime() { if (Kind == DateTimeKind.Utc) { @@ -750,7 +750,7 @@ public static DateTime SpecifyKind(DateTime value, DateTimeKind kind) return new DateTime(value.InternalTicks, kind); } - public Int64 ToBinary() + public long ToBinary() { if (Kind == DateTimeKind.Local) { @@ -765,17 +765,17 @@ public Int64 ToBinary() // end of the maximum range, and values just below minimum value are stored // at the end of the ticks area, just below 2^62. TimeSpan offset = TimeZoneInfo.GetLocalUtcOffset(this, TimeZoneInfoOptions.NoThrowOnInvalidTime); - Int64 ticks = Ticks; - Int64 storedTicks = ticks - offset.Ticks; + long ticks = Ticks; + long storedTicks = ticks - offset.Ticks; if (storedTicks < 0) { storedTicks = TicksCeiling + storedTicks; } - return storedTicks | (unchecked((Int64)LocalMask)); + return storedTicks | (unchecked((long)LocalMask)); } else { - return (Int64)_dateData; + return (long)_dateData; } } @@ -787,8 +787,8 @@ public DateTime Date { get { - Int64 ticks = InternalTicks; - return new DateTime((UInt64)(ticks - ticks % TicksPerDay) | InternalKind); + long ticks = InternalTicks; + return new DateTime((ulong)(ticks - ticks % TicksPerDay) | InternalKind); } } @@ -796,7 +796,7 @@ public DateTime Date // to compute the year, day-of-year, month, or day part. private int GetDatePart(int part) { - Int64 ticks = InternalTicks; + long ticks = InternalTicks; // n = number of days since 1/1/0001 int n = (int)(ticks / TicksPerDay); // y400 = number of whole 400-year periods since 1/1/0001 @@ -846,7 +846,7 @@ private int GetDatePart(int part) // are needed rather than redoing the computations for each. internal void GetDatePart(out int year, out int month, out int day) { - Int64 ticks = InternalTicks; + long ticks = InternalTicks; // n = number of days since 1/1/0001 int n = (int)(ticks / TicksPerDay); // y400 = number of whole 400-year periods since 1/1/0001 @@ -925,7 +925,7 @@ public int DayOfYear // public override int GetHashCode() { - Int64 ticks = InternalTicks; + long ticks = InternalTicks; return unchecked((int)ticks) ^ (int)(ticks >> 32); } @@ -940,7 +940,7 @@ public int Hour } } - internal Boolean IsAmbiguousDaylightSavingTime() + internal bool IsAmbiguousDaylightSavingTime() { return (InternalKind == KindLocalAmbiguousDst); } @@ -1001,8 +1001,8 @@ public static DateTime Now get { DateTime utc = UtcNow; - Boolean isAmbiguousLocalDst = false; - Int64 offset = TimeZoneInfo.GetDateTimeNowUtcOffsetFromUtc(utc, out isAmbiguousLocalDst).Ticks; + bool isAmbiguousLocalDst = false; + long offset = TimeZoneInfo.GetDateTimeNowUtcOffsetFromUtc(utc, out isAmbiguousLocalDst).Ticks; long tick = utc.Ticks + offset; if (tick > DateTime.MaxTicks) { @@ -1089,7 +1089,7 @@ public static bool IsLeapYear(int year) // 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) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return (DateTimeParse.Parse(s, DateTimeFormatInfo.CurrentInfo, DateTimeStyles.None)); @@ -1099,13 +1099,13 @@ public static DateTime Parse(String s) // 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) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return (DateTimeParse.Parse(s, DateTimeFormatInfo.GetInstance(provider), DateTimeStyles.None)); } - public static DateTime Parse(String s, IFormatProvider provider, DateTimeStyles styles) + public static DateTime Parse(string s, IFormatProvider provider, DateTimeStyles styles) { DateTimeFormatInfo.ValidateStyles(styles, nameof(styles)); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); @@ -1122,7 +1122,7 @@ public static DateTime Parse(ReadOnlySpan s, IFormatProvider provider = nu // 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) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); if (format == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.format); @@ -1133,7 +1133,7 @@ public static DateTime ParseExact(String s, String format, IFormatProvider provi // 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)); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); @@ -1147,7 +1147,7 @@ public static DateTime ParseExact(ReadOnlySpan s, ReadOnlySpan forma 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)); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); @@ -1173,7 +1173,7 @@ public DateTime Subtract(TimeSpan value) { throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_DateArithmetic); } - return new DateTime((UInt64)(ticks - valueTicks) | InternalKind); + return new DateTime((ulong)(ticks - valueTicks) | InternalKind); } // This function is duplicated in COMDateTime.cpp @@ -1232,9 +1232,9 @@ internal DateTime ToLocalTime(bool throwOnOverflow) { return this; } - Boolean isDaylightSavings = false; - Boolean isAmbiguousLocalDst = false; - Int64 offset = TimeZoneInfo.GetUtcOffsetFromUtc(this, TimeZoneInfo.Local, out isDaylightSavings, out isAmbiguousLocalDst).Ticks; + bool isDaylightSavings = false; + bool isAmbiguousLocalDst = false; + long offset = TimeZoneInfo.GetUtcOffsetFromUtc(this, TimeZoneInfo.Local, out isDaylightSavings, out isAmbiguousLocalDst).Ticks; long tick = Ticks + offset; if (tick > DateTime.MaxTicks) { @@ -1253,42 +1253,42 @@ internal DateTime ToLocalTime(bool throwOnOverflow) return new DateTime(tick, DateTimeKind.Local, isAmbiguousLocalDst); } - public String ToLongDateString() + public string ToLongDateString() { return DateTimeFormat.Format(this, "D", null); } - public String ToLongTimeString() + public string ToLongTimeString() { return DateTimeFormat.Format(this, "T", null); } - public String ToShortDateString() + public string ToShortDateString() { return DateTimeFormat.Format(this, "d", null); } - public String ToShortTimeString() + public string ToShortTimeString() { return DateTimeFormat.Format(this, "t", null); } - public override String ToString() + public override string ToString() { return DateTimeFormat.Format(this, null, null); } - public String ToString(String format) + public string ToString(string format) { return DateTimeFormat.Format(this, format, null); } - public String ToString(IFormatProvider provider) + public string ToString(IFormatProvider provider) { return DateTimeFormat.Format(this, null, provider); } - public String ToString(String format, IFormatProvider provider) + public string ToString(string format, IFormatProvider provider) { return DateTimeFormat.Format(this, format, provider); } @@ -1301,7 +1301,7 @@ public DateTime ToUniversalTime() return TimeZoneInfo.ConvertTimeToUtc(this, TimeZoneInfoOptions.NoThrowOnInvalidTime); } - public static Boolean TryParse(String s, out DateTime result) + public static bool TryParse(string s, out DateTime result) { if (s == null) { @@ -1316,7 +1316,7 @@ public static bool TryParse(ReadOnlySpan 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 bool TryParse(string s, IFormatProvider provider, DateTimeStyles styles, out DateTime result) { DateTimeFormatInfo.ValidateStyles(styles, nameof(styles)); @@ -1335,7 +1335,7 @@ public static bool TryParse(ReadOnlySpan s, IFormatProvider provider, Date 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 bool TryParseExact(string s, string format, IFormatProvider provider, DateTimeStyles style, out DateTime result) { DateTimeFormatInfo.ValidateStyles(style, nameof(style)); @@ -1354,7 +1354,7 @@ public static bool TryParseExact(ReadOnlySpan s, ReadOnlySpan format 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 bool TryParseExact(string s, string[] formats, IFormatProvider provider, DateTimeStyles style, out DateTime result) { DateTimeFormatInfo.ValidateStyles(style, nameof(style)); @@ -1381,7 +1381,7 @@ public static bool TryParseExact(ReadOnlySpan s, string[] formats, IFormat { throw new ArgumentOutOfRangeException(nameof(t), SR.ArgumentOutOfRange_DateArithmetic); } - return new DateTime((UInt64)(ticks + valueTicks) | d.InternalKind); + return new DateTime((ulong)(ticks + valueTicks) | d.InternalKind); } public static DateTime operator -(DateTime d, TimeSpan t) @@ -1392,7 +1392,7 @@ public static bool TryParseExact(ReadOnlySpan s, string[] formats, IFormat { throw new ArgumentOutOfRangeException(nameof(t), SR.ArgumentOutOfRange_DateArithmetic); } - return new DateTime((UInt64)(ticks - valueTicks) | d.InternalKind); + return new DateTime((ulong)(ticks - valueTicks) | d.InternalKind); } public static TimeSpan operator -(DateTime d1, DateTime d2) @@ -1434,7 +1434,7 @@ public static bool TryParseExact(ReadOnlySpan s, string[] formats, IFormat // Returns a string array containing all of the known date and time options for the // current culture. The strings returned are properly formatted date and // time strings for the current instance of DateTime. - public String[] GetDateTimeFormats() + public string[] GetDateTimeFormats() { return (GetDateTimeFormats(CultureInfo.CurrentCulture)); } @@ -1442,7 +1442,7 @@ public String[] GetDateTimeFormats() // Returns a string array containing all of the known date and time options for the // using the information provided by IFormatProvider. The strings returned are properly formatted date and // time strings for the current instance of DateTime. - public String[] GetDateTimeFormats(IFormatProvider provider) + public string[] GetDateTimeFormats(IFormatProvider provider) { return (DateTimeFormat.GetAllDateTimes(this, DateTimeFormatInfo.GetInstance(provider))); } @@ -1451,7 +1451,7 @@ public String[] GetDateTimeFormats(IFormatProvider provider) // Returns a string array containing all of the date and time options for the // given format format and current culture. The strings returned are properly formatted date and // time strings for the current instance of DateTime. - public String[] GetDateTimeFormats(char format) + public string[] GetDateTimeFormats(char format) { return (GetDateTimeFormats(format, CultureInfo.CurrentCulture)); } @@ -1459,7 +1459,7 @@ public String[] GetDateTimeFormats(char format) // Returns a string array containing all of the date and time options for the // given format format and given culture. The strings returned are properly formatted date and // time strings for the current instance of DateTime. - public String[] GetDateTimeFormats(char format, IFormatProvider provider) + public string[] GetDateTimeFormats(char format, IFormatProvider provider) { return (DateTimeFormat.GetAllDateTimes(this, format, DateTimeFormatInfo.GetInstance(provider))); } @@ -1534,7 +1534,7 @@ float IConvertible.ToSingle(IFormatProvider provider) throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "DateTime", "Double")); } - Decimal IConvertible.ToDecimal(IFormatProvider provider) + decimal IConvertible.ToDecimal(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "DateTime", "Decimal")); } @@ -1544,7 +1544,7 @@ DateTime IConvertible.ToDateTime(IFormatProvider provider) return this; } - Object IConvertible.ToType(Type type, IFormatProvider provider) + object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } @@ -1552,7 +1552,7 @@ Object IConvertible.ToType(Type type, IFormatProvider 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 bool 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) diff --git a/src/System.Private.CoreLib/shared/System/DateTimeOffset.cs b/src/System.Private.CoreLib/shared/System/DateTimeOffset.cs index da5705c8aa9..fd86132a17a 100644 --- a/src/System.Private.CoreLib/shared/System/DateTimeOffset.cs +++ b/src/System.Private.CoreLib/shared/System/DateTimeOffset.cs @@ -34,8 +34,8 @@ namespace System public struct DateTimeOffset : IComparable, IFormattable, IComparable, IEquatable, ISerializable, IDeserializationCallback, ISpanFormattable { // Constants - internal const Int64 MaxOffset = TimeSpan.TicksPerHour * 14; - internal const Int64 MinOffset = -MaxOffset; + internal const long MaxOffset = TimeSpan.TicksPerHour * 14; + internal const long MinOffset = -MaxOffset; private const long UnixEpochSeconds = DateTime.UnixEpochTicks / TimeSpan.TicksPerSecond; // 62,135,596,800 private const long UnixEpochMilliseconds = DateTime.UnixEpochTicks / TimeSpan.TicksPerMillisecond; // 62,135,596,800,000 @@ -50,7 +50,7 @@ public struct DateTimeOffset : IComparable, IFormattable, IComparable input, IFormatProvider for // 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) { if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); if (format == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.format); @@ -654,7 +654,7 @@ public static DateTimeOffset ParseExact(String input, String format, IFormatProv // 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)); if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); @@ -676,7 +676,7 @@ public static DateTimeOffset ParseExact(ReadOnlySpan input, ReadOnlySpan input, out DateTimeOffset result) return parsed; } - public static Boolean TryParse(String input, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result) + public static bool TryParse(string input, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result) { styles = ValidateStyles(styles, nameof(styles)); if (input == null) @@ -812,7 +812,7 @@ public static Boolean TryParse(String input, IFormatProvider formatProvider, Dat TimeSpan offset; DateTime dateResult; - Boolean parsed = DateTimeParse.TryParse(input, + bool parsed = DateTimeParse.TryParse(input, DateTimeFormatInfo.GetInstance(formatProvider), styles, out dateResult, @@ -829,7 +829,7 @@ public static bool TryParse(ReadOnlySpan input, IFormatProvider formatProv return parsed; } - public static Boolean TryParseExact(String input, String format, IFormatProvider formatProvider, DateTimeStyles styles, + public static bool TryParseExact(string input, string format, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result) { styles = ValidateStyles(styles, nameof(styles)); @@ -841,7 +841,7 @@ public static bool TryParse(ReadOnlySpan input, IFormatProvider formatProv TimeSpan offset; DateTime dateResult; - Boolean parsed = DateTimeParse.TryParseExact(input, + bool parsed = DateTimeParse.TryParseExact(input, format, DateTimeFormatInfo.GetInstance(formatProvider), styles, @@ -860,7 +860,7 @@ public static bool TryParse(ReadOnlySpan input, IFormatProvider formatProv return parsed; } - public static Boolean TryParseExact(String input, String[] formats, IFormatProvider formatProvider, DateTimeStyles styles, + public static bool TryParseExact(string input, string[] formats, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result) { styles = ValidateStyles(styles, nameof(styles)); @@ -872,7 +872,7 @@ public static bool TryParse(ReadOnlySpan input, IFormatProvider formatProv TimeSpan offset; DateTime dateResult; - Boolean parsed = DateTimeParse.TryParseExactMultiple(input, + bool parsed = DateTimeParse.TryParseExactMultiple(input, formats, DateTimeFormatInfo.GetInstance(formatProvider), styles, @@ -892,9 +892,9 @@ public static bool TryParse(ReadOnlySpan input, IFormatProvider formatProv } // Ensures the TimeSpan is valid to go in a DateTimeOffset. - private static Int16 ValidateOffset(TimeSpan offset) + private static short ValidateOffset(TimeSpan offset) { - Int64 ticks = offset.Ticks; + long ticks = offset.Ticks; if (ticks % TimeSpan.TicksPerMinute != 0) { throw new ArgumentException(SR.Argument_OffsetPrecision, nameof(offset)); @@ -903,7 +903,7 @@ private static Int16 ValidateOffset(TimeSpan offset) { throw new ArgumentOutOfRangeException(nameof(offset), SR.Argument_OffsetOutOfRange); } - return (Int16)(offset.Ticks / TimeSpan.TicksPerMinute); + return (short)(offset.Ticks / TimeSpan.TicksPerMinute); } // Ensures that the time and offset are in range. @@ -914,8 +914,8 @@ private static DateTime ValidateDate(DateTime dateTime, TimeSpan offset) 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; + // 14 hours and the DateTime instance is more than that distance from the boundaries of long. + long utcTicks = dateTime.Ticks - offset.Ticks; if (utcTicks < DateTime.MinTicks || utcTicks > DateTime.MaxTicks) { throw new ArgumentOutOfRangeException(nameof(offset), SR.Argument_UTCOutOfRange); @@ -925,7 +925,7 @@ private static DateTime ValidateDate(DateTime dateTime, TimeSpan offset) return new DateTime(utcTicks, DateTimeKind.Unspecified); } - private static DateTimeStyles ValidateStyles(DateTimeStyles style, String parameterName) + private static DateTimeStyles ValidateStyles(DateTimeStyles style, string parameterName) { if ((style & DateTimeFormatInfo.InvalidDateTimeStyles) != 0) { diff --git a/src/System.Private.CoreLib/shared/System/Diagnostics/Debug.Unix.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/Debug.Unix.cs index 627ea4ab7ed..86b095e47b0 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/Debug.Unix.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/Debug.Unix.cs @@ -22,11 +22,11 @@ private static void ShowDialog(string stackTrace, string message, string detailM // Fail in order to avoid anyone catching an exception and masking // an assert failure. DebugAssertException ex; - if (message == String.Empty) + if (message == string.Empty) { ex = new DebugAssertException(stackTrace); } - else if (detailMessage == String.Empty) + else if (detailMessage == string.Empty) { ex = new DebugAssertException(message, stackTrace); } diff --git a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventProvider.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventProvider.cs index 7ad7f0ce96b..21c2ea0ab6e 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventProvider.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventProvider.cs @@ -781,10 +781,10 @@ private static unsafe object EncodeObject(ref object data, ref EventData* dataDe *uintptr = (uint)data; dataDescriptor->Ptr = (ulong)uintptr; } - else if (data is UInt64) + else if (data is ulong) { dataDescriptor->Size = (uint)sizeof(ulong); - UInt64* ulongptr = (ulong*)dataBuffer; + ulong* ulongptr = (ulong*)dataBuffer; *ulongptr = (ulong)data; dataDescriptor->Ptr = (ulong)ulongptr; } @@ -1290,7 +1290,7 @@ int IEventProvider.EventActivityIdControl(UnsafeNativeMethods.ManifestEtw.Activi } // Define an EventPipeEvent handle. - unsafe IntPtr IEventProvider.DefineEventHandle(uint eventID, string eventName, Int64 keywords, uint eventVersion, uint level, byte *pMetadata, uint metadataLength) + unsafe IntPtr IEventProvider.DefineEventHandle(uint eventID, string eventName, long keywords, uint eventVersion, uint level, byte *pMetadata, uint metadataLength) { throw new System.NotSupportedException(); } @@ -1331,7 +1331,7 @@ int IEventProvider.EventActivityIdControl(UnsafeNativeMethods.ManifestEtw.Activi } // Define an EventPipeEvent handle. - unsafe IntPtr IEventProvider.DefineEventHandle(uint eventID, string eventName, Int64 keywords, uint eventVersion, uint level, byte *pMetadata, uint metadataLength) + unsafe IntPtr IEventProvider.DefineEventHandle(uint eventID, string eventName, long keywords, uint eventVersion, uint level, byte *pMetadata, uint metadataLength) { return IntPtr.Zero; } diff --git a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventSource.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventSource.cs index 59fb59e862e..f03a55fc102 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventSource.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventSource.cs @@ -626,7 +626,7 @@ private unsafe void DefineEventPipeEvents() uint metadataLength = (metadata != null) ? (uint)metadata.Length : 0; string eventName = m_eventData[i].Name; - Int64 keywords = m_eventData[i].Descriptor.Keywords; + long keywords = m_eventData[i].Descriptor.Keywords; uint eventVersion = m_eventData[i].Descriptor.Version; uint level = m_eventData[i].Descriptor.Level; @@ -4433,7 +4433,7 @@ public Guid RelatedActivityId /// /// Gets the payload for the event. /// - public ReadOnlyCollection Payload { get; internal set; } + public ReadOnlyCollection Payload { get; internal set; } /// /// Gets the payload argument names. @@ -5233,7 +5233,7 @@ public void AddEventParameter(Type type, string name) templates.Append(" length=\"").Append(name).Append("Size\""); } // ETW does not support 64-bit value maps, so we don't specify these as ETW maps - if (type.IsEnum() && Enum.GetUnderlyingType(type) != typeof(UInt64) && Enum.GetUnderlyingType(type) != typeof(Int64)) + if (type.IsEnum() && Enum.GetUnderlyingType(type) != typeof(ulong) && Enum.GetUnderlyingType(type) != typeof(long)) { templates.Append(" map=\"").Append(type.Name).Append("\""); if (mapsTab == null) @@ -5796,7 +5796,7 @@ private string TranslateToManifestConvention(string eventMessage, string evtName int leftBracket = i; i++; int argNum = 0; - while (i < eventMessage.Length && Char.IsDigit(eventMessage[i])) + while (i < eventMessage.Length && char.IsDigit(eventMessage[i])) { argNum = argNum * 10 + eventMessage[i] - '0'; i++; diff --git a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/IEventProvider.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/IEventProvider.cs index d34f80eb513..9bbebc79ed2 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/IEventProvider.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/IEventProvider.cs @@ -38,6 +38,6 @@ internal interface IEventProvider int EventActivityIdControl(UnsafeNativeMethods.ManifestEtw.ActivityControl ControlCode, ref Guid ActivityId); // Define an EventPipeEvent handle. - unsafe IntPtr DefineEventHandle(uint eventID, string eventName, Int64 keywords, uint eventVersion, uint level, byte *pMetadata, uint metadataLength); + unsafe IntPtr DefineEventHandle(uint eventID, string eventName, long keywords, uint eventVersion, uint level, byte *pMetadata, uint metadataLength); } } diff --git a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/PropertyValue.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/PropertyValue.cs index 9ff7e83cb83..daa6d9736a2 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/PropertyValue.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/PropertyValue.cs @@ -40,33 +40,33 @@ namespace System.Diagnostics.Tracing public struct Scalar { [FieldOffset(0)] - public Boolean AsBoolean; + public bool AsBoolean; [FieldOffset(0)] - public Byte AsByte; + public byte AsByte; [FieldOffset(0)] - public SByte AsSByte; + public sbyte AsSByte; [FieldOffset(0)] - public Char AsChar; + public char AsChar; [FieldOffset(0)] - public Int16 AsInt16; + public short AsInt16; [FieldOffset(0)] - public UInt16 AsUInt16; + public ushort AsUInt16; [FieldOffset(0)] - public Int32 AsInt32; + public int AsInt32; [FieldOffset(0)] - public UInt32 AsUInt32; + public uint AsUInt32; [FieldOffset(0)] - public Int64 AsInt64; + public long AsInt64; [FieldOffset(0)] - public UInt64 AsUInt64; + public ulong AsUInt64; [FieldOffset(0)] public IntPtr AsIntPtr; [FieldOffset(0)] public UIntPtr AsUIntPtr; [FieldOffset(0)] - public Single AsSingle; + public float AsSingle; [FieldOffset(0)] - public Double AsDouble; + public double AsDouble; [FieldOffset(0)] public Guid AsGuid; [FieldOffset(0)] @@ -76,7 +76,7 @@ public struct Scalar [FieldOffset(0)] public TimeSpan AsTimeSpan; [FieldOffset(0)] - public Decimal AsDecimal; + public decimal AsDecimal; } // Anything not covered by the Scalar union gets stored in this reference. @@ -98,47 +98,47 @@ private PropertyValue(Scalar scalar, int scalarLength) _scalarLength = scalarLength; } - private PropertyValue(Boolean value) : this(new Scalar() { AsBoolean = value }, sizeof(Boolean)) { } - private PropertyValue(Byte value) : this(new Scalar() { AsByte = value }, sizeof(Byte)) { } - private PropertyValue(SByte value) : this(new Scalar() { AsSByte = value }, sizeof(SByte)) { } - private PropertyValue(Char value) : this(new Scalar() { AsChar = value }, sizeof(Char)) { } - private PropertyValue(Int16 value) : this(new Scalar() { AsInt16 = value }, sizeof(Int16)) { } - private PropertyValue(UInt16 value) : this(new Scalar() { AsUInt16 = value }, sizeof(UInt16)) { } - private PropertyValue(Int32 value) : this(new Scalar() { AsInt32 = value }, sizeof(Int32)) { } - private PropertyValue(UInt32 value) : this(new Scalar() { AsUInt32 = value }, sizeof(UInt32)) { } - private PropertyValue(Int64 value) : this(new Scalar() { AsInt64 = value }, sizeof(Int64)) { } - private PropertyValue(UInt64 value) : this(new Scalar() { AsUInt64 = value }, sizeof(UInt64)) { } + private PropertyValue(bool value) : this(new Scalar() { AsBoolean = value }, sizeof(bool)) { } + private PropertyValue(byte value) : this(new Scalar() { AsByte = value }, sizeof(byte)) { } + private PropertyValue(sbyte value) : this(new Scalar() { AsSByte = value }, sizeof(sbyte)) { } + private PropertyValue(char value) : this(new Scalar() { AsChar = value }, sizeof(char)) { } + private PropertyValue(short value) : this(new Scalar() { AsInt16 = value }, sizeof(short)) { } + private PropertyValue(ushort value) : this(new Scalar() { AsUInt16 = value }, sizeof(ushort)) { } + private PropertyValue(int value) : this(new Scalar() { AsInt32 = value }, sizeof(int)) { } + private PropertyValue(uint value) : this(new Scalar() { AsUInt32 = value }, sizeof(uint)) { } + private PropertyValue(long value) : this(new Scalar() { AsInt64 = value }, sizeof(long)) { } + private PropertyValue(ulong value) : this(new Scalar() { AsUInt64 = value }, sizeof(ulong)) { } private PropertyValue(IntPtr value) : this(new Scalar() { AsIntPtr = value }, sizeof(IntPtr)) { } private PropertyValue(UIntPtr value) : this(new Scalar() { AsUIntPtr = value }, sizeof(UIntPtr)) { } - private PropertyValue(Single value) : this(new Scalar() { AsSingle = value }, sizeof(Single)) { } - private PropertyValue(Double value) : this(new Scalar() { AsDouble = value }, sizeof(Double)) { } + private PropertyValue(float value) : this(new Scalar() { AsSingle = value }, sizeof(float)) { } + private PropertyValue(double value) : this(new Scalar() { AsDouble = value }, sizeof(double)) { } private PropertyValue(Guid value) : this(new Scalar() { AsGuid = value }, sizeof(Guid)) { } private PropertyValue(DateTime value) : this(new Scalar() { AsDateTime = value }, sizeof(DateTime)) { } private PropertyValue(DateTimeOffset value) : this(new Scalar() { AsDateTimeOffset = value }, sizeof(DateTimeOffset)) { } private PropertyValue(TimeSpan value) : this(new Scalar() { AsTimeSpan = value }, sizeof(TimeSpan)) { } - private PropertyValue(Decimal value) : this(new Scalar() { AsDecimal = value }, sizeof(Decimal)) { } + private PropertyValue(decimal value) : this(new Scalar() { AsDecimal = value }, sizeof(decimal)) { } public static Func GetFactory(Type type) { - if (type == typeof(Boolean)) return value => new PropertyValue((Boolean)value); - if (type == typeof(Byte)) return value => new PropertyValue((Byte)value); - if (type == typeof(SByte)) return value => new PropertyValue((SByte)value); - if (type == typeof(Char)) return value => new PropertyValue((Char)value); - if (type == typeof(Int16)) return value => new PropertyValue((Int16)value); - if (type == typeof(UInt16)) return value => new PropertyValue((UInt16)value); - if (type == typeof(Int32)) return value => new PropertyValue((Int32)value); - if (type == typeof(UInt32)) return value => new PropertyValue((UInt32)value); - if (type == typeof(Int64)) return value => new PropertyValue((Int64)value); - if (type == typeof(UInt64)) return value => new PropertyValue((UInt64)value); + if (type == typeof(bool)) return value => new PropertyValue((bool)value); + if (type == typeof(byte)) return value => new PropertyValue((byte)value); + if (type == typeof(sbyte)) return value => new PropertyValue((sbyte)value); + if (type == typeof(char)) return value => new PropertyValue((char)value); + if (type == typeof(short)) return value => new PropertyValue((short)value); + if (type == typeof(ushort)) return value => new PropertyValue((ushort)value); + if (type == typeof(int)) return value => new PropertyValue((int)value); + if (type == typeof(uint)) return value => new PropertyValue((uint)value); + if (type == typeof(long)) return value => new PropertyValue((long)value); + if (type == typeof(ulong)) return value => new PropertyValue((ulong)value); if (type == typeof(IntPtr)) return value => new PropertyValue((IntPtr)value); if (type == typeof(UIntPtr)) return value => new PropertyValue((UIntPtr)value); - if (type == typeof(Single)) return value => new PropertyValue((Single)value); - if (type == typeof(Double)) return value => new PropertyValue((Double)value); + if (type == typeof(float)) return value => new PropertyValue((float)value); + if (type == typeof(double)) return value => new PropertyValue((double)value); if (type == typeof(Guid)) return value => new PropertyValue((Guid)value); if (type == typeof(DateTime)) return value => new PropertyValue((DateTime)value); if (type == typeof(DateTimeOffset)) return value => new PropertyValue((DateTimeOffset)value); if (type == typeof(TimeSpan)) return value => new PropertyValue((TimeSpan)value); - if (type == typeof(Decimal)) return value => new PropertyValue((Decimal)value); + if (type == typeof(decimal)) return value => new PropertyValue((decimal)value); return value => new PropertyValue(value); } @@ -249,25 +249,25 @@ sealed class ReferenceTypeHelper : TypeHelper where TContainer : cla if (type.GetTypeInfo().IsEnum) type = Enum.GetUnderlyingType(type); - if (type == typeof(Boolean)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } - if (type == typeof(Byte)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } - if (type == typeof(SByte)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } - if (type == typeof(Char)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } - if (type == typeof(Int16)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } - if (type == typeof(UInt16)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } - if (type == typeof(Int32)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } - if (type == typeof(UInt32)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } - if (type == typeof(Int64)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } - if (type == typeof(UInt64)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } + if (type == typeof(bool)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } + if (type == typeof(byte)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } + if (type == typeof(sbyte)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } + if (type == typeof(char)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } + if (type == typeof(short)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } + if (type == typeof(ushort)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } + if (type == typeof(int)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } + if (type == typeof(uint)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } + if (type == typeof(long)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } + if (type == typeof(ulong)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } if (type == typeof(IntPtr)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } if (type == typeof(UIntPtr)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } - if (type == typeof(Single)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } - if (type == typeof(Double)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } + if (type == typeof(float)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } + if (type == typeof(double)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } if (type == typeof(Guid)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } if (type == typeof(DateTime)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } if (type == typeof(DateTimeOffset)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } if (type == typeof(TimeSpan)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } - if (type == typeof(Decimal)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } + if (type == typeof(decimal)) { var f = (Func)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } return container => new PropertyValue(property.GetValue(container.ReferenceValue)); } diff --git a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/SimpleTypeInfos.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/SimpleTypeInfos.cs index 001a8e8f056..e0a93747903 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/SimpleTypeInfos.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/SimpleTypeInfos.cs @@ -73,20 +73,20 @@ public override void WriteData(TraceLoggingDataCollector collector, PropertyValu collector.AddScalar(value); } - public static TraceLoggingTypeInfo Boolean() { return new ScalarTypeInfo(typeof(Boolean), Statics.Format8, TraceLoggingDataType.Boolean8); } - public static TraceLoggingTypeInfo Byte() { return new ScalarTypeInfo(typeof(Byte), Statics.Format8, TraceLoggingDataType.UInt8); } - public static TraceLoggingTypeInfo SByte() { return new ScalarTypeInfo(typeof(SByte), Statics.Format8, TraceLoggingDataType.Int8); } - public static TraceLoggingTypeInfo Char() { return new ScalarTypeInfo(typeof(Char), Statics.Format16, TraceLoggingDataType.Char16); } - public static TraceLoggingTypeInfo Int16() { return new ScalarTypeInfo(typeof(Int16), Statics.Format16, TraceLoggingDataType.Int16); } - public static TraceLoggingTypeInfo UInt16() { return new ScalarTypeInfo(typeof(UInt16), Statics.Format16, TraceLoggingDataType.UInt16); } - public static TraceLoggingTypeInfo Int32() { return new ScalarTypeInfo(typeof(Int32), Statics.Format32, TraceLoggingDataType.Int32); } - public static TraceLoggingTypeInfo UInt32() { return new ScalarTypeInfo(typeof(UInt32), Statics.Format32, TraceLoggingDataType.UInt32); } - public static TraceLoggingTypeInfo Int64() { return new ScalarTypeInfo(typeof(Int64), Statics.Format64, TraceLoggingDataType.Int64); } - public static TraceLoggingTypeInfo UInt64() { return new ScalarTypeInfo(typeof(UInt64), Statics.Format64, TraceLoggingDataType.UInt64); } + public static TraceLoggingTypeInfo Boolean() { return new ScalarTypeInfo(typeof(bool), Statics.Format8, TraceLoggingDataType.Boolean8); } + public static TraceLoggingTypeInfo Byte() { return new ScalarTypeInfo(typeof(byte), Statics.Format8, TraceLoggingDataType.UInt8); } + public static TraceLoggingTypeInfo SByte() { return new ScalarTypeInfo(typeof(sbyte), Statics.Format8, TraceLoggingDataType.Int8); } + public static TraceLoggingTypeInfo Char() { return new ScalarTypeInfo(typeof(char), Statics.Format16, TraceLoggingDataType.Char16); } + public static TraceLoggingTypeInfo Int16() { return new ScalarTypeInfo(typeof(short), Statics.Format16, TraceLoggingDataType.Int16); } + public static TraceLoggingTypeInfo UInt16() { return new ScalarTypeInfo(typeof(ushort), Statics.Format16, TraceLoggingDataType.UInt16); } + public static TraceLoggingTypeInfo Int32() { return new ScalarTypeInfo(typeof(int), Statics.Format32, TraceLoggingDataType.Int32); } + public static TraceLoggingTypeInfo UInt32() { return new ScalarTypeInfo(typeof(uint), Statics.Format32, TraceLoggingDataType.UInt32); } + public static TraceLoggingTypeInfo Int64() { return new ScalarTypeInfo(typeof(long), Statics.Format64, TraceLoggingDataType.Int64); } + public static TraceLoggingTypeInfo UInt64() { return new ScalarTypeInfo(typeof(ulong), Statics.Format64, TraceLoggingDataType.UInt64); } public static TraceLoggingTypeInfo IntPtr() { return new ScalarTypeInfo(typeof(IntPtr), Statics.FormatPtr, Statics.IntPtrType); } public static TraceLoggingTypeInfo UIntPtr() { return new ScalarTypeInfo(typeof(UIntPtr), Statics.FormatPtr, Statics.UIntPtrType); } - public static TraceLoggingTypeInfo Single() { return new ScalarTypeInfo(typeof(Single), Statics.Format32, TraceLoggingDataType.Float); } - public static TraceLoggingTypeInfo Double() { return new ScalarTypeInfo(typeof(Double), Statics.Format64, TraceLoggingDataType.Double); } + public static TraceLoggingTypeInfo Single() { return new ScalarTypeInfo(typeof(float), Statics.Format32, TraceLoggingDataType.Float); } + public static TraceLoggingTypeInfo Double() { return new ScalarTypeInfo(typeof(double), Statics.Format64, TraceLoggingDataType.Double); } public static TraceLoggingTypeInfo Guid() { return new ScalarTypeInfo(typeof(Guid), (f, t) => Statics.MakeDataType(TraceLoggingDataType.Guid, f), TraceLoggingDataType.Guid); } } @@ -122,20 +122,20 @@ public override void WriteData(TraceLoggingDataCollector collector, PropertyValu collector.AddArray(value, elementSize); } - public static TraceLoggingTypeInfo Boolean() { return new ScalarArrayTypeInfo(typeof(Boolean[]), Statics.Format8, TraceLoggingDataType.Boolean8, sizeof(Boolean)); } - public static TraceLoggingTypeInfo Byte() { return new ScalarArrayTypeInfo(typeof(Byte[]), Statics.Format8, TraceLoggingDataType.UInt8, sizeof(Byte)); } - public static TraceLoggingTypeInfo SByte() { return new ScalarArrayTypeInfo(typeof(SByte[]), Statics.Format8, TraceLoggingDataType.Int8, sizeof(SByte)); } - public static TraceLoggingTypeInfo Char() { return new ScalarArrayTypeInfo(typeof(Char[]), Statics.Format16, TraceLoggingDataType.Char16, sizeof(Char)); } - public static TraceLoggingTypeInfo Int16() { return new ScalarArrayTypeInfo(typeof(Int16[]), Statics.Format16, TraceLoggingDataType.Int16, sizeof(Int16)); } - public static TraceLoggingTypeInfo UInt16() { return new ScalarArrayTypeInfo(typeof(UInt16[]), Statics.Format16, TraceLoggingDataType.UInt16, sizeof(UInt16)); } - public static TraceLoggingTypeInfo Int32() { return new ScalarArrayTypeInfo(typeof(Int32[]), Statics.Format32, TraceLoggingDataType.Int32, sizeof(Int32)); } - public static TraceLoggingTypeInfo UInt32() { return new ScalarArrayTypeInfo(typeof(UInt32[]), Statics.Format32, TraceLoggingDataType.UInt32, sizeof(UInt32)); } - public static TraceLoggingTypeInfo Int64() { return new ScalarArrayTypeInfo(typeof(Int64[]), Statics.Format64, TraceLoggingDataType.Int64, sizeof(Int64)); } - public static TraceLoggingTypeInfo UInt64() { return new ScalarArrayTypeInfo(typeof(UInt64[]), Statics.Format64, TraceLoggingDataType.UInt64, sizeof(UInt64)); } + public static TraceLoggingTypeInfo Boolean() { return new ScalarArrayTypeInfo(typeof(bool[]), Statics.Format8, TraceLoggingDataType.Boolean8, sizeof(bool)); } + public static TraceLoggingTypeInfo Byte() { return new ScalarArrayTypeInfo(typeof(byte[]), Statics.Format8, TraceLoggingDataType.UInt8, sizeof(byte)); } + public static TraceLoggingTypeInfo SByte() { return new ScalarArrayTypeInfo(typeof(sbyte[]), Statics.Format8, TraceLoggingDataType.Int8, sizeof(sbyte)); } + public static TraceLoggingTypeInfo Char() { return new ScalarArrayTypeInfo(typeof(char[]), Statics.Format16, TraceLoggingDataType.Char16, sizeof(char)); } + public static TraceLoggingTypeInfo Int16() { return new ScalarArrayTypeInfo(typeof(short[]), Statics.Format16, TraceLoggingDataType.Int16, sizeof(short)); } + public static TraceLoggingTypeInfo UInt16() { return new ScalarArrayTypeInfo(typeof(ushort[]), Statics.Format16, TraceLoggingDataType.UInt16, sizeof(ushort)); } + public static TraceLoggingTypeInfo Int32() { return new ScalarArrayTypeInfo(typeof(int[]), Statics.Format32, TraceLoggingDataType.Int32, sizeof(int)); } + public static TraceLoggingTypeInfo UInt32() { return new ScalarArrayTypeInfo(typeof(uint[]), Statics.Format32, TraceLoggingDataType.UInt32, sizeof(uint)); } + public static TraceLoggingTypeInfo Int64() { return new ScalarArrayTypeInfo(typeof(long[]), Statics.Format64, TraceLoggingDataType.Int64, sizeof(long)); } + public static TraceLoggingTypeInfo UInt64() { return new ScalarArrayTypeInfo(typeof(ulong[]), Statics.Format64, TraceLoggingDataType.UInt64, sizeof(ulong)); } public static TraceLoggingTypeInfo IntPtr() { return new ScalarArrayTypeInfo(typeof(IntPtr[]), Statics.FormatPtr, Statics.IntPtrType, System.IntPtr.Size); } public static TraceLoggingTypeInfo UIntPtr() { return new ScalarArrayTypeInfo(typeof(UIntPtr[]), Statics.FormatPtr, Statics.UIntPtrType, System.IntPtr.Size); } - public static TraceLoggingTypeInfo Single() { return new ScalarArrayTypeInfo(typeof(Single[]), Statics.Format32, TraceLoggingDataType.Float, sizeof(Single)); } - public static TraceLoggingTypeInfo Double() { return new ScalarArrayTypeInfo(typeof(Double[]), Statics.Format64, TraceLoggingDataType.Double, sizeof(Double)); } + public static TraceLoggingTypeInfo Single() { return new ScalarArrayTypeInfo(typeof(float[]), Statics.Format32, TraceLoggingDataType.Float, sizeof(float)); } + public static TraceLoggingTypeInfo Double() { return new ScalarArrayTypeInfo(typeof(double[]), Statics.Format64, TraceLoggingDataType.Double, sizeof(double)); } public static unsafe TraceLoggingTypeInfo Guid() { return new ScalarArrayTypeInfo(typeof(Guid), (f, t) => Statics.MakeDataType(TraceLoggingDataType.Guid, f), TraceLoggingDataType.Guid, sizeof(Guid)); } } @@ -243,11 +243,11 @@ public override void WriteData(TraceLoggingDataCollector collector, PropertyValu } /// - /// TraceLogging: Type handler for Decimal. (Note: not full-fidelity, exposed as Double.) + /// TraceLogging: Type handler for decimal. (Note: not full-fidelity, exposed as Double.) /// internal sealed class DecimalTypeInfo : TraceLoggingTypeInfo { - public DecimalTypeInfo() : base(typeof(Decimal)) { } + public DecimalTypeInfo() : base(typeof(decimal)) { } public override void WriteMetadata( TraceLoggingMetadataCollector collector, diff --git a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/Statics.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/Statics.cs index 05539ab4fd6..0c21672131c 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/Statics.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/TraceLogging/Statics.cs @@ -548,51 +548,51 @@ public static Delegate CreateDelegate(Type delegateType, MethodInfo methodInfo) else if (dataType.IsArray) { var elementType = dataType.GetElementType(); - if (elementType == typeof(Boolean)) + if (elementType == typeof(bool)) { result = ScalarArrayTypeInfo.Boolean(); } - else if (elementType == typeof(Byte)) + else if (elementType == typeof(byte)) { result = ScalarArrayTypeInfo.Byte(); } - else if (elementType == typeof(SByte)) + else if (elementType == typeof(sbyte)) { result = ScalarArrayTypeInfo.SByte(); } - else if (elementType == typeof(Int16)) + else if (elementType == typeof(short)) { result = ScalarArrayTypeInfo.Int16(); } - else if (elementType == typeof(UInt16)) + else if (elementType == typeof(ushort)) { result = ScalarArrayTypeInfo.UInt16(); } - else if (elementType == typeof(Int32)) + else if (elementType == typeof(int)) { result = ScalarArrayTypeInfo.Int32(); } - else if (elementType == typeof(UInt32)) + else if (elementType == typeof(uint)) { result = ScalarArrayTypeInfo.UInt32(); } - else if (elementType == typeof(Int64)) + else if (elementType == typeof(long)) { result = ScalarArrayTypeInfo.Int64(); } - else if (elementType == typeof(UInt64)) + else if (elementType == typeof(ulong)) { result = ScalarArrayTypeInfo.UInt64(); } - else if (elementType == typeof(Char)) + else if (elementType == typeof(char)) { result = ScalarArrayTypeInfo.Char(); } - else if (elementType == typeof(Double)) + else if (elementType == typeof(double)) { result = ScalarArrayTypeInfo.Double(); } - else if (elementType == typeof(Single)) + else if (elementType == typeof(float)) { result = ScalarArrayTypeInfo.Single(); } @@ -618,55 +618,55 @@ public static Delegate CreateDelegate(Type delegateType, MethodInfo methodInfo) if (Statics.IsEnum(dataType)) dataType = Enum.GetUnderlyingType(dataType); - if (dataType == typeof(String)) + if (dataType == typeof(string)) { result = new StringTypeInfo(); } - else if (dataType == typeof(Boolean)) + else if (dataType == typeof(bool)) { result = ScalarTypeInfo.Boolean(); } - else if (dataType == typeof(Byte)) + else if (dataType == typeof(byte)) { result = ScalarTypeInfo.Byte(); } - else if (dataType == typeof(SByte)) + else if (dataType == typeof(sbyte)) { result = ScalarTypeInfo.SByte(); } - else if (dataType == typeof(Int16)) + else if (dataType == typeof(short)) { result = ScalarTypeInfo.Int16(); } - else if (dataType == typeof(UInt16)) + else if (dataType == typeof(ushort)) { result = ScalarTypeInfo.UInt16(); } - else if (dataType == typeof(Int32)) + else if (dataType == typeof(int)) { result = ScalarTypeInfo.Int32(); } - else if (dataType == typeof(UInt32)) + else if (dataType == typeof(uint)) { result = ScalarTypeInfo.UInt32(); } - else if (dataType == typeof(Int64)) + else if (dataType == typeof(long)) { result = ScalarTypeInfo.Int64(); } - else if (dataType == typeof(UInt64)) + else if (dataType == typeof(ulong)) { result = ScalarTypeInfo.UInt64(); } - else if (dataType == typeof(Char)) + else if (dataType == typeof(char)) { result = ScalarTypeInfo.Char(); } - else if (dataType == typeof(Double)) + else if (dataType == typeof(double)) { result = ScalarTypeInfo.Double(); } - else if (dataType == typeof(Single)) + else if (dataType == typeof(float)) { result = ScalarTypeInfo.Single(); } @@ -674,7 +674,7 @@ public static Delegate CreateDelegate(Type delegateType, MethodInfo methodInfo) { result = new DateTimeTypeInfo(); } - else if (dataType == typeof(Decimal)) + else if (dataType == typeof(decimal)) { result = new DecimalTypeInfo(); } diff --git a/src/System.Private.CoreLib/shared/System/DivideByZeroException.cs b/src/System.Private.CoreLib/shared/System/DivideByZeroException.cs index b309695ff3f..27f57414ff7 100644 --- a/src/System.Private.CoreLib/shared/System/DivideByZeroException.cs +++ b/src/System.Private.CoreLib/shared/System/DivideByZeroException.cs @@ -25,13 +25,13 @@ public DivideByZeroException() HResult = HResults.COR_E_DIVIDEBYZERO; } - public DivideByZeroException(String message) + public DivideByZeroException(string message) : base(message) { HResult = HResults.COR_E_DIVIDEBYZERO; } - public DivideByZeroException(String message, Exception innerException) + public DivideByZeroException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_DIVIDEBYZERO; diff --git a/src/System.Private.CoreLib/shared/System/DllNotFoundException.cs b/src/System.Private.CoreLib/shared/System/DllNotFoundException.cs index 14fb50d9c51..bd29b8b13a8 100644 --- a/src/System.Private.CoreLib/shared/System/DllNotFoundException.cs +++ b/src/System.Private.CoreLib/shared/System/DllNotFoundException.cs @@ -26,13 +26,13 @@ public DllNotFoundException() HResult = HResults.COR_E_DLLNOTFOUND; } - public DllNotFoundException(String message) + public DllNotFoundException(string message) : base(message) { HResult = HResults.COR_E_DLLNOTFOUND; } - public DllNotFoundException(String message, Exception inner) + public DllNotFoundException(string message, Exception inner) : base(message, inner) { HResult = HResults.COR_E_DLLNOTFOUND; diff --git a/src/System.Private.CoreLib/shared/System/Double.cs b/src/System.Private.CoreLib/shared/System/Double.cs index e4669359536..79021f22b88 100644 --- a/src/System.Private.CoreLib/shared/System/Double.cs +++ b/src/System.Private.CoreLib/shared/System/Double.cs @@ -24,7 +24,7 @@ namespace System [Serializable] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] - public struct Double : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable + public struct Double : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable { private double m_value; // Do not rename (binary serialization) @@ -123,13 +123,13 @@ public static unsafe bool IsSubnormal(double d) // // 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 Double) + if (value is double) { double d = (double)value; if (m_value < d) return -1; @@ -145,7 +145,7 @@ public int CompareTo(Object value) throw new ArgumentException(SR.Arg_MustBeDouble); } - public int CompareTo(Double value) + public int CompareTo(double value) { if (m_value < value) return -1; if (m_value > value) return 1; @@ -160,13 +160,13 @@ public int CompareTo(Double value) // 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) + public override bool Equals(object obj) { - if (!(obj is Double)) + if (!(obj is double)) { return false; } - double temp = ((Double)obj).m_value; + 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) { @@ -176,42 +176,42 @@ public override bool Equals(Object obj) } [NonVersionable] - public static bool operator ==(Double left, Double right) + public static bool operator ==(double left, double right) { return left == right; } [NonVersionable] - public static bool operator !=(Double left, Double right) + public static bool operator !=(double left, double right) { return left != right; } [NonVersionable] - public static bool operator <(Double left, Double right) + public static bool operator <(double left, double right) { return left < right; } [NonVersionable] - public static bool operator >(Double left, Double right) + public static bool operator >(double left, double right) { return left > right; } [NonVersionable] - public static bool operator <=(Double left, Double right) + public static bool operator <=(double left, double right) { return left <= right; } [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) + public bool Equals(double obj) { if (obj == m_value) { @@ -238,22 +238,22 @@ public override int GetHashCode() return unchecked((int)bits) ^ ((int)(bits >> 32)); } - public override String ToString() + public override string ToString() { return Number.FormatDouble(m_value, null, NumberFormatInfo.CurrentInfo); } - public String ToString(String format) + public string ToString(string format) { return Number.FormatDouble(m_value, format, NumberFormatInfo.CurrentInfo); } - public String ToString(IFormatProvider provider) + public string ToString(IFormatProvider provider) { return Number.FormatDouble(m_value, null, NumberFormatInfo.GetInstance(provider)); } - public String ToString(String format, IFormatProvider provider) + public string ToString(string format, IFormatProvider provider) { return Number.FormatDouble(m_value, format, NumberFormatInfo.GetInstance(provider)); } @@ -263,26 +263,26 @@ public bool TryFormat(Span destination, out int charsWritten, ReadOnlySpan return Number.TryFormatDouble(m_value, format, NumberFormatInfo.GetInstance(provider), destination, out charsWritten); } - public static double Parse(String s) + public static double Parse(string s) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseDouble(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo); } - public static double Parse(String s, NumberStyles style) + public static double Parse(string s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseDouble(s, style, NumberFormatInfo.CurrentInfo); } - public static double Parse(String s, IFormatProvider provider) + public static double Parse(string s, IFormatProvider provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseDouble(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.GetInstance(provider)); } - public static double Parse(String s, NumberStyles style, IFormatProvider provider) + public static double Parse(string s, NumberStyles style, IFormatProvider provider) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); @@ -305,7 +305,7 @@ public static double Parse(ReadOnlySpan s, NumberStyles style = NumberStyl - public static bool TryParse(String s, out double result) + public static bool TryParse(string s, out double result) { if (s == null) { @@ -321,7 +321,7 @@ public static bool TryParse(ReadOnlySpan 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); @@ -435,7 +435,7 @@ float IConvertible.ToSingle(IFormatProvider provider) return m_value; } - Decimal IConvertible.ToDecimal(IFormatProvider provider) + decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } @@ -445,7 +445,7 @@ DateTime IConvertible.ToDateTime(IFormatProvider provider) throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Double", "DateTime")); } - 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/System.Private.CoreLib/shared/System/DuplicateWaitObjectException.cs b/src/System.Private.CoreLib/shared/System/DuplicateWaitObjectException.cs index 77303846a37..f48e4be1740 100644 --- a/src/System.Private.CoreLib/shared/System/DuplicateWaitObjectException.cs +++ b/src/System.Private.CoreLib/shared/System/DuplicateWaitObjectException.cs @@ -21,9 +21,9 @@ namespace System [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class DuplicateWaitObjectException : ArgumentException { - private static volatile String s_duplicateWaitObjectMessage = null; + private static volatile string s_duplicateWaitObjectMessage = null; - private static String DuplicateWaitObjectMessage + private static string DuplicateWaitObjectMessage { get { @@ -41,19 +41,19 @@ public DuplicateWaitObjectException() HResult = HResults.COR_E_DUPLICATEWAITOBJECT; } - public DuplicateWaitObjectException(String parameterName) + public DuplicateWaitObjectException(string parameterName) : base(DuplicateWaitObjectMessage, parameterName) { HResult = HResults.COR_E_DUPLICATEWAITOBJECT; } - public DuplicateWaitObjectException(String parameterName, String message) + public DuplicateWaitObjectException(string parameterName, string message) : base(message, parameterName) { HResult = HResults.COR_E_DUPLICATEWAITOBJECT; } - public DuplicateWaitObjectException(String message, Exception innerException) + public DuplicateWaitObjectException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_DUPLICATEWAITOBJECT; diff --git a/src/System.Private.CoreLib/shared/System/EntryPointNotFoundException.cs b/src/System.Private.CoreLib/shared/System/EntryPointNotFoundException.cs index dac1cdb9715..606743aa1e5 100644 --- a/src/System.Private.CoreLib/shared/System/EntryPointNotFoundException.cs +++ b/src/System.Private.CoreLib/shared/System/EntryPointNotFoundException.cs @@ -26,13 +26,13 @@ public EntryPointNotFoundException() HResult = HResults.COR_E_ENTRYPOINTNOTFOUND; } - public EntryPointNotFoundException(String message) + public EntryPointNotFoundException(string message) : base(message) { HResult = HResults.COR_E_ENTRYPOINTNOTFOUND; } - public EntryPointNotFoundException(String message, Exception inner) + public EntryPointNotFoundException(string message, Exception inner) : base(message, inner) { HResult = HResults.COR_E_ENTRYPOINTNOTFOUND; diff --git a/src/System.Private.CoreLib/shared/System/EventHandler.cs b/src/System.Private.CoreLib/shared/System/EventHandler.cs index 3d1cbfef267..c38e17ce6fb 100644 --- a/src/System.Private.CoreLib/shared/System/EventHandler.cs +++ b/src/System.Private.CoreLib/shared/System/EventHandler.cs @@ -6,7 +6,7 @@ namespace System { - public delegate void EventHandler(Object sender, EventArgs e); + public delegate void EventHandler(object sender, EventArgs e); - public delegate void EventHandler(Object sender, TEventArgs e); // Removed TEventArgs constraint post-.NET 4 + public delegate void EventHandler(object sender, TEventArgs e); // Removed TEventArgs constraint post-.NET 4 } diff --git a/src/System.Private.CoreLib/shared/System/ExecutionEngineException.cs b/src/System.Private.CoreLib/shared/System/ExecutionEngineException.cs index 5edd5cf19ff..5649cc082b3 100644 --- a/src/System.Private.CoreLib/shared/System/ExecutionEngineException.cs +++ b/src/System.Private.CoreLib/shared/System/ExecutionEngineException.cs @@ -31,13 +31,13 @@ public ExecutionEngineException() HResult = HResults.COR_E_EXECUTIONENGINE; } - public ExecutionEngineException(String message) + public ExecutionEngineException(string message) : base(message) { HResult = HResults.COR_E_EXECUTIONENGINE; } - public ExecutionEngineException(String message, Exception innerException) + public ExecutionEngineException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_EXECUTIONENGINE; diff --git a/src/System.Private.CoreLib/shared/System/FieldAccessException.cs b/src/System.Private.CoreLib/shared/System/FieldAccessException.cs index cb28264d61b..b23984133c9 100644 --- a/src/System.Private.CoreLib/shared/System/FieldAccessException.cs +++ b/src/System.Private.CoreLib/shared/System/FieldAccessException.cs @@ -23,13 +23,13 @@ public FieldAccessException() HResult = HResults.COR_E_FIELDACCESS; } - public FieldAccessException(String message) + public FieldAccessException(string message) : base(message) { HResult = HResults.COR_E_FIELDACCESS; } - public FieldAccessException(String message, Exception inner) + public FieldAccessException(string message, Exception inner) : base(message, inner) { HResult = HResults.COR_E_FIELDACCESS; diff --git a/src/System.Private.CoreLib/shared/System/FormatException.cs b/src/System.Private.CoreLib/shared/System/FormatException.cs index b0e273369cd..97d5001f3fd 100644 --- a/src/System.Private.CoreLib/shared/System/FormatException.cs +++ b/src/System.Private.CoreLib/shared/System/FormatException.cs @@ -25,13 +25,13 @@ public FormatException() HResult = HResults.COR_E_FORMAT; } - public FormatException(String message) + public FormatException(string message) : base(message) { HResult = HResults.COR_E_FORMAT; } - public FormatException(String message, Exception innerException) + public FormatException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_FORMAT; diff --git a/src/System.Private.CoreLib/shared/System/Globalization/Calendar.cs b/src/System.Private.CoreLib/shared/System/Globalization/Calendar.cs index d38d0da0ede..66a63694a58 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/Calendar.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/Calendar.cs @@ -736,7 +736,7 @@ public virtual DateTime ToDateTime(int year, int month, int day, int hour, int m 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 bool TryToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era, out DateTime result) { result = DateTime.MinValue; try diff --git a/src/System.Private.CoreLib/shared/System/Globalization/CalendarData.Windows.cs b/src/System.Private.CoreLib/shared/System/Globalization/CalendarData.Windows.cs index 03f9088d62b..de503744121 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/CalendarData.Windows.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/CalendarData.Windows.cs @@ -13,7 +13,7 @@ namespace System.Globalization { internal partial class CalendarData { - private bool LoadCalendarDataFromSystem(String localeName, CalendarId calendarId) + private bool LoadCalendarDataFromSystem(string localeName, CalendarId calendarId) { Debug.Assert(!GlobalizationMode.Invariant); @@ -127,7 +127,7 @@ internal static int GetTwoDigitYearMax(CalendarId calendarId) } // Call native side to figure out which calendars are allowed - internal static int GetCalendars(String localeName, bool useUserOverride, CalendarId[] calendars) + internal static int GetCalendars(string localeName, bool useUserOverride, CalendarId[] calendars) { Debug.Assert(!GlobalizationMode.Invariant); @@ -451,7 +451,7 @@ private static unsafe Interop.BOOL EnumCalendarsCallback(char* lpCalendarInfoStr } } - private static unsafe String GetUserDefaultLocaleName() + private static unsafe string GetUserDefaultLocaleName() { Debug.Assert(!GlobalizationMode.Invariant); @@ -463,7 +463,7 @@ private static unsafe String GetUserDefaultLocaleName() char* localeName = stackalloc char[LOCALE_NAME_MAX_LENGTH]; result = CultureData.GetLocaleInfoEx(LOCALE_NAME_USER_DEFAULT, LOCALE_SNAME, localeName, LOCALE_NAME_MAX_LENGTH); - return result <= 0 ? "" : new String(localeName, 0, result - 1); // exclude the null termination + return result <= 0 ? "" : new string(localeName, 0, result - 1); // exclude the null termination } } } diff --git a/src/System.Private.CoreLib/shared/System/Globalization/CharUnicodeInfo.cs b/src/System.Private.CoreLib/shared/System/Globalization/CharUnicodeInfo.cs index 4acb67e78fa..d8d621cb057 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/CharUnicodeInfo.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/CharUnicodeInfo.cs @@ -43,7 +43,7 @@ public static partial class CharUnicodeInfo // // Actions: // Convert the BMP character or surrogate pointed by index to a UTF32 value. - // This is similar to Char.ConvertToUTF32, but the difference is that + // This is similar to char.ConvertToUTF32, but the difference is that // it does not throw exceptions when invalid surrogate characters are passed in. // // WARNING: since it doesn't throw an exception it CAN return a value @@ -51,7 +51,7 @@ public static partial class CharUnicodeInfo // //////////////////////////////////////////////////////////////////////// - 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"); @@ -115,7 +115,7 @@ internal static int InternalConvertToUtf32(StringBuilder s, int index) // //////////////////////////////////////////////////////////////////////// - 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"); @@ -146,7 +146,7 @@ internal static int InternalConvertToUtf32(String s, int index, out int charLeng // //////////////////////////////////////////////////////////////////////// - internal static bool IsWhiteSpace(String s, int index) + internal static bool IsWhiteSpace(string s, int index) { Debug.Assert(s != null, "s!=null"); Debug.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length"); @@ -246,7 +246,7 @@ public static double GetNumericValue(char ch) } - public static double GetNumericValue(String s, int index) + public static double GetNumericValue(string s, int index) { if (s == null) { @@ -264,7 +264,7 @@ public static int GetDecimalDigitValue(char ch) return (sbyte)(InternalGetDigitValues(ch) >> 8); } - public static int GetDecimalDigitValue(String s, int index) + public static int GetDecimalDigitValue(string s, int index) { if (s == null) { @@ -284,7 +284,7 @@ public static int GetDigitValue(char ch) return (sbyte)(InternalGetDigitValues(ch) & 0x00FF); } - public static int GetDigitValue(String s, int index) + public static int GetDigitValue(string s, int index) { if (s == null) { @@ -304,7 +304,7 @@ public static UnicodeCategory GetUnicodeCategory(char ch) return (GetUnicodeCategory((int)ch)); } - public static UnicodeCategory GetUnicodeCategory(String s, int index) + public static UnicodeCategory GetUnicodeCategory(string s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); @@ -372,7 +372,7 @@ internal static unsafe byte InternalGetCategoryValue(int ch, int offset) // //////////////////////////////////////////////////////////////////////// - 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"); @@ -380,7 +380,7 @@ internal static UnicodeCategory InternalGetUnicodeCategory(String value, int ind return (GetUnicodeCategory(InternalConvertToUtf32(value, index))); } - internal static BidiCategory GetBidiCategory(String s, int index) + internal static BidiCategory GetBidiCategory(string s, int index) { if (s == null) throw new ArgumentNullException(nameof(s)); @@ -408,7 +408,7 @@ internal static BidiCategory GetBidiCategory(StringBuilder s, int index) // //////////////////////////////////////////////////////////////////////// - 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"); ; diff --git a/src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.Unix.cs b/src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.Unix.cs index 25c9d34c33d..2c4684342e4 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.Unix.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.Unix.cs @@ -764,12 +764,12 @@ private static unsafe bool IsSortable(char *text, int length) while (index < length) { - if (Char.IsHighSurrogate(text[index])) + if (char.IsHighSurrogate(text[index])) { - if (index == length - 1 || !Char.IsLowSurrogate(text[index+1])) + if (index == length - 1 || !char.IsLowSurrogate(text[index+1])) return false; // unpaired surrogate - uc = CharUnicodeInfo.GetUnicodeCategory(Char.ConvertToUtf32(text[index], text[index+1])); + uc = CharUnicodeInfo.GetUnicodeCategory(char.ConvertToUtf32(text[index], text[index+1])); if (uc == UnicodeCategory.PrivateUse || uc == UnicodeCategory.OtherNotAssigned) return false; @@ -777,7 +777,7 @@ private static unsafe bool IsSortable(char *text, int length) continue; } - if (Char.IsLowSurrogate(text[index])) + if (char.IsLowSurrogate(text[index])) { return false; // unpaired surrogate } diff --git a/src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.Windows.cs b/src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.Windows.cs index 063095f31ec..2a14e26c510 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.Windows.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.Windows.cs @@ -316,7 +316,7 @@ private unsafe int CompareString(ReadOnlySpan string1, ReadOnlySpan } } - internal unsafe int IndexOfCore(String source, String target, int startIndex, int count, CompareOptions options, int* matchLengthPtr) + internal unsafe int IndexOfCore(string source, string target, int startIndex, int count, CompareOptions options, int* matchLengthPtr) { Debug.Assert(!_invariantMode); @@ -533,7 +533,7 @@ private static unsafe int FastIndexOfString(string source, string target, int st return retValue; } - private unsafe SortKey CreateSortKey(String source, CompareOptions options) + private unsafe SortKey CreateSortKey(string source, CompareOptions options) { Debug.Assert(!_invariantMode); diff --git a/src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.cs b/src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.cs index ef016369a87..74924ee4767 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.cs @@ -107,7 +107,7 @@ public static CompareInfo GetCompareInfo(int culture, Assembly assembly) { throw new ArgumentNullException(nameof(assembly)); } - if (assembly != typeof(Object).Module.Assembly) + if (assembly != typeof(object).Module.Assembly) { throw new ArgumentException(SR.Argument_OnlyMscorlib); } @@ -134,7 +134,7 @@ public static CompareInfo GetCompareInfo(string name, Assembly assembly) throw new ArgumentNullException(name == null ? nameof(name) : nameof(assembly)); } - if (assembly != typeof(Object).Module.Assembly) + if (assembly != typeof(object).Module.Assembly) { throw new ArgumentException(SR.Argument_OnlyMscorlib); } @@ -633,7 +633,7 @@ internal static bool EqualsOrdinalIgnoreCase(ref char strA, ref char strB, int l // IsPrefix // // Determines whether prefix is a prefix of string. If prefix equals - // String.Empty, true is returned. + // string.Empty, true is returned. // //////////////////////////////////////////////////////////////////////// public virtual bool IsPrefix(string source, string prefix, CompareOptions options) @@ -698,7 +698,7 @@ public virtual bool IsPrefix(string source, string prefix) // IsSuffix // // Determines whether suffix is a suffix of string. If suffix equals - // String.Empty, true is returned. + // string.Empty, true is returned. // //////////////////////////////////////////////////////////////////////// public virtual bool IsSuffix(string source, string suffix, CompareOptions options) @@ -765,7 +765,7 @@ public virtual bool IsSuffix(string source, string suffix) // // Returns the first index where value is found in string. The // search starts from startIndex and ends at endIndex. Returns -1 if - // the specified value is not found. If value equals String.Empty, + // the specified value is not found. If value equals string.Empty, // startIndex is returned. Throws IndexOutOfRange if startIndex or // endIndex is less than zero or greater than the length of string. // Throws ArgumentException if value is null. @@ -1013,7 +1013,7 @@ internal int IndexOfOrdinal(string source, string value, int startIndex, int cou // // Returns the last index where value is found in string. The // search starts from startIndex and ends at endIndex. Returns -1 if - // the specified value is not found. If value equals String.Empty, + // the specified value is not found. If value equals string.Empty, // endIndex is returned. Throws IndexOutOfRange if startIndex or // endIndex is less than zero or greater than the length of string. // Throws ArgumentException if value is null. @@ -1021,7 +1021,7 @@ internal int IndexOfOrdinal(string source, string value, int startIndex, int cou //////////////////////////////////////////////////////////////////////// - public virtual int LastIndexOf(String source, char value) + public virtual int LastIndexOf(string source, char value) { if (source == null) throw new ArgumentNullException(nameof(source)); @@ -1236,7 +1236,7 @@ public virtual SortKey GetSortKey(string source) //////////////////////////////////////////////////////////////////////// - public override bool Equals(Object value) + public override bool Equals(object value) { CompareInfo that = value as CompareInfo; diff --git a/src/System.Private.CoreLib/shared/System/Globalization/CultureData.Unix.cs b/src/System.Private.CoreLib/shared/System/Globalization/CultureData.Unix.cs index 3fce527929d..933087d3b45 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/CultureData.Unix.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/CultureData.Unix.cs @@ -149,7 +149,7 @@ private string GetLocaleInfo(string localeName, LocaleStringData type) // Failed, just use empty string StringBuilderCache.Release(sb); Debug.Fail("[CultureData.GetLocaleInfo(LocaleStringData)] Failed"); - return String.Empty; + return string.Empty; } return StringBuilderCache.GetStringAndRelease(sb); } @@ -216,7 +216,7 @@ private string GetTimeFormatString(bool shortFormat) // Failed, just use empty string StringBuilderCache.Release(sb); Debug.Fail("[CultureData.GetTimeFormatString(bool shortFormat)] Failed"); - return String.Empty; + return string.Empty; } return ConvertIcuTimeFormatString(StringBuilderCache.GetStringAndRelease(sb)); diff --git a/src/System.Private.CoreLib/shared/System/Globalization/DateTimeFormat.cs b/src/System.Private.CoreLib/shared/System/Globalization/DateTimeFormat.cs index 81e81d0dab9..73fb0e9b3d6 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/DateTimeFormat.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/DateTimeFormat.cs @@ -165,7 +165,7 @@ class DateTimeFormat // If the digits of the value is greater than len, no leading zero is added. // // Notes: - // The function can format to Int32.MaxValue. + // The function can format to int.MaxValue. // //////////////////////////////////////////////////////////////////////////// internal static void FormatDigits(StringBuilder outputBuffer, int value, int len) @@ -765,10 +765,10 @@ private static bool IsUseGenitiveForm(ReadOnlySpan format, int index, int // 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, ReadOnlySpan format, Int32 tokenLen, Boolean timeOnly, StringBuilder result) + private static void FormatCustomizedTimeZone(DateTime dateTime, TimeSpan offset, ReadOnlySpan format, int tokenLen, bool timeOnly, StringBuilder result) { // See if the instance already has an offset - Boolean dateTimeFormat = (offset == NullOffset); + bool dateTimeFormat = (offset == NullOffset); if (dateTimeFormat) { // No offset. The instance is a DateTime and the output should be the local time zone @@ -1069,7 +1069,7 @@ private static StringBuilder FormatStringBuilder(DateTime dateTime, ReadOnlySpan Debug.Assert(dtfi != null); if (format.Length == 0) { - Boolean timeOnlySpecialCase = false; + bool timeOnlySpecialCase = false; if (dateTime.Ticks < Calendar.TicksPerDay) { // If the time is less than 1 day, consider it as time of day. diff --git a/src/System.Private.CoreLib/shared/System/Globalization/DateTimeFormatInfo.cs b/src/System.Private.CoreLib/shared/System/Globalization/DateTimeFormatInfo.cs index edec75ac85b..1b47c372cb2 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/DateTimeFormatInfo.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/DateTimeFormatInfo.cs @@ -58,10 +58,10 @@ public sealed class DateTimeFormatInfo : IFormatProvider, ICloneable private CultureData _cultureData; // The culture name used to create this DTFI. - private String _name = null; + private string _name = null; // The language name of the culture used to create this DTFI. - private String _langName = null; + private string _langName = null; // CompareInfo usually used by the parser. private CompareInfo _compareInfo = null; @@ -73,28 +73,28 @@ public sealed class DateTimeFormatInfo : IFormatProvider, ICloneable // Caches for various properties. // - private String amDesignator = null; - private String pmDesignator = null; + private string amDesignator = null; + private string pmDesignator = null; - private String dateSeparator = null; // derived from short date (whidbey expects, arrowhead doesn't) + private string dateSeparator = null; // derived from short date (whidbey expects, arrowhead doesn't) - private String generalShortTimePattern = null; // short date + short time (whidbey expects, arrowhead doesn't) + private string generalShortTimePattern = null; // short date + short time (whidbey expects, arrowhead doesn't) - private String generalLongTimePattern = null; // short date + long time (whidbey expects, arrowhead doesn't) + private string generalLongTimePattern = null; // short date + long time (whidbey expects, arrowhead doesn't) - private String timeSeparator = null; // derived from long time (whidbey expects, arrowhead doesn't) - private String monthDayPattern = null; + private string timeSeparator = null; // derived from long time (whidbey expects, arrowhead doesn't) + private string monthDayPattern = null; // added in .NET Framework Release {2.0SP1/3.0SP1/3.5RTM} - private String dateTimeOffsetPattern = null; + private string dateTimeOffsetPattern = null; // // The following are constant values. // - private const String rfc1123Pattern = "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'"; + private const string rfc1123Pattern = "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'"; // The sortable pattern is based on ISO 8601. - private const String sortableDateTimePattern = "yyyy'-'MM'-'dd'T'HH':'mm':'ss"; - private const String universalSortableDateTimePattern = "yyyy'-'MM'-'dd HH':'mm':'ss'Z'"; + private const string sortableDateTimePattern = "yyyy'-'MM'-'dd'T'HH':'mm':'ss"; + private const string universalSortableDateTimePattern = "yyyy'-'MM'-'dd HH':'mm':'ss'Z'"; // // The following are affected by calendar settings. @@ -105,27 +105,27 @@ public sealed class DateTimeFormatInfo : IFormatProvider, ICloneable private int calendarWeekRule = -1; - private String fullDateTimePattern = null; // long date + long time (whidbey expects, arrowhead doesn't) + private string fullDateTimePattern = null; // long date + long time (whidbey expects, arrowhead doesn't) - private String[] abbreviatedDayNames = null; + private string[] abbreviatedDayNames = null; - private String[] m_superShortDayNames = null; + private string[] m_superShortDayNames = null; - private String[] dayNames = null; - private String[] abbreviatedMonthNames = null; - private String[] monthNames = null; + private string[] dayNames = null; + private string[] abbreviatedMonthNames = null; + private string[] monthNames = null; // Cache the genitive month names that we retrieve from the data table. - private String[] genitiveMonthNames = null; + private string[] genitiveMonthNames = null; // Cache the abbreviated genitive month names that we retrieve from the data table. - private String[] m_genitiveAbbreviatedMonthNames = null; + private string[] m_genitiveAbbreviatedMonthNames = null; // Cache the month names of a leap year that we retrieve from the data table. - private String[] leapYearMonthNames = null; + private string[] leapYearMonthNames = null; // For our "patterns" arrays we have 2 variables, a string and a string[] // @@ -134,23 +134,23 @@ public sealed class DateTimeFormatInfo : IFormatProvider, ICloneable // When we initially construct our string[], we set the string to string[0] // The "default" Date/time patterns - private String longDatePattern = null; - private String shortDatePattern = null; - private String yearMonthPattern = null; - private String longTimePattern = null; - private String shortTimePattern = null; + private string longDatePattern = null; + private string shortDatePattern = null; + private string yearMonthPattern = null; + private string longTimePattern = null; + private string shortTimePattern = null; - private String[] allYearMonthPatterns = null; + private string[] allYearMonthPatterns = null; - private String[] allShortDatePatterns = null; - private String[] allLongDatePatterns = null; - private String[] allShortTimePatterns = null; - private String[] allLongTimePatterns = null; + private string[] allShortDatePatterns = null; + private string[] allLongDatePatterns = null; + private string[] allShortTimePatterns = null; + private string[] allLongTimePatterns = null; // Cache the era names for this DateTimeFormatInfo instance. - private String[] m_eraNames = null; - private String[] m_abbrevEraNames = null; - private String[] m_abbrevEnglishEraNames = null; + private string[] m_eraNames = null; + private string[] m_abbrevEraNames = null; + private string[] m_abbrevEnglishEraNames = null; private CalendarId[] optionalCalendars = null; @@ -164,7 +164,7 @@ public sealed class DateTimeFormatInfo : IFormatProvider, ICloneable private DateTimeFormatFlags formatFlags = DateTimeFormatFlags.NotInitialized; - private String CultureName + private string CultureName { get { @@ -189,7 +189,7 @@ private CultureInfo Culture } // TODO: This ignores other cultures that might want to do something similar - private String LanguageName + private string LanguageName { get { @@ -261,9 +261,9 @@ private string[] internalGetDayOfWeekNamesCore() // //////////////////////////////////////////////////////////////////////////// - private String[] internalGetAbbreviatedMonthNames() => this.abbreviatedMonthNames ?? internalGetAbbreviatedMonthNamesCore(); + private string[] internalGetAbbreviatedMonthNames() => this.abbreviatedMonthNames ?? internalGetAbbreviatedMonthNamesCore(); [MethodImpl(MethodImplOptions.NoInlining)] - private String[] internalGetAbbreviatedMonthNamesCore() + private string[] internalGetAbbreviatedMonthNamesCore() { // Get the month names for our current calendar this.abbreviatedMonthNames = _cultureData.AbbreviatedMonthNames(Calendar.ID); @@ -386,13 +386,13 @@ public static DateTimeFormatInfo CurrentInfo provider.GetFormat(typeof(DateTimeFormatInfo)) is DateTimeFormatInfo info2 ? info2 : CurrentInfo; // Couldn't get anything, just use currentInfo as fallback - public Object GetFormat(Type formatType) + public object GetFormat(Type formatType) { 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, @@ -403,7 +403,7 @@ public Object Clone() } - public String AMDesignator + public string AMDesignator { get { @@ -546,7 +546,7 @@ private CalendarId[] OptionalCalendars ============================================================================*/ - public int GetEra(String eraName) + public int GetEra(string eraName) { if (eraName == null) { @@ -602,7 +602,7 @@ public int GetEra(String eraName) } - internal String[] EraNames + internal string[] EraNames { get { @@ -624,7 +624,7 @@ internal String[] EraNames ============================================================================*/ // Era names are 1 indexed - public String GetEraName(int era) + public string GetEraName(int era) { if (era == Calendar.CurrentEra) { @@ -641,7 +641,7 @@ public String GetEraName(int era) throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue); } - internal String[] AbbreviatedEraNames + internal string[] AbbreviatedEraNames { get { @@ -654,7 +654,7 @@ internal String[] AbbreviatedEraNames } // Era names are 1 indexed - public String GetAbbreviatedEraName(int era) + public string GetAbbreviatedEraName(int era) { if (AbbreviatedEraNames.Length == 0) { @@ -673,7 +673,7 @@ public String GetAbbreviatedEraName(int era) throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue); } - internal String[] AbbreviatedEnglishEraNames + internal string[] AbbreviatedEnglishEraNames { get { @@ -772,7 +772,7 @@ public CalendarWeekRule CalendarWeekRule } } - public String FullDateTimePattern + public string FullDateTimePattern { get { @@ -802,7 +802,7 @@ public String FullDateTimePattern // 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 { @@ -842,7 +842,7 @@ public String LongDatePattern // 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 { @@ -881,7 +881,7 @@ public String LongTimePattern // Note: just to be confusing there's only 1 month day pattern, not a whole list - public String MonthDayPattern + public string MonthDayPattern { get { @@ -909,7 +909,7 @@ public String MonthDayPattern } - public String PMDesignator + public string PMDesignator { get { @@ -937,7 +937,7 @@ public String PMDesignator } - public String RFC1123Pattern + public string RFC1123Pattern { get { @@ -950,7 +950,7 @@ public String RFC1123Pattern // 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 { @@ -991,7 +991,7 @@ public String ShortDatePattern // 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 { @@ -1026,7 +1026,7 @@ public String ShortTimePattern } - public String SortableDateTimePattern + public string SortableDateTimePattern { get { @@ -1041,7 +1041,7 @@ public String SortableDateTimePattern ** concatation every time somebody asks for the general format. ==============================================================================*/ - internal String GeneralShortTimePattern + internal string GeneralShortTimePattern { get { @@ -1060,7 +1060,7 @@ internal String GeneralShortTimePattern ** concatation every time somebody asks for the general format. ==============================================================================*/ - internal String GeneralLongTimePattern + internal string GeneralLongTimePattern { get { @@ -1079,7 +1079,7 @@ internal String GeneralLongTimePattern ** concatation every time somebody uses this form ==============================================================================*/ - internal String DateTimeOffsetPattern + internal string DateTimeOffsetPattern { get { @@ -1168,7 +1168,7 @@ public string TimeSeparator } } - public String UniversalSortableDateTimePattern + public string UniversalSortableDateTimePattern { get { @@ -1181,7 +1181,7 @@ public String UniversalSortableDateTimePattern // The string[] contains the list of patterns, EXCEPT the default may not be included. // The string contains the default pattern. // When we initially construct our string[], we set the string to string[0] - public String YearMonthPattern + public string YearMonthPattern { get { @@ -1215,7 +1215,7 @@ public String YearMonthPattern // // Check if a string array contains a null value, and throw ArgumentNullException with parameter name "value" // - private static void CheckNullValue(String[] values, int length) + private static void CheckNullValue(string[] values, int length) { Debug.Assert(values != null, "value != null"); Debug.Assert(values.Length >= length); @@ -1230,11 +1230,11 @@ private static void CheckNullValue(String[] values, int length) } - public String[] AbbreviatedDayNames + public string[] AbbreviatedDayNames { get { - return ((String[])internalGetAbbreviatedDayOfWeekNames().Clone()); + return ((string[])internalGetAbbreviatedDayOfWeekNames().Clone()); } set @@ -1258,11 +1258,11 @@ public String[] AbbreviatedDayNames } // Returns the string array of the one-letter day of week names. - public String[] ShortestDayNames + public string[] ShortestDayNames { get { - return ((String[])internalGetSuperShortDayNames().Clone()); + return ((string[])internalGetSuperShortDayNames().Clone()); } set @@ -1284,11 +1284,11 @@ public String[] ShortestDayNames } - public String[] DayNames + public string[] DayNames { get { - return ((String[])internalGetDayOfWeekNames().Clone()); + return ((string[])internalGetDayOfWeekNames().Clone()); } set @@ -1312,11 +1312,11 @@ public String[] DayNames } - public String[] AbbreviatedMonthNames + public string[] AbbreviatedMonthNames { get { - return ((String[])internalGetAbbreviatedMonthNames().Clone()); + return ((string[])internalGetAbbreviatedMonthNames().Clone()); } set @@ -1339,11 +1339,11 @@ public String[] AbbreviatedMonthNames } - public String[] MonthNames + public string[] MonthNames { get { - return ((String[])internalGetMonthNames().Clone()); + return ((string[])internalGetMonthNames().Clone()); } set @@ -1398,13 +1398,13 @@ internal bool HasSpacesInDayNames // 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; + string[] monthNamesArray = null; switch (style) { case MonthNameStyles.Genitive: @@ -1436,7 +1436,7 @@ internal String internalGetMonthName(int month, MonthNameStyles style, bool abbr // Arguments: // abbreviated When true, return abbreviated form. Otherwise, return a full form. // - private String[] internalGetGenitiveMonthNames(bool abbreviated) + private string[] internalGetGenitiveMonthNames(bool abbreviated) { if (abbreviated) { @@ -1465,7 +1465,7 @@ private String[] internalGetGenitiveMonthNames(bool abbreviated) // If this culture does not have different month names in a leap year, the normal month name is returned. // Arguments: None. (can use abbreviated later if needed) // - internal String[] internalGetLeapYearMonthNames(/*bool abbreviated*/) + internal string[] internalGetLeapYearMonthNames(/*bool abbreviated*/) { if (this.leapYearMonthNames == null) { @@ -1478,7 +1478,7 @@ internal String[] internalGetLeapYearMonthNames(/*bool abbreviated*/) } - public String GetAbbreviatedDayName(DayOfWeek dayofweek) + public string GetAbbreviatedDayName(DayOfWeek dayofweek) { if ((int)dayofweek < 0 || (int)dayofweek > 6) { @@ -1510,13 +1510,13 @@ public string GetShortestDayName(DayOfWeek dayOfWeek) } // Get all possible combination of inputs - private static String[] GetCombinedPatterns(String[] patterns1, String[] patterns2, String connectString) + private static string[] GetCombinedPatterns(string[] patterns1, string[] patterns2, string connectString) { Debug.Assert(patterns1 != null); Debug.Assert(patterns2 != null); // Get array size - String[] result = new String[patterns1.Length * patterns2.Length]; + string[] result = new string[patterns1.Length * patterns2.Length]; // Counter of actual results int k = 0; @@ -1535,11 +1535,11 @@ private static String[] GetCombinedPatterns(String[] patterns1, String[] pattern public string[] GetAllDateTimePatterns() { - List results = new List(DEFAULT_ALL_DATETIMES_SIZE); + List results = new List(DEFAULT_ALL_DATETIMES_SIZE); for (int i = 0; i < DateTimeFormat.allStandardFormats.Length; i++) { - String[] strings = GetAllDateTimePatterns(DateTimeFormat.allStandardFormats[i]); + string[] strings = GetAllDateTimePatterns(DateTimeFormat.allStandardFormats[i]); for (int j = 0; j < strings.Length; j++) { results.Add(strings[j]); @@ -1550,7 +1550,7 @@ public string[] GetAllDateTimePatterns() public string[] GetAllDateTimePatterns(char format) { - String[] result = null; + string[] result = null; switch (format) { @@ -1575,18 +1575,18 @@ public string[] GetAllDateTimePatterns(char format) break; case 'm': case 'M': - result = new String[] { MonthDayPattern }; + result = new string[] { MonthDayPattern }; break; case 'o': case 'O': - result = new String[] { RoundtripFormat }; + result = new string[] { 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; @@ -1595,7 +1595,7 @@ public string[] GetAllDateTimePatterns(char format) result = this.AllLongTimePatterns; break; case 'u': - result = new String[] { UniversalSortableDateTimePattern }; + result = new string[] { UniversalSortableDateTimePattern }; break; case 'y': case 'Y': @@ -1608,7 +1608,7 @@ public string[] GetAllDateTimePatterns(char format) } - public String GetDayName(DayOfWeek dayofweek) + public string GetDayName(DayOfWeek dayofweek) { if ((int)dayofweek < 0 || (int)dayofweek > 6) { @@ -1621,7 +1621,7 @@ public String GetDayName(DayOfWeek dayofweek) return (internalGetDayOfWeekNames()[(int)dayofweek]); } - public String GetAbbreviatedMonthName(int month) + public string GetAbbreviatedMonthName(int month) { if (month < 1 || month > 13) { @@ -1633,7 +1633,7 @@ public String GetAbbreviatedMonthName(int month) return (internalGetAbbreviatedMonthNames()[month - 1]); } - public String GetMonthName(int month) + public string GetMonthName(int month) { if (month < 1 || month > 13) { @@ -1690,7 +1690,7 @@ private static string[] GetMergedPatterns(string[] patterns, string defaultPatte else { // Not found, make room for it - newPatterns = new String[patterns.Length + 1]; + newPatterns = new string[patterns.Length + 1]; // Copy existing array Array.Copy(patterns, 0, newPatterns, 1, patterns.Length); @@ -1704,12 +1704,12 @@ private static string[] GetMergedPatterns(string[] patterns, string defaultPatte } // Needed by DateTimeFormatInfo and DateTimeFormat - internal const String RoundtripFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK"; - internal const String RoundtripDateTimeUnfixed = "yyyy'-'MM'-'ddTHH':'mm':'ss zzz"; + internal const string RoundtripFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK"; + internal const string RoundtripDateTimeUnfixed = "yyyy'-'MM'-'ddTHH':'mm':'ss zzz"; // Default string isn't necessarily in our string array, so get the // merged patterns of both - private String[] AllYearMonthPatterns + private string[] AllYearMonthPatterns { get { @@ -1717,7 +1717,7 @@ private String[] AllYearMonthPatterns } } - private String[] AllShortDatePatterns + private string[] AllShortDatePatterns { get { @@ -1725,7 +1725,7 @@ private String[] AllShortDatePatterns } } - private String[] AllShortTimePatterns + private string[] AllShortTimePatterns { get { @@ -1733,7 +1733,7 @@ private String[] AllShortTimePatterns } } - private String[] AllLongDatePatterns + private string[] AllLongDatePatterns { get { @@ -1741,7 +1741,7 @@ private String[] AllLongDatePatterns } } - private String[] AllLongTimePatterns + private string[] AllLongTimePatterns { get { @@ -1751,7 +1751,7 @@ private String[] AllLongTimePatterns // NOTE: Clone this string array if you want to return it to user. Otherwise, you are returning a writable cache copy. // This won't include default, call AllYearMonthPatterns - private String[] UnclonedYearMonthPatterns + private string[] UnclonedYearMonthPatterns { get { @@ -1770,7 +1770,7 @@ private String[] UnclonedYearMonthPatterns // 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 { @@ -1788,7 +1788,7 @@ private String[] UnclonedShortDatePatterns // NOTE: Clone this string array if you want to return it to user. Otherwise, you are returning a writable cache copy. // This won't include default, call AllLongDatePatterns - private String[] UnclonedLongDatePatterns + private string[] UnclonedLongDatePatterns { get { @@ -1806,7 +1806,7 @@ private String[] UnclonedLongDatePatterns // NOTE: Clone this string array if you want to return it to user. Otherwise, you are returning a writable cache copy. // This won't include default, call AllShortTimePatterns - private String[] UnclonedShortTimePatterns + private string[] UnclonedShortTimePatterns { get { @@ -1823,7 +1823,7 @@ private String[] UnclonedShortTimePatterns // NOTE: Clone this string array if you want to return it to user. Otherwise, you are returning a writable cache copy. // This won't include default, call AllLongTimePatterns - private String[] UnclonedLongTimePatterns + private string[] UnclonedLongTimePatterns { get { @@ -1896,7 +1896,7 @@ public string NativeCalendarName // // WARNING: If more validation is ever done in one place, it should be done in the other. // - public void SetAllDateTimePatterns(String[] patterns, char format) + public void SetAllDateTimePatterns(string[] patterns, char format) { if (IsReadOnly) throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); @@ -1957,11 +1957,11 @@ public void SetAllDateTimePatterns(String[] patterns, char format) ClearTokenHashTable(); } - public String[] AbbreviatedMonthGenitiveNames + public string[] AbbreviatedMonthGenitiveNames { get { - return ((String[])internalGetGenitiveMonthNames(true).Clone()); + return ((string[])internalGetGenitiveMonthNames(true).Clone()); } set @@ -1983,11 +1983,11 @@ public String[] AbbreviatedMonthGenitiveNames } } - public String[] MonthGenitiveNames + public string[] MonthGenitiveNames { get { - return ((String[])internalGetGenitiveMonthNames(false).Clone()); + return ((string[])internalGetGenitiveMonthNames(false).Clone()); } set @@ -2013,7 +2013,7 @@ public String[] MonthGenitiveNames // Positive TimeSpan Pattern // private string _fullTimeSpanPositivePattern; - internal String FullTimeSpanPositivePattern + internal string FullTimeSpanPositivePattern { get { @@ -2024,7 +2024,7 @@ internal String FullTimeSpanPositivePattern cultureDataWithoutUserOverrides = CultureData.GetCultureData(_cultureData.CultureName, false); else cultureDataWithoutUserOverrides = _cultureData; - String decimalSeparator = new NumberFormatInfo(cultureDataWithoutUserOverrides).NumberDecimalSeparator; + string decimalSeparator = new NumberFormatInfo(cultureDataWithoutUserOverrides).NumberDecimalSeparator; _fullTimeSpanPositivePattern = "d':'h':'mm':'ss'" + decimalSeparator + "'FFFFFFF"; } @@ -2036,7 +2036,7 @@ internal String FullTimeSpanPositivePattern // Negative TimeSpan Pattern // private string _fullTimeSpanNegativePattern; - internal String FullTimeSpanNegativePattern + internal string FullTimeSpanNegativePattern { get { @@ -2070,7 +2070,7 @@ internal CompareInfo CompareInfo | DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeLocal | DateTimeStyles.AssumeUniversal | DateTimeStyles.RoundtripKind); - internal static void ValidateStyles(DateTimeStyles style, String parameterName) + internal static void ValidateStyles(DateTimeStyles style, string parameterName) { if ((style & InvalidDateTimeStyles) != 0) { @@ -2106,7 +2106,7 @@ private DateTimeFormatFlags InitializeFormatFlags() return formatFlags; } - internal Boolean HasForceTwoDigitYears + internal bool HasForceTwoDigitYears { get { @@ -2129,7 +2129,7 @@ internal Boolean HasForceTwoDigitYears } // Returns whether the YearMonthAdjustment function has any fix-up work to do for this culture/calendar. - internal Boolean HasYearMonthAdjustment + internal bool HasYearMonthAdjustment { get { @@ -2142,7 +2142,7 @@ internal Boolean HasYearMonthAdjustment // 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) + internal bool YearMonthAdjustment(ref int year, ref int month, bool parsedMonthName) { if ((FormatFlags & DateTimeFormatFlags.UseHebrewRule) != 0) { @@ -2189,45 +2189,45 @@ internal Boolean YearMonthAdjustment(ref int year, ref int month, Boolean parsed private const int TOKEN_HASH_SIZE = 199; private const int SECOND_PRIME = 197; - private const String dateSeparatorOrTimeZoneOffset = "-"; - private const String invariantDateSeparator = "/"; - private const String invariantTimeSeparator = ":"; + private const string dateSeparatorOrTimeZoneOffset = "-"; + private const string invariantDateSeparator = "/"; + private const string invariantTimeSeparator = ":"; // // 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 GMTName = "GMT"; - internal const String ZuluName = "Z"; + internal const string GMTName = "GMT"; + internal const string ZuluName = "Z"; - internal const String KoreanLangName = "ko"; - internal const String JapaneseLangName = "ja"; - internal const String EnglishLangName = "en"; + internal const string KoreanLangName = "ko"; + internal const string JapaneseLangName = "ja"; + internal const string EnglishLangName = "en"; private static volatile DateTimeFormatInfo s_jajpDTFI; private static volatile DateTimeFormatInfo s_zhtwDTFI; @@ -2341,7 +2341,7 @@ internal TokenHashValue[] CreateTokenHashTable() InsertHash(temp, dateSeparatorOrTimeZoneOffset, TokenType.SEP_DateOrOffset, 0); } - String[] dateWords = null; + string[] dateWords = null; DateTimeFormatInfoScanner scanner = null; // We need to rescan the date words since we're always synthetic @@ -2355,7 +2355,7 @@ internal TokenHashValue[] CreateTokenHashTable() // 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; + string monthPostfix = null; if (dateWords != null) { // There are DateWords. It could be a real date word (such as "de"), or a monthPostfix. @@ -2372,7 +2372,7 @@ internal TokenHashValue[] CreateTokenHashTable() AddMonthNames(temp, monthPostfix); break; case DateTimeFormatInfoScanner.IgnorableSymbolChar: - String symbol = dateWords[i].Substring(1); + string symbol = dateWords[i].Substring(1); InsertHash(temp, symbol, TokenType.IgnorableSymbol, 0); if (this.DateSeparator.Trim(null).Equals(symbol)) { @@ -2412,7 +2412,7 @@ internal TokenHashValue[] CreateTokenHashTable() { for (int i = 1; i <= 13; i++) { - String str; + string str; str = internalGetMonthName(i, MonthNameStyles.Genitive, false); InsertHash(temp, str, TokenType.MonthToken, i); } @@ -2422,7 +2422,7 @@ internal TokenHashValue[] CreateTokenHashTable() { for (int i = 1; i <= 13; i++) { - String str; + string str; str = internalGetMonthName(i, MonthNameStyles.LeapYear, false); InsertHash(temp, str, TokenType.MonthToken, i); } @@ -2432,7 +2432,7 @@ internal TokenHashValue[] CreateTokenHashTable() { //String str = GetDayOfWeekNames()[i]; // We have to call public methods here to work with inherited DTFI. - String str = GetDayName((DayOfWeek)i); + string str = GetDayName((DayOfWeek)i); InsertHash(temp, str, TokenType.DayOfWeekToken, i); str = GetAbbreviatedDayName((DayOfWeek)i); @@ -2452,7 +2452,7 @@ internal TokenHashValue[] CreateTokenHashTable() // Japanese allows day of week forms like: "(Tue)" for (int i = 0; i < 7; i++) { - String specialDayOfWeek = "(" + GetAbbreviatedDayName((DayOfWeek)i) + ")"; + string specialDayOfWeek = "(" + GetAbbreviatedDayName((DayOfWeek)i) + ")"; InsertHash(temp, specialDayOfWeek, TokenType.DayOfWeekToken, i); } if (this.Calendar.GetType() != typeof(JapaneseCalendar)) @@ -2488,7 +2488,7 @@ internal TokenHashValue[] CreateTokenHashTable() // Add invariant month names and day names. for (int i = 1; i <= 12; i++) { - String str; + 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 abbreviated // month names. @@ -2501,7 +2501,7 @@ internal TokenHashValue[] CreateTokenHashTable() 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); + string str = InvariantInfo.GetDayName((DayOfWeek)i); InsertHash(temp, str, TokenType.DayOfWeekToken, i); str = InvariantInfo.GetAbbreviatedDayName((DayOfWeek)i); @@ -2526,11 +2526,11 @@ internal TokenHashValue[] CreateTokenHashTable() return (temp); } - private void AddMonthNames(TokenHashValue[] temp, String monthPostfix) + private void AddMonthNames(TokenHashValue[] temp, string monthPostfix) { for (int i = 1; i <= 13; i++) { - String str; + 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 abbreviated @@ -2568,7 +2568,7 @@ private void AddMonthNames(TokenHashValue[] temp, String monthPostfix) private static bool TryParseHebrewNumber( ref __DTString str, - out Boolean badFormat, + out bool badFormat, out int number) { number = -1; @@ -2631,7 +2631,7 @@ private static bool IsHebrewChar(char ch) Debug.Assert(str.Index < str.Value.Length, "DateTimeFormatInfo.Tokenize(): start < value.Length"); char ch = str.m_current; - bool isLetter = Char.IsLetter(ch); + bool isLetter = char.IsLetter(ch); if (isLetter) { ch = this.Culture.TextInfo.ToLower(ch); @@ -2689,7 +2689,7 @@ private static bool IsHebrewChar(char ch) { // Check word boundary. The next character should NOT be a letter. char nextCh = str.Value[nextCharIndex]; - compareStrings = !(Char.IsLetter(nextCh)); + compareStrings = !(char.IsLetter(nextCh)); } } @@ -2724,7 +2724,7 @@ private static bool IsHebrewChar(char ch) return (false); } - private 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]; @@ -2757,7 +2757,7 @@ private void InsertAtCurrentHashNode(TokenHashValue[] hashTable, String str, cha Debug.Fail("The hashtable is full. This should not happen."); } - private 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) @@ -2768,7 +2768,7 @@ private void InsertHash(TokenHashValue[] hashTable, String str, TokenType tokenT 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(null); // Trim white space characters. // Could have space for separators @@ -2860,11 +2860,11 @@ private bool CompareStringIgnoreCaseOptimized(string string1, int offset1, int l internal class TokenHashValue { - internal String tokenString; + 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; diff --git a/src/System.Private.CoreLib/shared/System/Globalization/DateTimeFormatInfoScanner.cs b/src/System.Private.CoreLib/shared/System/Globalization/DateTimeFormatInfoScanner.cs index d7e0abfba1d..de43c2da3ea 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/DateTimeFormatInfoScanner.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/DateTimeFormatInfoScanner.cs @@ -189,7 +189,7 @@ internal static int SkipWhiteSpacesAndNonLetter(string pattern, int currentIndex break; } } - if (Char.IsLetter(ch) || ch == '\'' || ch == '.') + if (char.IsLetter(ch) || ch == '\'' || ch == '.') { break; } @@ -314,7 +314,7 @@ internal int AddDateWords(string pattern, int index, string formatPostfix) 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()); @@ -479,7 +479,7 @@ internal void ScanDateWord(string pattern) i++; break; default: - if (_ymdFlags == FoundDatePattern.FoundYMDPatternFlag && !Char.IsWhiteSpace(ch)) + if (_ymdFlags == FoundDatePattern.FoundYMDPatternFlag && !char.IsWhiteSpace(ch)) { // We are not seeing "." after YMD. Clear the flag. _ymdFlags = FoundDatePattern.None; @@ -659,7 +659,7 @@ private static bool ArrayElementsHaveSpace(string[] array) // so we don't have to go to native code side. for (int j = 0; j < array[i].Length; j++) { - if (Char.IsWhiteSpace(array[i][j])) + if (char.IsWhiteSpace(array[i][j])) { return true; } diff --git a/src/System.Private.CoreLib/shared/System/Globalization/DateTimeParse.cs b/src/System.Private.CoreLib/shared/System/Globalization/DateTimeParse.cs index 0c2d6c406e9..682b9e32b41 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/DateTimeParse.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/DateTimeParse.cs @@ -11,7 +11,7 @@ namespace System { internal static class DateTimeParse { - internal const Int32 MaxDateTimeNumberDigits = 8; + internal const int MaxDateTimeNumberDigits = 8; internal delegate bool MatchNumberDelegate(ref __DTString str, int digitLen, out int result); @@ -418,7 +418,7 @@ private static bool MatchWord(ref __DTString str, string target) if (nextCharIndex < str.Value.Length) { char nextCh = str.Value[nextCharIndex]; - if (Char.IsLetter(nextCh)) + if (char.IsLetter(nextCh)) { return (false); } @@ -573,7 +573,7 @@ private static bool HandleTimeZone(ref __DTString str, ref DateTimeResult result 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.Length - 1) + while (char.IsWhiteSpace(nextCh) && str.Index + whitespaceCount < str.Length - 1) { whitespaceCount++; nextCh = str.Value[str.Index + whitespaceCount]; @@ -602,7 +602,7 @@ private static bool HandleTimeZone(ref __DTString str, ref DateTimeResult result // 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) + private static bool Lex(DS dps, ref __DTString str, ref DateTimeToken dtok, ref DateTimeRawInfo raw, ref DateTimeResult result, ref DateTimeFormatInfo dtfi, DateTimeStyles styles) { TokenType tokenType; int tokenValue; @@ -1119,7 +1119,7 @@ private static Boolean Lex(DS dps, ref __DTString str, ref DateTimeToken dtok, r } break; case TokenType.UnknownToken: - if (Char.IsLetter(str.m_current)) + if (char.IsLetter(str.m_current)) { result.SetFailure(ParseFailureKind.FormatWithOriginalDateTimeAndParameter, nameof(SR.Format_UnknownDateTimeWord), str.Index); LexTraceExit("0200", dps); @@ -1128,7 +1128,7 @@ private static Boolean Lex(DS dps, ref __DTString str, ref DateTimeToken dtok, r if ((str.m_current == '-' || str.m_current == '+') && ((result.flags & ParseFlags.TimeZoneUsed) == 0)) { - Int32 originalIndex = str.Index; + int originalIndex = str.Index; if (ParseTimeZone(ref str, ref result.timeZoneOffset)) { result.flags |= ParseFlags.TimeZoneUsed; @@ -1160,10 +1160,10 @@ private static Boolean Lex(DS dps, ref __DTString str, ref DateTimeToken dtok, r return true; } - private static Boolean VerifyValidPunctuation(ref __DTString str) + private static bool VerifyValidPunctuation(ref __DTString str) { // Compatability Behavior. Allow trailing nulls and surrounding hashes - Char ch = str.Value[str.Index]; + char ch = str.Value[str.Index]; if (ch == '#') { bool foundStart = false; @@ -1198,7 +1198,7 @@ private static Boolean VerifyValidPunctuation(ref __DTString str) return false; } } - else if ((!Char.IsWhiteSpace(ch))) + else if ((!char.IsWhiteSpace(ch))) { // Anything other than whitespace outside hashes is invalid if (!foundStart || foundEnd) @@ -1247,7 +1247,7 @@ private static Boolean VerifyValidPunctuation(ref __DTString str) // // Return 0 for YMD, 1 for MDY, 2 for DMY, otherwise -1. // - private static Boolean GetYearMonthDayOrder(string datePattern, DateTimeFormatInfo dtfi, out int order) + private static bool GetYearMonthDayOrder(string datePattern, DateTimeFormatInfo dtfi, out int order) { int yearOrder = -1; int monthOrder = -1; @@ -1345,7 +1345,7 @@ private static Boolean GetYearMonthDayOrder(string datePattern, DateTimeFormatIn // // Return 0 for YM, 1 for MY, otherwise -1. // - private static Boolean GetYearMonthOrder(string pattern, DateTimeFormatInfo dtfi, out int order) + private static bool GetYearMonthOrder(string pattern, DateTimeFormatInfo dtfi, out int order) { int yearOrder = -1; int monthOrder = -1; @@ -1411,7 +1411,7 @@ private static Boolean GetYearMonthOrder(string pattern, DateTimeFormatInfo dtfi // // Return 0 for MD, 1 for DM, otherwise -1. // - private static Boolean GetMonthDayOrder(string pattern, DateTimeFormatInfo dtfi, out int order) + private static bool GetMonthDayOrder(string pattern, DateTimeFormatInfo dtfi, out int order) { int monthOrder = -1; int dayOrder = -1; @@ -1539,7 +1539,7 @@ private static void GetDefaultYear(ref DateTimeResult result, ref DateTimeStyles } // Processing teriminal case: DS.DX_NN - private static Boolean GetDayOfNN(ref DateTimeResult result, ref DateTimeStyles styles, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi) + private static bool GetDayOfNN(ref DateTimeResult result, ref DateTimeStyles styles, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi) { if ((result.flags & ParseFlags.HaveDate) != 0) { @@ -1582,7 +1582,7 @@ private static Boolean GetDayOfNN(ref DateTimeResult result, ref DateTimeStyles } // Processing teriminal case: DS.DX_NNN - private static Boolean GetDayOfNNN(ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi) + private static bool GetDayOfNNN(ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi) { if ((result.flags & ParseFlags.HaveDate) != 0) { @@ -1639,7 +1639,7 @@ private static Boolean GetDayOfNNN(ref DateTimeResult result, ref DateTimeRawInf return false; } - private static Boolean GetDayOfMN(ref DateTimeResult result, ref DateTimeStyles styles, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi) + private static bool GetDayOfMN(ref DateTimeResult result, ref DateTimeStyles styles, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi) { if ((result.flags & ParseFlags.HaveDate) != 0) { @@ -1701,7 +1701,7 @@ private static Boolean GetDayOfMN(ref DateTimeResult result, ref DateTimeStyles // //////////////////////////////////////////////////////////////////////// - private static Boolean GetHebrewDayOfNM(ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi) + private static bool GetHebrewDayOfNM(ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi) { int monthDayOrder; if (!GetMonthDayOrder(dtfi.MonthDayPattern, dtfi, out monthDayOrder)) @@ -1722,7 +1722,7 @@ private static Boolean GetHebrewDayOfNM(ref DateTimeResult result, ref DateTimeR return false; } - private static Boolean GetDayOfNM(ref DateTimeResult result, ref DateTimeStyles styles, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi) + private static bool GetDayOfNM(ref DateTimeResult result, ref DateTimeStyles styles, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi) { if ((result.flags & ParseFlags.HaveDate) != 0) { @@ -1778,7 +1778,7 @@ private static Boolean GetDayOfNM(ref DateTimeResult result, ref DateTimeStyles return true; } - private static Boolean GetDayOfMNN(ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi) + private static bool GetDayOfMNN(ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi) { if ((result.flags & ParseFlags.HaveDate) != 0) { @@ -1848,7 +1848,7 @@ private static Boolean GetDayOfMNN(ref DateTimeResult result, ref DateTimeRawInf return false; } - private static Boolean GetDayOfYNN(ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi) + private static bool GetDayOfYNN(ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi) { if ((result.flags & ParseFlags.HaveDate) != 0) { @@ -1883,7 +1883,7 @@ private static Boolean GetDayOfYNN(ref DateTimeResult result, ref DateTimeRawInf return false; } - private static Boolean GetDayOfNNY(ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi) + private static bool GetDayOfNNY(ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi) { if ((result.flags & ParseFlags.HaveDate) != 0) { @@ -1923,7 +1923,7 @@ private static Boolean GetDayOfNNY(ref DateTimeResult result, ref DateTimeRawInf } - private static Boolean GetDayOfYMN(ref DateTimeResult result, ref DateTimeRawInfo raw) + private static bool GetDayOfYMN(ref DateTimeResult result, ref DateTimeRawInfo raw) { if ((result.flags & ParseFlags.HaveDate) != 0) { @@ -1941,7 +1941,7 @@ private static Boolean GetDayOfYMN(ref DateTimeResult result, ref DateTimeRawInf return false; } - private static Boolean GetDayOfYN(ref DateTimeResult result, ref DateTimeRawInfo raw) + private static bool GetDayOfYN(ref DateTimeResult result, ref DateTimeRawInfo raw) { if ((result.flags & ParseFlags.HaveDate) != 0) { @@ -1959,7 +1959,7 @@ private static Boolean GetDayOfYN(ref DateTimeResult result, ref DateTimeRawInfo return false; } - private static Boolean GetDayOfYM(ref DateTimeResult result, ref DateTimeRawInfo raw) + private static bool GetDayOfYM(ref DateTimeResult result, ref DateTimeRawInfo raw) { if ((result.flags & ParseFlags.HaveDate) != 0) { @@ -2004,7 +2004,7 @@ private static void AdjustTimeMark(DateTimeFormatInfo dtfi, ref DateTimeRawInfo // // Adjust hour according to the time mark. // - private static Boolean AdjustHour(ref int hour, TM timeMark) + private static bool AdjustHour(ref int hour, TM timeMark) { if (timeMark != TM.NotSet) { @@ -2031,7 +2031,7 @@ private static Boolean AdjustHour(ref int hour, TM timeMark) return true; } - private static Boolean GetTimeOfN(ref DateTimeResult result, ref DateTimeRawInfo raw) + private static bool GetTimeOfN(ref DateTimeResult result, ref DateTimeRawInfo raw) { if ((result.flags & ParseFlags.HaveTime) != 0) { @@ -2052,7 +2052,7 @@ private static Boolean GetTimeOfN(ref DateTimeResult result, ref DateTimeRawInfo return true; } - private static Boolean GetTimeOfNN(ref DateTimeResult result, ref DateTimeRawInfo raw) + private static bool GetTimeOfNN(ref DateTimeResult result, ref DateTimeRawInfo raw) { Debug.Assert(raw.numCount >= 2, "raw.numCount >= 2"); if ((result.flags & ParseFlags.HaveTime) != 0) @@ -2068,7 +2068,7 @@ private static Boolean GetTimeOfNN(ref DateTimeResult result, ref DateTimeRawInf return true; } - private static Boolean GetTimeOfNNN(ref DateTimeResult result, ref DateTimeRawInfo raw) + private static bool GetTimeOfNNN(ref DateTimeResult result, ref DateTimeRawInfo raw) { if ((result.flags & ParseFlags.HaveTime) != 0) { @@ -2087,7 +2087,7 @@ private static Boolean GetTimeOfNNN(ref DateTimeResult result, ref DateTimeRawIn // // Processing terminal state: A Date suffix followed by one number. // - private static Boolean GetDateOfDSN(ref DateTimeResult result, ref DateTimeRawInfo raw) + private static bool GetDateOfDSN(ref DateTimeResult result, ref DateTimeRawInfo raw) { if (raw.numCount != 1 || result.Day != -1) { @@ -2098,7 +2098,7 @@ private static Boolean GetDateOfDSN(ref DateTimeResult result, ref DateTimeRawIn return true; } - private static Boolean GetDateOfNDS(ref DateTimeResult result, ref DateTimeRawInfo raw) + private static bool GetDateOfNDS(ref DateTimeResult result, ref DateTimeRawInfo raw) { if (result.Month == -1) { @@ -2122,7 +2122,7 @@ private static Boolean GetDateOfNDS(ref DateTimeResult result, ref DateTimeRawIn return true; } - private static Boolean GetDateOfNNDS(ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi) + private static bool 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 @@ -2236,7 +2236,7 @@ private static bool ProcessDateTimeSuffix(ref DateTimeResult result, ref DateTim // //////////////////////////////////////////////////////////////////////// - internal static Boolean ProcessHebrewTerminalState(DS dps, ref __DTString str, ref DateTimeResult result, ref DateTimeStyles styles, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi) + internal static bool ProcessHebrewTerminalState(DS dps, ref __DTString str, ref DateTimeResult result, ref DateTimeStyles styles, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi) { // The following are accepted terminal state for Hebrew date. switch (dps) @@ -2346,7 +2346,7 @@ internal static Boolean ProcessHebrewTerminalState(DS dps, ref __DTString str, r // A terminal state has been reached, call the appropriate function to fill in the parsing result. // Return true if the state is a terminal state. // - internal static Boolean ProcessTerminalState(DS dps, ref __DTString str, ref DateTimeResult result, ref DateTimeStyles styles, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi) + internal static bool ProcessTerminalState(DS dps, ref __DTString str, ref DateTimeResult result, ref DateTimeStyles styles, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi) { bool passed = true; switch (dps) @@ -2516,7 +2516,7 @@ internal static bool TryParse(ReadOnlySpan s, DateTimeFormatInfo dtfi, Dat DateTimeRawInfo raw = new DateTimeRawInfo(); // The buffer to store temporary parsing information. unsafe { - Int32* numberPointer = stackalloc Int32[3]; + int* numberPointer = stackalloc int[3]; raw.Init(numberPointer); } raw.hasSameDateAndTimeSeparators = dtfi.DateSeparator.Equals(dtfi.TimeSeparator, StringComparison.Ordinal); @@ -2730,7 +2730,7 @@ internal static bool TryParse(ReadOnlySpan s, DateTimeFormatInfo dtfi, Dat // Handles time zone adjustments and sets DateTimeKind values as required by the styles - private static Boolean DetermineTimeZoneAdjustments(ref __DTString str, ref DateTimeResult result, DateTimeStyles styles, Boolean bTimeOnly) + private static bool DetermineTimeZoneAdjustments(ref __DTString str, ref DateTimeResult result, DateTimeStyles styles, bool bTimeOnly) { if ((result.flags & ParseFlags.CaptureOffset) != 0) { @@ -2740,7 +2740,7 @@ private static Boolean DetermineTimeZoneAdjustments(ref __DTString str, ref Date } else { - Int64 offsetTicks = result.timeZoneOffset.Ticks; + long offsetTicks = result.timeZoneOffset.Ticks; // the DateTime offset must be within +- 14:00 hours. if (offsetTicks < DateTimeOffset.MinOffset || offsetTicks > DateTimeOffset.MaxOffset) @@ -2808,7 +2808,7 @@ private static Boolean DetermineTimeZoneAdjustments(ref __DTString str, ref Date } // Apply validation and adjustments specific to DateTimeOffset - private static Boolean DateTimeOffsetTimeZonePostProcessing(ref __DTString str, ref DateTimeResult result, DateTimeStyles styles) + private static bool DateTimeOffsetTimeZonePostProcessing(ref __DTString str, ref DateTimeResult result, DateTimeStyles styles) { // For DateTimeOffset, default to the Utc or Local offset when an offset was not specified by // the input string. @@ -2826,11 +2826,11 @@ private static Boolean DateTimeOffsetTimeZonePostProcessing(ref __DTString str, } } - Int64 offsetTicks = result.timeZoneOffset.Ticks; + long 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; + long 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. @@ -2854,7 +2854,7 @@ private static Boolean DateTimeOffsetTimeZonePostProcessing(ref __DTString str, 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); + bool toUtcResult = AdjustTimeZoneToUniversal(ref result); result.timeZoneOffset = TimeSpan.Zero; return toUtcResult; } @@ -2875,7 +2875,7 @@ private static Boolean DateTimeOffsetTimeZonePostProcessing(ref __DTString str, // 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 bool AdjustTimeZoneToUniversal(ref DateTimeResult result) { long resultTicks = result.parsedDate.Ticks; resultTicks -= result.timeZoneOffset.Ticks; @@ -2900,12 +2900,12 @@ private static Boolean AdjustTimeZoneToUniversal(ref DateTimeResult result) // 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 bool AdjustTimeZoneToLocal(ref DateTimeResult result, bool bTimeOnly) { long resultTicks = result.parsedDate.Ticks; // Convert to local ticks TimeZoneInfo tz = TimeZoneInfo.Local; - Boolean isAmbiguousLocalDst = false; + bool isAmbiguousLocalDst = false; if (resultTicks < Calendar.TicksPerDay) { // @@ -2936,7 +2936,7 @@ private static Boolean AdjustTimeZoneToLocal(ref DateTimeResult result, bool bTi { // Convert the GMT time to local time. DateTime utcDt = new DateTime(resultTicks, DateTimeKind.Utc); - Boolean isDaylightSavings = false; + bool isDaylightSavings = false; resultTicks += TimeZoneInfo.GetUtcOffsetFromUtc(utcDt, TimeZoneInfo.Local, out isDaylightSavings, out isAmbiguousLocalDst).Ticks; } } @@ -4948,13 +4948,13 @@ internal void GetRegularToken(out TokenType tokenType, out int tokenValue, DateT } } } - else if (Char.IsWhiteSpace(m_current)) + else if (char.IsWhiteSpace(m_current)) { // Just skip to the next character. while (++Index < Length) { m_current = Value[Index]; - if (!(Char.IsWhiteSpace(m_current))) + if (!(char.IsWhiteSpace(m_current))) { goto Start; } @@ -5002,7 +5002,7 @@ internal TokenType GetSeparatorToken(DateTimeFormatInfo dtfi, out int indexBefor Index + target.Length <= Length && m_info.Compare(Value.Slice(Index, target.Length), target, CompareOptions.IgnoreCase) == 0; - private static readonly Char[] WhiteSpaceChecks = new Char[] { ' ', '\u00A0' }; + private static readonly char[] WhiteSpaceChecks = new char[] { ' ', '\u00A0' }; internal bool MatchSpecifiedWords(string target, bool checkWordBoundary, ref int matchLength) { @@ -5035,7 +5035,7 @@ internal bool MatchSpecifiedWords(string target, bool checkWordBoundary, ref int 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; } @@ -5051,7 +5051,7 @@ internal bool MatchSpecifiedWords(string target, bool checkWordBoundary, ref int // Skip past multiple whitespace - while (thisPosition < Value.Length && Char.IsWhiteSpace(Value[thisPosition])) + while (thisPosition < Value.Length && char.IsWhiteSpace(Value[thisPosition])) { thisPosition++; matchLength++; @@ -5077,7 +5077,7 @@ internal bool MatchSpecifiedWords(string target, bool checkWordBoundary, ref int int nextCharIndex = Index + matchLength; if (nextCharIndex < Value.Length) { - if (Char.IsLetter(Value[nextCharIndex])) + if (char.IsLetter(Value[nextCharIndex])) { return (false); } @@ -5219,7 +5219,7 @@ internal void SkipWhiteSpaces() while (Index + 1 < Length) { char ch = Value[Index + 1]; - if (!Char.IsWhiteSpace(ch)) + if (!char.IsWhiteSpace(ch)) { return; } @@ -5240,7 +5240,7 @@ internal bool SkipWhiteSpaceCurrent() return (false); } - if (!Char.IsWhiteSpace(m_current)) + if (!char.IsWhiteSpace(m_current)) { return (true); } @@ -5248,7 +5248,7 @@ internal bool SkipWhiteSpaceCurrent() while (++Index < Length) { m_current = Value[Index]; - if (!Char.IsWhiteSpace(m_current)) + if (!char.IsWhiteSpace(m_current)) { return (true); } @@ -5260,7 +5260,7 @@ internal bool SkipWhiteSpaceCurrent() internal void TrimTail() { int i = Length - 1; - while (i >= 0 && Char.IsWhiteSpace(Value[i])) + while (i >= 0 && char.IsWhiteSpace(Value[i])) { i--; } @@ -5330,7 +5330,7 @@ internal DTSubString GetSubString() while (Index + sub.length < Length) { DTSubStringType currentType; - Char ch = Value[Index + sub.length]; + char ch = Value[Index + sub.length]; if (ch >= '0' && ch <= '9') { currentType = DTSubStringType.Number; @@ -5406,12 +5406,12 @@ internal enum DTSubStringType internal ref struct DTSubString { internal ReadOnlySpan s; - internal Int32 index; - internal Int32 length; + internal int index; + internal int length; internal DTSubStringType type; - internal Int32 value; + internal int value; - internal Char this[Int32 relativeIndex] + internal char this[int relativeIndex] { get { diff --git a/src/System.Private.CoreLib/shared/System/Globalization/HebrewNumber.cs b/src/System.Private.CoreLib/shared/System/Globalization/HebrewNumber.cs index 1e8fff2bcb2..4413cd9fa0a 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/HebrewNumber.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/HebrewNumber.cs @@ -87,7 +87,7 @@ private HebrewNumber() // //////////////////////////////////////////////////////////////////////////// - internal static String ToString(int Number) + internal static string ToString(int Number) { char cTens = '\x0'; char cUnits; // tens and units chars diff --git a/src/System.Private.CoreLib/shared/System/Globalization/HijriCalendar.Win32.cs b/src/System.Private.CoreLib/shared/System/Globalization/HijriCalendar.Win32.cs index 657163fba0c..42a79ec3919 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/HijriCalendar.Win32.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/HijriCalendar.Win32.cs @@ -10,7 +10,7 @@ public partial class HijriCalendar : Calendar { private int GetHijriDateAdjustment() { - if (_hijriAdvance == Int32.MinValue) + if (_hijriAdvance == int.MinValue) { // Never been set before. Use the system value from registry. _hijriAdvance = GetAdvanceHijriDate(); @@ -55,7 +55,7 @@ private static int GetAdvanceHijriDate() { try { - Object value = key.InternalGetValue(HijriAdvanceRegKeyEntry, null, false, false); + object value = key.InternalGetValue(HijriAdvanceRegKeyEntry, null, false, false); if (value == null) { return (0); @@ -69,7 +69,7 @@ private static int GetAdvanceHijriDate() { try { - int advance = Int32.Parse(str.AsSpan(HijriAdvanceRegKeyEntry.Length), provider:CultureInfo.InvariantCulture); + int advance = int.Parse(str.AsSpan(HijriAdvanceRegKeyEntry.Length), provider:CultureInfo.InvariantCulture); if ((advance >= MinAdvancedHijri) && (advance <= MaxAdvancedHijri)) { hijriAdvance = advance; diff --git a/src/System.Private.CoreLib/shared/System/Globalization/HijriCalendar.cs b/src/System.Private.CoreLib/shared/System/Globalization/HijriCalendar.cs index d6f2bc970f0..3eaf3d2539f 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/HijriCalendar.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/HijriCalendar.cs @@ -55,7 +55,7 @@ public partial class HijriCalendar : Calendar internal static readonly int[] HijriMonthDays = { 0, 30, 59, 89, 118, 148, 177, 207, 236, 266, 295, 325, 355 }; - private int _hijriAdvance = Int32.MinValue; + private int _hijriAdvance = int.MinValue; // DateTime.MaxValue = Hijri calendar (year:9666, month: 4, day: 3). internal const int MaxCalendarYear = 9666; @@ -176,7 +176,7 @@ public int HijriAdjustment { get { - if (_hijriAdvance == Int32.MinValue) + if (_hijriAdvance == int.MinValue) { // Never been set before. Use the system value from registry. _hijriAdvance = GetHijriDateAdjustment(); diff --git a/src/System.Private.CoreLib/shared/System/Globalization/IdnMapping.cs b/src/System.Private.CoreLib/shared/System/Globalization/IdnMapping.cs index e732ffaa209..164e46dc8a9 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/IdnMapping.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/IdnMapping.cs @@ -361,7 +361,7 @@ static string PunycodeEncode(string unicode) // Check last char int iTest = iNextDot - 1; - if (Char.IsLowSurrogate(unicode, iTest)) + if (char.IsLowSurrogate(unicode, iTest)) { iTest--; } @@ -380,7 +380,7 @@ static string PunycodeEncode(string unicode) for (basicCount = iAfterLastDot; basicCount < iNextDot; basicCount++) { // Can't be lonely surrogate because it would've thrown in normalization - Debug.Assert(Char.IsLowSurrogate(unicode, basicCount) == false, "[IdnMapping.punycode_encode]Unexpected low surrogate"); + Debug.Assert(char.IsLowSurrogate(unicode, basicCount) == false, "[IdnMapping.punycode_encode]Unexpected low surrogate"); // Double check our bidi rules BidiCategory testBidi = CharUnicodeInfo.GetBidiCategory(unicode, basicCount); @@ -406,7 +406,7 @@ static string PunycodeEncode(string unicode) numProcessed++; } // If its a surrogate, skip the next since our bidi category tester doesn't handle it. - else if (Char.IsSurrogatePair(unicode, basicCount)) + else if (char.IsSurrogatePair(unicode, basicCount)) basicCount++; } @@ -452,7 +452,7 @@ static string PunycodeEncode(string unicode) j < iNextDot; j += IsSupplementary(test) ? 2 : 1) { - test = Char.ConvertToUtf32(unicode, j); + test = char.ConvertToUtf32(unicode, j); if (test >= n && test < m) m = test; } @@ -465,7 +465,7 @@ static string PunycodeEncode(string unicode) for (j = iAfterLastDot; j < iNextDot; j+= IsSupplementary(test) ? 2 : 1) { // Make sure we're aware of surrogates - test = Char.ConvertToUtf32(unicode, j); + test = char.ConvertToUtf32(unicode, j); // Adjust for character position (only the chars in our string already, some // haven't been processed. @@ -740,7 +740,7 @@ private static string PunycodeDecode(string ascii) // insert n at position i of the output: Really tricky if we have surrogates int iUseInsertLocation; - String strTemp = Char.ConvertFromUtf32(n); + string strTemp = char.ConvertFromUtf32(n); // If we have supplimentary characters if (numSurrogatePairs > 0) @@ -752,7 +752,7 @@ private static string PunycodeDecode(string ascii) // If its a surrogate, we have to go one more if (iUseInsertLocation >= output.Length) throw new ArgumentException(SR.Argument_IdnBadPunycode, nameof(ascii)); - if (Char.IsSurrogate(output[iUseInsertLocation])) + if (char.IsSurrogate(output[iUseInsertLocation])) iUseInsertLocation++; } } @@ -788,7 +788,7 @@ private static string PunycodeDecode(string ascii) for (int iTest = iOutputAfterLastDot; iTest < output.Length; iTest++) { // This might happen if we run into a pair - if (Char.IsLowSurrogate(output[iTest])) + if (char.IsLowSurrogate(output[iTest])) continue; // Check to see if its LTR diff --git a/src/System.Private.CoreLib/shared/System/Globalization/InternalGlobalizationHelper.cs b/src/System.Private.CoreLib/shared/System/Globalization/InternalGlobalizationHelper.cs index 60abcecf611..6dc2b195156 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/InternalGlobalizationHelper.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/InternalGlobalizationHelper.cs @@ -25,8 +25,8 @@ internal static long TimeToTicks(int hour, int minute, int second) internal const long TicksPerMillisecond = 10000; internal const long TicksPerTenthSecond = TicksPerMillisecond * 100; internal const long TicksPerSecond = TicksPerMillisecond * 1000; // 10,000,000 - internal const long MaxSeconds = Int64.MaxValue / TicksPerSecond; - internal const long MinSeconds = Int64.MinValue / TicksPerSecond; + internal const long MaxSeconds = long.MaxValue / TicksPerSecond; + internal const long MinSeconds = long.MinValue / TicksPerSecond; private const int DaysPerYear = 365; private const int DaysPer4Years = DaysPerYear * 4 + 1; // 1461 private const int DaysPer100Years = DaysPer4Years * 25 - 1; // 36524 @@ -37,12 +37,12 @@ internal static long TimeToTicks(int hour, int minute, int second) private const long TicksPerDay = TicksPerHour * 24; internal const long MaxTicks = DaysTo10000 * TicksPerDay - 1; internal const long MinTicks = 0; - internal const long MaxMilliSeconds = Int64.MaxValue / TicksPerMillisecond; - internal const long MinMilliSeconds = Int64.MinValue / TicksPerMillisecond; + internal const long MaxMilliSeconds = long.MaxValue / TicksPerMillisecond; + internal const long MinMilliSeconds = long.MinValue / TicksPerMillisecond; internal const int StringBuilderDefaultCapacity = 16; - internal const Int64 MaxOffset = TimeSpan.TicksPerHour * 14; - internal const Int64 MinOffset = -MaxOffset; + internal const long MaxOffset = TimeSpan.TicksPerHour * 14; + internal const long MinOffset = -MaxOffset; } } diff --git a/src/System.Private.CoreLib/shared/System/Globalization/JapaneseCalendar.Win32.cs b/src/System.Private.CoreLib/shared/System/Globalization/JapaneseCalendar.Win32.cs index 1d0180b00e8..f4787a6cb46 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/JapaneseCalendar.Win32.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/JapaneseCalendar.Win32.cs @@ -43,7 +43,7 @@ private static EraInfo[] GetJapaneseEras() if (key == null) return null; // Look up the values in our reg key - String[] valueNames = key.GetValueNames(); + string[] valueNames = key.GetValueNames(); if (valueNames != null && valueNames.Length > 0) { registryEraRanges = new EraInfo[valueNames.Length]; @@ -143,7 +143,7 @@ private static int CompareEraRanges(EraInfo a, EraInfo b) // . is a delimiter, but the value of . doesn't matter. // '_' marks the space between the japanese era name, japanese abbreviated era name // english name, and abbreviated english names. - private static EraInfo GetEraFromValue(String value, String data) + private static EraInfo GetEraFromValue(string value, string data) { // Need inputs if (value == null || data == null) return null; @@ -160,9 +160,9 @@ private static EraInfo GetEraFromValue(String value, String data) int day; ReadOnlySpan valueSpan = value.AsSpan(); - if (!Int32.TryParse(valueSpan.Slice(0, 4), NumberStyles.None, NumberFormatInfo.InvariantInfo, out year) || - !Int32.TryParse(valueSpan.Slice(5, 2), NumberStyles.None, NumberFormatInfo.InvariantInfo, out month) || - !Int32.TryParse(valueSpan.Slice(8, 2), NumberStyles.None, NumberFormatInfo.InvariantInfo, out day)) + if (!int.TryParse(valueSpan.Slice(0, 4), NumberStyles.None, NumberFormatInfo.InvariantInfo, out year) || + !int.TryParse(valueSpan.Slice(5, 2), NumberStyles.None, NumberFormatInfo.InvariantInfo, out month) || + !int.TryParse(valueSpan.Slice(8, 2), NumberStyles.None, NumberFormatInfo.InvariantInfo, out day)) { // Couldn't convert integer, fail return null; @@ -172,7 +172,7 @@ private static EraInfo GetEraFromValue(String value, String data) // Get Strings // // Needs to be a certain length e_a_E_A at least (7 chars, exactly 4 groups) - String[] names = data.Split('_'); + string[] names = data.Split('_'); // Should have exactly 4 parts // 0 - Era Name @@ -199,7 +199,7 @@ private static EraInfo GetEraFromValue(String value, String data) // PAL Layer ends here - private static string[] s_japaneseErasEnglishNames = new String[] { "M", "T", "S", "H" }; + private static string[] s_japaneseErasEnglishNames = new string[] { "M", "T", "S", "H" }; private static string GetJapaneseEnglishEraName(int era) { diff --git a/src/System.Private.CoreLib/shared/System/Globalization/KoreanLunisolarCalendar.cs b/src/System.Private.CoreLib/shared/System/Globalization/KoreanLunisolarCalendar.cs index 0f71b5f687b..63636f5e3f4 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/KoreanLunisolarCalendar.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/KoreanLunisolarCalendar.cs @@ -1248,7 +1248,7 @@ internal override int GetYearInfo(int lunarYear, int index) { throw new ArgumentOutOfRangeException( "year", - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, MIN_LUNISOLAR_YEAR, @@ -1271,7 +1271,7 @@ internal override int GetGregorianYear(int year, int era) { throw new ArgumentOutOfRangeException( nameof(year), - String.Format( + string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, MIN_LUNISOLAR_YEAR, MAX_LUNISOLAR_YEAR)); } diff --git a/src/System.Private.CoreLib/shared/System/Globalization/NumberFormatInfo.cs b/src/System.Private.CoreLib/shared/System/Globalization/NumberFormatInfo.cs index 33d50b3fc3c..7afe0947482 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/NumberFormatInfo.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/NumberFormatInfo.cs @@ -237,7 +237,7 @@ NumberFormatInfo GetProviderNonNull(IFormatProvider provider) } } - public Object Clone() + public object Clone() { NumberFormatInfo n = (NumberFormatInfo)MemberwiseClone(); n.isReadOnly = false; @@ -325,7 +325,7 @@ public int[] CurrencyGroupSizes } VerifyWritable(); - Int32[] inputSizes = (Int32[])value.Clone(); + int[] inputSizes = (int[])value.Clone(); CheckGroupSize(nameof(CurrencyGroupSizes), inputSizes); currencyGroupSizes = inputSizes; } @@ -348,7 +348,7 @@ public int[] NumberGroupSizes } VerifyWritable(); - Int32[] inputSizes = (Int32[])value.Clone(); + int[] inputSizes = (int[])value.Clone(); CheckGroupSize(nameof(NumberGroupSizes), inputSizes); numberGroupSizes = inputSizes; } @@ -369,7 +369,7 @@ public int[] PercentGroupSizes SR.ArgumentNull_Obj); } VerifyWritable(); - Int32[] inputSizes = (Int32[])value.Clone(); + int[] inputSizes = (int[])value.Clone(); CheckGroupSize(nameof(PercentGroupSizes), inputSizes); percentGroupSizes = inputSizes; } @@ -774,7 +774,7 @@ public DigitShapes DigitSubstitution } } - public Object GetFormat(Type formatType) + public object GetFormat(Type formatType) { return formatType == typeof(NumberFormatInfo) ? this : null; } diff --git a/src/System.Private.CoreLib/shared/System/Globalization/RegionInfo.cs b/src/System.Private.CoreLib/shared/System/Globalization/RegionInfo.cs index b9daea3f9db..8416257d919 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/RegionInfo.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/RegionInfo.cs @@ -358,7 +358,7 @@ public virtual string ISOCurrencySymbol // (ie: en-US) // //////////////////////////////////////////////////////////////////////// - public override bool Equals(Object value) + public override bool Equals(object value) { RegionInfo that = value as RegionInfo; if (that != null) diff --git a/src/System.Private.CoreLib/shared/System/Globalization/SortKey.cs b/src/System.Private.CoreLib/shared/System/Globalization/SortKey.cs index 647db75b63c..96249462573 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/SortKey.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/SortKey.cs @@ -33,7 +33,7 @@ public partial class SortKey // The following constructor is designed to be called from CompareInfo to get the // the sort key of specific string for synthetic culture // - internal SortKey(String localeName, String str, CompareOptions options, byte[] keyData) + internal SortKey(string localeName, string str, CompareOptions options, byte[] keyData) { _keyData = keyData; _localeName = localeName; @@ -49,7 +49,7 @@ internal SortKey(String localeName, String str, CompareOptions options, byte[] k // of SortKey. // //////////////////////////////////////////////////////////////////////// - public virtual String OriginalString + public virtual string OriginalString { get { @@ -133,7 +133,7 @@ public static int Compare(SortKey sortkey1, SortKey sortkey2) // or not object refers to the same SortKey as the current instance. // //////////////////////////////////////////////////////////////////////// - public override bool Equals(Object value) + public override bool Equals(object value) { SortKey that = value as SortKey; @@ -167,7 +167,7 @@ public override int GetHashCode() // SortKey. // //////////////////////////////////////////////////////////////////////// - public override String ToString() + public override string ToString() { return ("SortKey - " + _localeName + ", " + _options + ", " + _string); } diff --git a/src/System.Private.CoreLib/shared/System/Globalization/StringInfo.cs b/src/System.Private.CoreLib/shared/System/Globalization/StringInfo.cs index 5b5cd939995..f7be252bfe2 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/StringInfo.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/StringInfo.cs @@ -32,7 +32,7 @@ public StringInfo(string value) this.String = value; } - public override bool Equals(Object value) + public override bool Equals(object value) { StringInfo that = value as StringInfo; if (that != null) diff --git a/src/System.Private.CoreLib/shared/System/Globalization/TextElementEnumerator.cs b/src/System.Private.CoreLib/shared/System/Globalization/TextElementEnumerator.cs index 8b0f102a774..7d8ff64a38f 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/TextElementEnumerator.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/TextElementEnumerator.cs @@ -21,7 +21,7 @@ namespace System.Globalization public class TextElementEnumerator : IEnumerator { - private String _str; + private string _str; private int _index; private int _startIndex; @@ -33,7 +33,7 @@ public class TextElementEnumerator : IEnumerator 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) + internal TextElementEnumerator(string str, int startIndex, int strLen) { Debug.Assert(str != null, "TextElementEnumerator(): str != null"); Debug.Assert(startIndex >= 0 && strLen >= 0, "TextElementEnumerator(): startIndex >= 0 && strLen >= 0"); @@ -61,7 +61,7 @@ public bool MoveNext() // Get the current text element. // - public Object Current + public object Current { get { @@ -73,7 +73,7 @@ public Object Current // Get the current text element. // - public String GetTextElement() + public string GetTextElement() { if (_index == _startIndex) { diff --git a/src/System.Private.CoreLib/shared/System/Globalization/TextInfo.cs b/src/System.Private.CoreLib/shared/System/Globalization/TextInfo.cs index 4906bedff49..c5f392cb080 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/TextInfo.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/TextInfo.cs @@ -76,7 +76,7 @@ internal TextInfo(CultureData cultureData) FinishInitialization(); } - void IDeserializationCallback.OnDeserialization(Object sender) + void IDeserializationCallback.OnDeserialization(object sender) { throw new PlatformNotSupportedException(); } @@ -612,7 +612,7 @@ private bool IsAsciiCasingSameAsInvariant // or not object refers to the same CultureInfo as the current instance. // //////////////////////////////////////////////////////////////////////// - public override bool Equals(Object obj) + public override bool Equals(object obj) { TextInfo that = obj as TextInfo; diff --git a/src/System.Private.CoreLib/shared/System/IAsyncResult.cs b/src/System.Private.CoreLib/shared/System/IAsyncResult.cs index 0abeaca5258..56ebcdb2f51 100644 --- a/src/System.Private.CoreLib/shared/System/IAsyncResult.cs +++ b/src/System.Private.CoreLib/shared/System/IAsyncResult.cs @@ -23,7 +23,7 @@ public interface IAsyncResult WaitHandle AsyncWaitHandle { get; } - Object AsyncState { get; } + object AsyncState { get; } bool CompletedSynchronously { get; } } diff --git a/src/System.Private.CoreLib/shared/System/IComparable.cs b/src/System.Private.CoreLib/shared/System/IComparable.cs index 72aeeb027c0..cf71953e255 100644 --- a/src/System.Private.CoreLib/shared/System/IComparable.cs +++ b/src/System.Private.CoreLib/shared/System/IComparable.cs @@ -18,7 +18,7 @@ public interface IComparable // if this is equal to object, or a value greater than zero // if this is greater than object. // - int CompareTo(Object obj); + int CompareTo(object obj); } // Generic version of IComparable. diff --git a/src/System.Private.CoreLib/shared/System/IConvertible.cs b/src/System.Private.CoreLib/shared/System/IConvertible.cs index 87351127f2f..7abd0c45c3a 100644 --- a/src/System.Private.CoreLib/shared/System/IConvertible.cs +++ b/src/System.Private.CoreLib/shared/System/IConvertible.cs @@ -54,10 +54,10 @@ public interface IConvertible ulong ToUInt64(IFormatProvider provider); float ToSingle(IFormatProvider provider); double ToDouble(IFormatProvider provider); - Decimal ToDecimal(IFormatProvider provider); + decimal ToDecimal(IFormatProvider provider); DateTime ToDateTime(IFormatProvider provider); - String ToString(IFormatProvider provider); - Object ToType(Type conversionType, IFormatProvider provider); + string ToString(IFormatProvider provider); + object ToType(Type conversionType, IFormatProvider provider); } } diff --git a/src/System.Private.CoreLib/shared/System/ICustomFormatter.cs b/src/System.Private.CoreLib/shared/System/ICustomFormatter.cs index 47340f30931..cd798b4a1e2 100644 --- a/src/System.Private.CoreLib/shared/System/ICustomFormatter.cs +++ b/src/System.Private.CoreLib/shared/System/ICustomFormatter.cs @@ -19,6 +19,6 @@ namespace System public interface ICustomFormatter { // Interface does not need to be marked with the serializable attribute - String Format(String format, Object arg, IFormatProvider formatProvider); + string Format(string format, object arg, IFormatProvider formatProvider); } } diff --git a/src/System.Private.CoreLib/shared/System/IFormatProvider.cs b/src/System.Private.CoreLib/shared/System/IFormatProvider.cs index 0c17354af30..9369b074f98 100644 --- a/src/System.Private.CoreLib/shared/System/IFormatProvider.cs +++ b/src/System.Private.CoreLib/shared/System/IFormatProvider.cs @@ -18,6 +18,6 @@ namespace System public interface IFormatProvider { // Interface does not need to be marked with the serializable attribute - Object GetFormat(Type formatType); + object GetFormat(Type formatType); } } diff --git a/src/System.Private.CoreLib/shared/System/IFormattable.cs b/src/System.Private.CoreLib/shared/System/IFormattable.cs index 1f2f7022ccb..b5ed9bb45b6 100644 --- a/src/System.Private.CoreLib/shared/System/IFormattable.cs +++ b/src/System.Private.CoreLib/shared/System/IFormattable.cs @@ -8,6 +8,6 @@ namespace System { public interface IFormattable { - String ToString(String format, IFormatProvider formatProvider); + string ToString(string format, IFormatProvider formatProvider); } } diff --git a/src/System.Private.CoreLib/shared/System/IO/BinaryWriter.cs b/src/System.Private.CoreLib/shared/System/IO/BinaryWriter.cs index ad1d31f5771..d1a333f419f 100644 --- a/src/System.Private.CoreLib/shared/System/IO/BinaryWriter.cs +++ b/src/System.Private.CoreLib/shared/System/IO/BinaryWriter.cs @@ -166,7 +166,7 @@ public virtual void Write(byte[] buffer, int index, int count) // public unsafe virtual void Write(char ch) { - if (Char.IsSurrogate(ch)) + if (char.IsSurrogate(ch)) throw new ArgumentException(SR.Arg_SurrogatesNotAllowedAsSingleChar); Debug.Assert(_encoding.GetMaxByteCount(1) <= 16, "_encoding.GetMaxByteCount(1) <= 16)"); @@ -223,7 +223,7 @@ public unsafe virtual void Write(double value) public virtual void Write(decimal value) { - Decimal.GetBytes(value, _buffer); + decimal.GetBytes(value, _buffer); OutStream.Write(_buffer, 0, 16); } @@ -325,7 +325,7 @@ public unsafe virtual void Write(float value) // 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) throw new ArgumentNullException(nameof(value)); diff --git a/src/System.Private.CoreLib/shared/System/IO/IOException.cs b/src/System.Private.CoreLib/shared/System/IO/IOException.cs index 89b25d51427..04e65320613 100644 --- a/src/System.Private.CoreLib/shared/System/IO/IOException.cs +++ b/src/System.Private.CoreLib/shared/System/IO/IOException.cs @@ -17,19 +17,19 @@ public IOException() HResult = HResults.COR_E_IO; } - public IOException(String message) + public IOException(string message) : base(message) { HResult = HResults.COR_E_IO; } - public IOException(String message, int hresult) + public IOException(string message, int hresult) : base(message) { HResult = hresult; } - public IOException(String message, Exception innerException) + public IOException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_IO; diff --git a/src/System.Private.CoreLib/shared/System/IO/MemoryStream.cs b/src/System.Private.CoreLib/shared/System/IO/MemoryStream.cs index 173917f6355..9bac0d818b1 100644 --- a/src/System.Private.CoreLib/shared/System/IO/MemoryStream.cs +++ b/src/System.Private.CoreLib/shared/System/IO/MemoryStream.cs @@ -393,7 +393,7 @@ public override int Read(Span buffer) return n; } - public override Task ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); @@ -722,7 +722,7 @@ public override void Write(ReadOnlySpan buffer) _position = i; } - public override Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); diff --git a/src/System.Private.CoreLib/shared/System/IO/Stream.cs b/src/System.Private.CoreLib/shared/System/IO/Stream.cs index 6a091f2d9e9..faeb69fb541 100644 --- a/src/System.Private.CoreLib/shared/System/IO/Stream.cs +++ b/src/System.Private.CoreLib/shared/System/IO/Stream.cs @@ -253,13 +253,13 @@ protected virtual WaitHandle CreateWaitHandle() return new ManualResetEvent(false); } - public virtual IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) + public virtual IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { return BeginReadInternal(buffer, offset, count, callback, state, serializeAsynchronously: false, apm: true); } 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) { if (!CanRead) throw Error.GetReadNotSupported(); @@ -415,13 +415,13 @@ private struct ReadWriteParameters // struct for arguments to Read and Write cal - public virtual IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) + public virtual IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { return BeginWriteInternal(buffer, offset, count, callback, state, serializeAsynchronously: false, apm: true); } 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) { if (!CanWrite) throw Error.GetWriteNotSupported(); @@ -792,7 +792,7 @@ protected virtual void ObjectInvariant() { } - internal IAsyncResult BlockingBeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) + internal IAsyncResult BlockingBeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { // To avoid a race with a stream's position pointer & generating conditions // with internal buffer indexes in our own streams that @@ -824,7 +824,7 @@ internal static int BlockingEndRead(IAsyncResult asyncResult) return SynchronousAsyncResult.EndRead(asyncResult); } - internal IAsyncResult BlockingBeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) + internal IAsyncResult BlockingBeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { // To avoid a race condition with a stream's position pointer & generating conditions // with internal buffer indexes in our own streams that @@ -910,7 +910,7 @@ public override Task FlushAsync(CancellationToken cancellationToken) Task.CompletedTask; } - public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) + public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { if (!CanRead) throw Error.GetReadNotSupported(); @@ -925,7 +925,7 @@ public override int EndRead(IAsyncResult asyncResult) return BlockingEndRead(asyncResult); } - public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) + public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { if (!CanWrite) throw Error.GetWriteNotSupported(); @@ -1005,7 +1005,7 @@ public override void SetLength(long length) /// Used as the IAsyncResult object when using asynchronous IO methods on the base Stream class. private sealed class SynchronousAsyncResult : IAsyncResult { - private readonly Object _stateObject; + private readonly object _stateObject; private readonly bool _isWrite; private ManualResetEvent _waitHandle; private ExceptionDispatchInfo _exceptionInfo; @@ -1013,20 +1013,20 @@ private sealed class SynchronousAsyncResult : IAsyncResult private bool _endXxxCalled; private int _bytesRead; - internal SynchronousAsyncResult(int bytesRead, Object asyncStateObject) + internal SynchronousAsyncResult(int 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; @@ -1047,7 +1047,7 @@ public WaitHandle AsyncWaitHandle } } - public Object AsyncState + public object AsyncState { get { return _stateObject; } } @@ -1226,7 +1226,7 @@ public override int ReadByte() return _stream.ReadByte(); } - public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) + public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { #if CORERT throw new NotImplementedException(); // TODO: https://github.com/dotnet/corert/issues/3251 @@ -1287,7 +1287,7 @@ public override void WriteByte(byte b) _stream.WriteByte(b); } - public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) + public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { #if CORERT throw new NotImplementedException(); // TODO: https://github.com/dotnet/corert/issues/3251 diff --git a/src/System.Private.CoreLib/shared/System/IO/StreamReader.cs b/src/System.Private.CoreLib/shared/System/IO/StreamReader.cs index ea30541f5aa..5c3cc9157d1 100644 --- a/src/System.Private.CoreLib/shared/System/IO/StreamReader.cs +++ b/src/System.Private.CoreLib/shared/System/IO/StreamReader.cs @@ -1059,7 +1059,7 @@ internal override async ValueTask ReadAsyncInternal(Memory buffer, Ca // data read in, let's try writing directly to the user's buffer. bool readToUserBuffer = false; - Byte[] tmpByteBuffer = _byteBuffer; + byte[] tmpByteBuffer = _byteBuffer; Stream tmpStream = _stream; int count = buffer.Length; @@ -1290,7 +1290,7 @@ private async Task ReadBufferAsync() { _charLen = 0; _charPos = 0; - Byte[] tmpByteBuffer = _byteBuffer; + byte[] tmpByteBuffer = _byteBuffer; Stream tmpStream = _stream; if (!_checkPreamble) diff --git a/src/System.Private.CoreLib/shared/System/IO/StreamWriter.cs b/src/System.Private.CoreLib/shared/System/IO/StreamWriter.cs index 06d94d23850..b510b6b2877 100644 --- a/src/System.Private.CoreLib/shared/System/IO/StreamWriter.cs +++ b/src/System.Private.CoreLib/shared/System/IO/StreamWriter.cs @@ -965,7 +965,7 @@ private bool HaveWrittenPreamble_Prop // to ensure performant access inside the state machine that corresponds this async method. private static async Task FlushAsyncInternal(StreamWriter _this, bool flushStream, bool flushEncoder, char[] charBuffer, int charPos, bool haveWrittenPreamble, - Encoding encoding, Encoder encoder, Byte[] byteBuffer, Stream stream, CancellationToken cancellationToken) + Encoding encoding, Encoder encoder, byte[] byteBuffer, Stream stream, CancellationToken cancellationToken) { if (!haveWrittenPreamble) { diff --git a/src/System.Private.CoreLib/shared/System/IO/TextReader.cs b/src/System.Private.CoreLib/shared/System/IO/TextReader.cs index 98e1e64cd5f..bb5b142bde4 100644 --- a/src/System.Private.CoreLib/shared/System/IO/TextReader.cs +++ b/src/System.Private.CoreLib/shared/System/IO/TextReader.cs @@ -207,7 +207,7 @@ public virtual string ReadLine() #region Task based Async APIs public virtual Task ReadLineAsync() { - return Task.Factory.StartNew(state => + return Task.Factory.StartNew(state => { return ((TextReader)state).ReadLine(); }, diff --git a/src/System.Private.CoreLib/shared/System/IO/TextWriter.cs b/src/System.Private.CoreLib/shared/System/IO/TextWriter.cs index 0acb4d18cf6..4ab3c708cc6 100644 --- a/src/System.Private.CoreLib/shared/System/IO/TextWriter.cs +++ b/src/System.Private.CoreLib/shared/System/IO/TextWriter.cs @@ -193,7 +193,7 @@ public virtual void Write(bool value) // Writes the text representation of an integer to the text stream. The // text representation of the given value is produced by calling the - // Int32.ToString() method. + // int.ToString() method. // public virtual void Write(int value) { @@ -202,7 +202,7 @@ public virtual void Write(int value) // Writes the text representation of an integer to the text stream. The // text representation of the given value is produced by calling the - // UInt32.ToString() method. + // uint.ToString() method. // [CLSCompliant(false)] public virtual void Write(uint value) @@ -212,7 +212,7 @@ public virtual void Write(uint value) // Writes the text representation of a long to the text stream. The // text representation of the given value is produced by calling the - // Int64.ToString() method. + // long.ToString() method. // public virtual void Write(long value) { @@ -221,7 +221,7 @@ public virtual void Write(long value) // Writes the text representation of an unsigned long to the text // stream. The text representation of the given value is produced - // by calling the UInt64.ToString() method. + // by calling the ulong.ToString() method. // [CLSCompliant(false)] public virtual void Write(ulong value) @@ -299,7 +299,7 @@ public virtual void Write(StringBuilder value) } // Writes out a formatted string. Uses the same semantics as - // String.Format. + // string.Format. // public virtual void Write(string format, object arg0) { @@ -307,7 +307,7 @@ public virtual void Write(string format, object arg0) } // Writes out a formatted string. Uses the same semantics as - // String.Format. + // string.Format. // public virtual void Write(string format, object arg0, object arg1) { @@ -315,7 +315,7 @@ public virtual void Write(string format, object arg0, object arg1) } // Writes out a formatted string. Uses the same semantics as - // String.Format. + // string.Format. // public virtual void Write(string format, object arg0, object arg1, object arg2) { @@ -323,7 +323,7 @@ public virtual void Write(string format, object arg0, object arg1, object arg2) } // Writes out a formatted string. Uses the same semantics as - // String.Format. + // string.Format. // public virtual void Write(string format, params object[] arg) { @@ -498,7 +498,7 @@ public virtual void WriteLine(object value) } // Writes out a formatted string and a new line. Uses the same - // semantics as String.Format. + // semantics as string.Format. // public virtual void WriteLine(string format, object arg0) { @@ -506,7 +506,7 @@ public virtual void WriteLine(string format, object arg0) } // Writes out a formatted string and a new line. Uses the same - // semantics as String.Format. + // semantics as string.Format. // public virtual void WriteLine(string format, object arg0, object arg1) { @@ -514,7 +514,7 @@ public virtual void WriteLine(string format, object arg0, object arg1) } // Writes out a formatted string and a new line. Uses the same - // semantics as String.Format. + // semantics as string.Format. // public virtual void WriteLine(string format, object arg0, object arg1, object arg2) { @@ -522,7 +522,7 @@ public virtual void WriteLine(string format, object arg0, object arg1, object ar } // Writes out a formatted string and a new line. Uses the same - // semantics as String.Format. + // semantics as string.Format. // public virtual void WriteLine(string format, params object[] arg) { @@ -809,7 +809,7 @@ protected override void Dispose(bool disposing) public override void Write(double value) => _out.Write(value); [MethodImpl(MethodImplOptions.Synchronized)] - public override void Write(Decimal value) => _out.Write(value); + public override void Write(decimal value) => _out.Write(value); [MethodImpl(MethodImplOptions.Synchronized)] public override void Write(string value) => _out.Write(value); diff --git a/src/System.Private.CoreLib/shared/System/IO/UnmanagedMemoryStream.cs b/src/System.Private.CoreLib/shared/System/IO/UnmanagedMemoryStream.cs index 70770e4a28c..d4af4cfee37 100644 --- a/src/System.Private.CoreLib/shared/System/IO/UnmanagedMemoryStream.cs +++ b/src/System.Private.CoreLib/shared/System/IO/UnmanagedMemoryStream.cs @@ -47,7 +47,7 @@ public class UnmanagedMemoryStream : Stream private long _offset; private FileAccess _access; private bool _isOpen; - private Task _lastReadTask; // The last successful task returned from ReadAsync + private Task _lastReadTask; // The last successful task returned from ReadAsync /// /// Creates a closed stream. @@ -456,7 +456,7 @@ internal int ReadCore(Span buffer) /// Maximum number of bytes to read. /// Token that can be used to cancel this operation. /// Task that can be used to access the number of bytes actually read. - public override Task ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); @@ -468,18 +468,18 @@ public override Task ReadAsync(Byte[] buffer, Int32 offset, Int32 count, throw new ArgumentException(SR.Argument_InvalidOffLen); if (cancellationToken.IsCancellationRequested) - return Task.FromCanceled(cancellationToken); + return Task.FromCanceled(cancellationToken); try { - Int32 n = Read(buffer, offset, count); - Task t = _lastReadTask; + int n = Read(buffer, offset, count); + Task t = _lastReadTask; return (t != null && t.Result == n) ? t : (_lastReadTask = Task.FromResult(n)); } catch (Exception ex) { Debug.Assert(!(ex is OperationCanceledException)); - return Task.FromException(ex); + return Task.FromException(ex); } } @@ -752,7 +752,7 @@ internal unsafe void WriteCore(ReadOnlySpan buffer) /// Number of bytes to write. /// Token that can be used to cancel the operation. /// Task that can be awaited - public override Task WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); diff --git a/src/System.Private.CoreLib/shared/System/IO/UnmanagedMemoryStreamWrapper.cs b/src/System.Private.CoreLib/shared/System/IO/UnmanagedMemoryStreamWrapper.cs index 104f5590a8b..9a598951ee8 100644 --- a/src/System.Private.CoreLib/shared/System/IO/UnmanagedMemoryStreamWrapper.cs +++ b/src/System.Private.CoreLib/shared/System/IO/UnmanagedMemoryStreamWrapper.cs @@ -160,7 +160,7 @@ public unsafe override void WriteTo(Stream stream) stream.Write(buffer, 0, buffer.Length); } - public override void SetLength(Int64 value) + public override void SetLength(long 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. @@ -169,7 +169,7 @@ public override void SetLength(Int64 value) } - public override Task CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken) + public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) { // The parameter checks must be in sync with the base version: if (destination == null) @@ -201,7 +201,7 @@ public override Task FlushAsync(CancellationToken cancellationToken) } - public override Task ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { return _unmanagedStream.ReadAsync(buffer, offset, count, cancellationToken); } @@ -212,7 +212,7 @@ public override ValueTask ReadAsync(Memory buffer, CancellationToken } - public override Task WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { return _unmanagedStream.WriteAsync(buffer, offset, count, cancellationToken); } diff --git a/src/System.Private.CoreLib/shared/System/IndexOutOfRangeException.cs b/src/System.Private.CoreLib/shared/System/IndexOutOfRangeException.cs index b6d93ef5683..aadc942314b 100644 --- a/src/System.Private.CoreLib/shared/System/IndexOutOfRangeException.cs +++ b/src/System.Private.CoreLib/shared/System/IndexOutOfRangeException.cs @@ -25,13 +25,13 @@ public IndexOutOfRangeException() HResult = HResults.COR_E_INDEXOUTOFRANGE; } - public IndexOutOfRangeException(String message) + public IndexOutOfRangeException(string message) : base(message) { HResult = HResults.COR_E_INDEXOUTOFRANGE; } - public IndexOutOfRangeException(String message, Exception innerException) + public IndexOutOfRangeException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_INDEXOUTOFRANGE; diff --git a/src/System.Private.CoreLib/shared/System/InsufficientExecutionStackException.cs b/src/System.Private.CoreLib/shared/System/InsufficientExecutionStackException.cs index 4822028f854..4c4bf242e18 100644 --- a/src/System.Private.CoreLib/shared/System/InsufficientExecutionStackException.cs +++ b/src/System.Private.CoreLib/shared/System/InsufficientExecutionStackException.cs @@ -16,13 +16,13 @@ public InsufficientExecutionStackException() HResult = HResults.COR_E_INSUFFICIENTEXECUTIONSTACK; } - public InsufficientExecutionStackException(String message) + public InsufficientExecutionStackException(string message) : base(message) { HResult = HResults.COR_E_INSUFFICIENTEXECUTIONSTACK; } - public InsufficientExecutionStackException(String message, Exception innerException) + public InsufficientExecutionStackException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_INSUFFICIENTEXECUTIONSTACK; diff --git a/src/System.Private.CoreLib/shared/System/InsufficientMemoryException.cs b/src/System.Private.CoreLib/shared/System/InsufficientMemoryException.cs index 4e90714c926..68377540e6d 100644 --- a/src/System.Private.CoreLib/shared/System/InsufficientMemoryException.cs +++ b/src/System.Private.CoreLib/shared/System/InsufficientMemoryException.cs @@ -30,13 +30,13 @@ public sealed class InsufficientMemoryException : OutOfMemoryException HResult = HResults.COR_E_INSUFFICIENTMEMORY; } - public InsufficientMemoryException(String message) + public InsufficientMemoryException(string message) : base(message) { HResult = HResults.COR_E_INSUFFICIENTMEMORY; } - public InsufficientMemoryException(String message, Exception innerException) + public InsufficientMemoryException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_INSUFFICIENTMEMORY; diff --git a/src/System.Private.CoreLib/shared/System/Int16.cs b/src/System.Private.CoreLib/shared/System/Int16.cs index fecc87e9fe6..2993337a74e 100644 --- a/src/System.Private.CoreLib/shared/System/Int16.cs +++ b/src/System.Private.CoreLib/shared/System/Int16.cs @@ -12,7 +12,7 @@ namespace System [Serializable] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] - public struct Int16 : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable + public struct Int16 : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable { private short m_value; // Do not rename (binary serialization) @@ -25,37 +25,37 @@ public struct Int16 : IComparable, IConvertible, IFormattable, IComparable 0 && (format[0] == 'X' || format[0] == 'x')) { @@ -103,26 +103,26 @@ public bool TryFormat(Span destination, out int charsWritten, ReadOnlySpan return Number.TryFormatInt32(m_value, format, provider, destination, out charsWritten); } - public static short Parse(String s) + public static short Parse(string s) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan)s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } - public static short Parse(String s, NumberStyles style) + public static short Parse(string s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan)s, style, NumberFormatInfo.CurrentInfo); } - public static short Parse(String s, IFormatProvider provider) + public static short Parse(string s, IFormatProvider provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan)s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); } - public static short Parse(String s, NumberStyles style, IFormatProvider provider) + public static short Parse(string s, NumberStyles style, IFormatProvider provider) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); @@ -151,7 +151,7 @@ private static short Parse(ReadOnlySpan s, NumberStyles style, NumberForma // for negative numbers if ((style & NumberStyles.AllowHexSpecifier) != 0) { // We are parsing a hexadecimal number - if ((i < 0) || (i > UInt16.MaxValue)) + if ((i < 0) || (i > ushort.MaxValue)) { throw new OverflowException(SR.Overflow_Int16); } @@ -162,7 +162,7 @@ private static short Parse(ReadOnlySpan s, NumberStyles style, NumberForma return (short)i; } - public static bool TryParse(String s, out Int16 result) + public static bool TryParse(string s, out short result) { if (s == null) { @@ -178,7 +178,7 @@ public static bool TryParse(ReadOnlySpan s, out short 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 short result) { NumberFormatInfo.ValidateParseStyleInteger(style); @@ -197,7 +197,7 @@ public static bool TryParse(ReadOnlySpan s, NumberStyles style, IFormatPro return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result); } - private static bool TryParse(ReadOnlySpan s, NumberStyles style, NumberFormatInfo info, out Int16 result) + private static bool TryParse(ReadOnlySpan s, NumberStyles style, NumberFormatInfo info, out short result) { result = 0; int i; @@ -210,11 +210,11 @@ private static bool TryParse(ReadOnlySpan s, NumberStyles style, NumberFor // for negative numbers if ((style & NumberStyles.AllowHexSpecifier) != 0) { // We are parsing a hexadecimal number - if ((i < 0) || i > UInt16.MaxValue) + if ((i < 0) || i > ushort.MaxValue) { return false; } - result = (Int16)i; + result = (short)i; return true; } @@ -222,7 +222,7 @@ private static bool TryParse(ReadOnlySpan s, NumberStyles style, NumberFor { return false; } - result = (Int16)i; + result = (short)i; return true; } @@ -296,7 +296,7 @@ float IConvertible.ToSingle(IFormatProvider provider) return Convert.ToDouble(m_value); } - Decimal IConvertible.ToDecimal(IFormatProvider provider) + decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } @@ -306,7 +306,7 @@ DateTime IConvertible.ToDateTime(IFormatProvider provider) throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Int16", "DateTime")); } - 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/System.Private.CoreLib/shared/System/Int32.cs b/src/System.Private.CoreLib/shared/System/Int32.cs index b573e950e46..5c40812c0aa 100644 --- a/src/System.Private.CoreLib/shared/System/Int32.cs +++ b/src/System.Private.CoreLib/shared/System/Int32.cs @@ -12,7 +12,7 @@ namespace System [Serializable] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] - public struct Int32 : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable + public struct Int32 : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable { private int m_value; // Do not rename (binary serialization) @@ -28,13 +28,13 @@ public struct Int32 : IComparable, IConvertible, IFormattable, IComparable MaxValue. @@ -55,17 +55,17 @@ public int CompareTo(int value) return 0; } - public override bool Equals(Object obj) + public override bool Equals(object obj) { - if (!(obj is Int32)) + if (!(obj is int)) { return false; } - return m_value == ((Int32)obj).m_value; + return m_value == ((int)obj).m_value; } [NonVersionable] - public bool Equals(Int32 obj) + public bool Equals(int obj) { return m_value == obj; } @@ -76,22 +76,22 @@ public override int GetHashCode() return m_value; } - public override String ToString() + public override string ToString() { return Number.FormatInt32(m_value, null, null); } - public String ToString(String format) + public string ToString(string format) { return Number.FormatInt32(m_value, format, null); } - public String ToString(IFormatProvider provider) + public string ToString(IFormatProvider provider) { return Number.FormatInt32(m_value, null, provider); } - public String ToString(String format, IFormatProvider provider) + public string ToString(string format, IFormatProvider provider) { return Number.FormatInt32(m_value, format, provider); } @@ -101,13 +101,13 @@ public bool TryFormat(Span destination, out int charsWritten, ReadOnlySpan return Number.TryFormatInt32(m_value, format, provider, destination, out charsWritten); } - public static int Parse(String s) + public static int Parse(string s) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } - public static int Parse(String s, NumberStyles style) + public static int Parse(string s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); @@ -118,7 +118,7 @@ public static int Parse(String s, NumberStyles style) // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. // - public static int Parse(String s, IFormatProvider provider) + public static int Parse(string s, IFormatProvider provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); @@ -128,7 +128,7 @@ public static int Parse(String s, IFormatProvider provider) // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. // - public static int Parse(String s, NumberStyles style, IFormatProvider provider) + public static int Parse(string s, NumberStyles style, IFormatProvider provider) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); @@ -144,7 +144,7 @@ public static int Parse(ReadOnlySpan s, NumberStyles style = NumberStyles. // Parses an integer from a String. Returns false rather // than throwing exceptin if input is invalid // - public static bool TryParse(String s, out Int32 result) + public static bool TryParse(string s, out int result) { if (s == null) { @@ -163,7 +163,7 @@ public static bool TryParse(ReadOnlySpan s, out int result) // Parses an integer from a String in the given style. Returns false rather // than throwing exceptin if input is invalid // - public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out Int32 result) + public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, out int result) { NumberFormatInfo.ValidateParseStyleInteger(style); @@ -251,7 +251,7 @@ float IConvertible.ToSingle(IFormatProvider provider) return Convert.ToDouble(m_value); } - Decimal IConvertible.ToDecimal(IFormatProvider provider) + decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } @@ -261,7 +261,7 @@ DateTime IConvertible.ToDateTime(IFormatProvider provider) throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Int32", "DateTime")); } - 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/System.Private.CoreLib/shared/System/Int64.cs b/src/System.Private.CoreLib/shared/System/Int64.cs index 0bcca87309b..29198781d7a 100644 --- a/src/System.Private.CoreLib/shared/System/Int64.cs +++ b/src/System.Private.CoreLib/shared/System/Int64.cs @@ -12,7 +12,7 @@ namespace System [Serializable] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] - public struct Int64 : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable + public struct Int64 : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable { private long m_value; // Do not rename (binary serialization) @@ -25,13 +25,13 @@ public struct Int64 : IComparable, IConvertible, IFormattable, IComparable> 32)); } - public override String ToString() + public override string ToString() { return Number.FormatInt64(m_value, null, null); } - public String ToString(IFormatProvider provider) + public string ToString(IFormatProvider provider) { return Number.FormatInt64(m_value, null, provider); } - public String ToString(String format) + public string ToString(string format) { return Number.FormatInt64(m_value, format, null); } - public String ToString(String format, IFormatProvider provider) + public string ToString(string format, IFormatProvider provider) { return Number.FormatInt64(m_value, format, provider); } @@ -98,20 +98,20 @@ public bool TryFormat(Span destination, out int charsWritten, ReadOnlySpan return Number.TryFormatInt64(m_value, format, provider, destination, out charsWritten); } - public static long Parse(String s) + public static long Parse(string s) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseInt64(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } - public static long Parse(String s, NumberStyles style) + public static long Parse(string s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseInt64(s, style, NumberFormatInfo.CurrentInfo); } - public static long Parse(String s, IFormatProvider provider) + public static long Parse(string s, IFormatProvider provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseInt64(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); @@ -122,7 +122,7 @@ public static long Parse(String s, IFormatProvider provider) // 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); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); @@ -135,7 +135,7 @@ public static long Parse(ReadOnlySpan s, NumberStyles style = NumberStyles return Number.ParseInt64(s, style, NumberFormatInfo.GetInstance(provider)); } - public static Boolean TryParse(String s, out Int64 result) + public static bool TryParse(string s, out long result) { if (s == null) { @@ -151,7 +151,7 @@ public static bool TryParse(ReadOnlySpan s, out long 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 bool TryParse(string s, NumberStyles style, IFormatProvider provider, out long result) { NumberFormatInfo.ValidateParseStyleInteger(style); @@ -239,7 +239,7 @@ float IConvertible.ToSingle(IFormatProvider provider) return Convert.ToDouble(m_value); } - Decimal IConvertible.ToDecimal(IFormatProvider provider) + decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } @@ -249,7 +249,7 @@ DateTime IConvertible.ToDateTime(IFormatProvider provider) throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Int64", "DateTime")); } - 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/System.Private.CoreLib/shared/System/IntPtr.cs b/src/System.Private.CoreLib/shared/System/IntPtr.cs index 44638ddd8ee..c5419a96e02 100644 --- a/src/System.Private.CoreLib/shared/System/IntPtr.cs +++ b/src/System.Private.CoreLib/shared/System/IntPtr.cs @@ -72,7 +72,7 @@ unsafe void ISerializable.GetObjectData(SerializationInfo info, StreamingContext info.AddValue("value", ToInt64()); } - public unsafe override bool Equals(Object obj) + public unsafe override bool Equals(object obj) { if (obj is IntPtr) { diff --git a/src/System.Private.CoreLib/shared/System/InvalidCastException.cs b/src/System.Private.CoreLib/shared/System/InvalidCastException.cs index 055643278ab..cb6036aeb48 100644 --- a/src/System.Private.CoreLib/shared/System/InvalidCastException.cs +++ b/src/System.Private.CoreLib/shared/System/InvalidCastException.cs @@ -22,19 +22,19 @@ public InvalidCastException() HResult = HResults.COR_E_INVALIDCAST; } - public InvalidCastException(String message) + public InvalidCastException(string message) : base(message) { HResult = HResults.COR_E_INVALIDCAST; } - public InvalidCastException(String message, Exception innerException) + public InvalidCastException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_INVALIDCAST; } - public InvalidCastException(String message, int errorCode) + public InvalidCastException(string message, int errorCode) : base(message) { HResult = errorCode; diff --git a/src/System.Private.CoreLib/shared/System/InvalidOperationException.cs b/src/System.Private.CoreLib/shared/System/InvalidOperationException.cs index 62c222af401..9fffbec4337 100644 --- a/src/System.Private.CoreLib/shared/System/InvalidOperationException.cs +++ b/src/System.Private.CoreLib/shared/System/InvalidOperationException.cs @@ -26,13 +26,13 @@ public InvalidOperationException() HResult = HResults.COR_E_INVALIDOPERATION; } - public InvalidOperationException(String message) + public InvalidOperationException(string message) : base(message) { HResult = HResults.COR_E_INVALIDOPERATION; } - public InvalidOperationException(String message, Exception innerException) + public InvalidOperationException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_INVALIDOPERATION; diff --git a/src/System.Private.CoreLib/shared/System/InvalidProgramException.cs b/src/System.Private.CoreLib/shared/System/InvalidProgramException.cs index c8047c548b3..62a14f91168 100644 --- a/src/System.Private.CoreLib/shared/System/InvalidProgramException.cs +++ b/src/System.Private.CoreLib/shared/System/InvalidProgramException.cs @@ -25,13 +25,13 @@ public InvalidProgramException() HResult = HResults.COR_E_INVALIDPROGRAM; } - public InvalidProgramException(String message) + public InvalidProgramException(string message) : base(message) { HResult = HResults.COR_E_INVALIDPROGRAM; } - public InvalidProgramException(String message, Exception inner) + public InvalidProgramException(string message, Exception inner) : base(message, inner) { HResult = HResults.COR_E_INVALIDPROGRAM; diff --git a/src/System.Private.CoreLib/shared/System/InvalidTimeZoneException.cs b/src/System.Private.CoreLib/shared/System/InvalidTimeZoneException.cs index 25b155e8d10..1bbb7e067bc 100644 --- a/src/System.Private.CoreLib/shared/System/InvalidTimeZoneException.cs +++ b/src/System.Private.CoreLib/shared/System/InvalidTimeZoneException.cs @@ -14,12 +14,12 @@ public InvalidTimeZoneException() { } - public InvalidTimeZoneException(String message) + public InvalidTimeZoneException(string message) : base(message) { } - public InvalidTimeZoneException(String message, Exception innerException) + public InvalidTimeZoneException(string message, Exception innerException) : base(message, innerException) { } diff --git a/src/System.Private.CoreLib/shared/System/MemberAccessException.cs b/src/System.Private.CoreLib/shared/System/MemberAccessException.cs index dfea52dbed5..0cf1e0fbebe 100644 --- a/src/System.Private.CoreLib/shared/System/MemberAccessException.cs +++ b/src/System.Private.CoreLib/shared/System/MemberAccessException.cs @@ -31,13 +31,13 @@ public MemberAccessException() // message, its HRESULT set to COR_E_ACCESS, // and its ExceptionInfo reference set to null. // - public MemberAccessException(String message) + public MemberAccessException(string message) : base(message) { HResult = HResults.COR_E_MEMBERACCESS; } - public MemberAccessException(String message, Exception inner) + public MemberAccessException(string message, Exception inner) : base(message, inner) { HResult = HResults.COR_E_MEMBERACCESS; diff --git a/src/System.Private.CoreLib/shared/System/MethodAccessException.cs b/src/System.Private.CoreLib/shared/System/MethodAccessException.cs index 1ca0297b943..f329334b23a 100644 --- a/src/System.Private.CoreLib/shared/System/MethodAccessException.cs +++ b/src/System.Private.CoreLib/shared/System/MethodAccessException.cs @@ -23,13 +23,13 @@ public MethodAccessException() HResult = HResults.COR_E_METHODACCESS; } - public MethodAccessException(String message) + public MethodAccessException(string message) : base(message) { HResult = HResults.COR_E_METHODACCESS; } - public MethodAccessException(String message, Exception inner) + public MethodAccessException(string message, Exception inner) : base(message, inner) { HResult = HResults.COR_E_METHODACCESS; diff --git a/src/System.Private.CoreLib/shared/System/MissingFieldException.cs b/src/System.Private.CoreLib/shared/System/MissingFieldException.cs index 38a8cc7eab1..ba66bed0cd3 100644 --- a/src/System.Private.CoreLib/shared/System/MissingFieldException.cs +++ b/src/System.Private.CoreLib/shared/System/MissingFieldException.cs @@ -16,13 +16,13 @@ public MissingFieldException() HResult = HResults.COR_E_MISSINGFIELD; } - public MissingFieldException(String message) + public MissingFieldException(string message) : base(message) { HResult = HResults.COR_E_MISSINGFIELD; } - public MissingFieldException(String message, Exception inner) + public MissingFieldException(string message, Exception inner) : base(message, inner) { HResult = HResults.COR_E_MISSINGFIELD; diff --git a/src/System.Private.CoreLib/shared/System/MissingMemberException.cs b/src/System.Private.CoreLib/shared/System/MissingMemberException.cs index 36f6468a472..a3da06017bf 100644 --- a/src/System.Private.CoreLib/shared/System/MissingMemberException.cs +++ b/src/System.Private.CoreLib/shared/System/MissingMemberException.cs @@ -16,13 +16,13 @@ public MissingMemberException() HResult = HResults.COR_E_MISSINGMEMBER; } - public MissingMemberException(String message) + public MissingMemberException(string message) : base(message) { HResult = HResults.COR_E_MISSINGMEMBER; } - public MissingMemberException(String message, Exception inner) + public MissingMemberException(string message, Exception inner) : base(message, inner) { HResult = HResults.COR_E_MISSINGMEMBER; diff --git a/src/System.Private.CoreLib/shared/System/MulticastNotSupportedException.cs b/src/System.Private.CoreLib/shared/System/MulticastNotSupportedException.cs index cc6c77023e7..cb07ac7d099 100644 --- a/src/System.Private.CoreLib/shared/System/MulticastNotSupportedException.cs +++ b/src/System.Private.CoreLib/shared/System/MulticastNotSupportedException.cs @@ -21,13 +21,13 @@ public MulticastNotSupportedException() HResult = HResults.COR_E_MULTICASTNOTSUPPORTED; } - public MulticastNotSupportedException(String message) + public MulticastNotSupportedException(string message) : base(message) { HResult = HResults.COR_E_MULTICASTNOTSUPPORTED; } - public MulticastNotSupportedException(String message, Exception inner) + public MulticastNotSupportedException(string message, Exception inner) : base(message, inner) { HResult = HResults.COR_E_MULTICASTNOTSUPPORTED; diff --git a/src/System.Private.CoreLib/shared/System/NotImplementedException.cs b/src/System.Private.CoreLib/shared/System/NotImplementedException.cs index 1a3b6afcd47..e5f378fed39 100644 --- a/src/System.Private.CoreLib/shared/System/NotImplementedException.cs +++ b/src/System.Private.CoreLib/shared/System/NotImplementedException.cs @@ -25,12 +25,12 @@ public NotImplementedException() { HResult = HResults.E_NOTIMPL; } - public NotImplementedException(String message) + public NotImplementedException(string message) : base(message) { HResult = HResults.E_NOTIMPL; } - public NotImplementedException(String message, Exception inner) + public NotImplementedException(string message, Exception inner) : base(message, inner) { HResult = HResults.E_NOTIMPL; diff --git a/src/System.Private.CoreLib/shared/System/NotSupportedException.cs b/src/System.Private.CoreLib/shared/System/NotSupportedException.cs index 3180bc28372..e3191ea13e5 100644 --- a/src/System.Private.CoreLib/shared/System/NotSupportedException.cs +++ b/src/System.Private.CoreLib/shared/System/NotSupportedException.cs @@ -25,13 +25,13 @@ public NotSupportedException() HResult = HResults.COR_E_NOTSUPPORTED; } - public NotSupportedException(String message) + public NotSupportedException(string message) : base(message) { HResult = HResults.COR_E_NOTSUPPORTED; } - public NotSupportedException(String message, Exception innerException) + public NotSupportedException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_NOTSUPPORTED; diff --git a/src/System.Private.CoreLib/shared/System/NullReferenceException.cs b/src/System.Private.CoreLib/shared/System/NullReferenceException.cs index c2e722470cd..cfbc0fb78e8 100644 --- a/src/System.Private.CoreLib/shared/System/NullReferenceException.cs +++ b/src/System.Private.CoreLib/shared/System/NullReferenceException.cs @@ -25,13 +25,13 @@ public NullReferenceException() HResult = HResults.COR_E_NULLREFERENCE; } - public NullReferenceException(String message) + public NullReferenceException(string message) : base(message) { HResult = HResults.COR_E_NULLREFERENCE; } - public NullReferenceException(String message, Exception innerException) + public NullReferenceException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_NULLREFERENCE; diff --git a/src/System.Private.CoreLib/shared/System/Nullable.cs b/src/System.Private.CoreLib/shared/System/Nullable.cs index 73ad6056c29..3c1cbd51013 100644 --- a/src/System.Private.CoreLib/shared/System/Nullable.cs +++ b/src/System.Private.CoreLib/shared/System/Nullable.cs @@ -141,7 +141,7 @@ public static Type GetUnderlyingType(Type nullableType) { // instantiated generic type only Type genericType = nullableType.GetGenericTypeDefinition(); - if (Object.ReferenceEquals(genericType, typeof(Nullable<>))) + if (object.ReferenceEquals(genericType, typeof(Nullable<>))) { return nullableType.GetGenericArguments()[0]; } diff --git a/src/System.Private.CoreLib/shared/System/Numerics/ConstantHelper.cs b/src/System.Private.CoreLib/shared/System/Numerics/ConstantHelper.cs index ea32ed3803f..3fb3086b2df 100644 --- a/src/System.Private.CoreLib/shared/System/Numerics/ConstantHelper.cs +++ b/src/System.Private.CoreLib/shared/System/Numerics/ConstantHelper.cs @@ -9,131 +9,131 @@ namespace System.Numerics internal class ConstantHelper { [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static Byte GetByteWithAllBitsSet() + public static byte GetByteWithAllBitsSet() { - Byte value = 0; + byte value = 0; unsafe { unchecked { - *((Byte*)&value) = (Byte)0xff; + *((byte*)&value) = (byte)0xff; } } return value; } [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static SByte GetSByteWithAllBitsSet() + public static sbyte GetSByteWithAllBitsSet() { - SByte value = 0; + sbyte value = 0; unsafe { unchecked { - *((SByte*)&value) = (SByte)0xff; + *((sbyte*)&value) = (sbyte)0xff; } } return value; } [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static UInt16 GetUInt16WithAllBitsSet() + public static ushort GetUInt16WithAllBitsSet() { - UInt16 value = 0; + ushort value = 0; unsafe { unchecked { - *((UInt16*)&value) = (UInt16)0xffff; + *((ushort*)&value) = (ushort)0xffff; } } return value; } [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static Int16 GetInt16WithAllBitsSet() + public static short GetInt16WithAllBitsSet() { - Int16 value = 0; + short value = 0; unsafe { unchecked { - *((Int16*)&value) = (Int16)0xffff; + *((short*)&value) = (short)0xffff; } } return value; } [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static UInt32 GetUInt32WithAllBitsSet() + public static uint GetUInt32WithAllBitsSet() { - UInt32 value = 0; + uint value = 0; unsafe { unchecked { - *((UInt32*)&value) = (UInt32)0xffffffff; + *((uint*)&value) = (uint)0xffffffff; } } return value; } [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static Int32 GetInt32WithAllBitsSet() + public static int GetInt32WithAllBitsSet() { - Int32 value = 0; + int value = 0; unsafe { unchecked { - *((Int32*)&value) = (Int32)0xffffffff; + *((int*)&value) = (int)0xffffffff; } } return value; } [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static UInt64 GetUInt64WithAllBitsSet() + public static ulong GetUInt64WithAllBitsSet() { - UInt64 value = 0; + ulong value = 0; unsafe { unchecked { - *((UInt64*)&value) = (UInt64)0xffffffffffffffff; + *((ulong*)&value) = (ulong)0xffffffffffffffff; } } return value; } [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static Int64 GetInt64WithAllBitsSet() + public static long GetInt64WithAllBitsSet() { - Int64 value = 0; + long value = 0; unsafe { unchecked { - *((Int64*)&value) = (Int64)0xffffffffffffffff; + *((long*)&value) = (long)0xffffffffffffffff; } } return value; } [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static Single GetSingleWithAllBitsSet() + public static float GetSingleWithAllBitsSet() { - Single value = 0; + float value = 0; unsafe { unchecked { - *((Int32*)&value) = (Int32)0xffffffff; + *((int*)&value) = (int)0xffffffff; } } return value; } [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static Double GetDoubleWithAllBitsSet() + public static double GetDoubleWithAllBitsSet() { - Double value = 0; + double value = 0; unsafe { unchecked { - *((Int64*)&value) = (Int64)0xffffffffffffffff; + *((long*)&value) = (long)0xffffffffffffffff; } } return value; diff --git a/src/System.Private.CoreLib/shared/System/Numerics/Register.cs b/src/System.Private.CoreLib/shared/System/Numerics/Register.cs index a27e922b9d8..8efa85b199e 100644 --- a/src/System.Private.CoreLib/shared/System/Numerics/Register.cs +++ b/src/System.Private.CoreLib/shared/System/Numerics/Register.cs @@ -17,155 +17,155 @@ internal struct Register #region Internal Storage Fields // Internal System.Byte Fields [FieldOffset(0)] - internal Byte byte_0; + internal byte byte_0; [FieldOffset(1)] - internal Byte byte_1; + internal byte byte_1; [FieldOffset(2)] - internal Byte byte_2; + internal byte byte_2; [FieldOffset(3)] - internal Byte byte_3; + internal byte byte_3; [FieldOffset(4)] - internal Byte byte_4; + internal byte byte_4; [FieldOffset(5)] - internal Byte byte_5; + internal byte byte_5; [FieldOffset(6)] - internal Byte byte_6; + internal byte byte_6; [FieldOffset(7)] - internal Byte byte_7; + internal byte byte_7; [FieldOffset(8)] - internal Byte byte_8; + internal byte byte_8; [FieldOffset(9)] - internal Byte byte_9; + internal byte byte_9; [FieldOffset(10)] - internal Byte byte_10; + internal byte byte_10; [FieldOffset(11)] - internal Byte byte_11; + internal byte byte_11; [FieldOffset(12)] - internal Byte byte_12; + internal byte byte_12; [FieldOffset(13)] - internal Byte byte_13; + internal byte byte_13; [FieldOffset(14)] - internal Byte byte_14; + internal byte byte_14; [FieldOffset(15)] - internal Byte byte_15; + internal byte byte_15; // Internal System.SByte Fields [FieldOffset(0)] - internal SByte sbyte_0; + internal sbyte sbyte_0; [FieldOffset(1)] - internal SByte sbyte_1; + internal sbyte sbyte_1; [FieldOffset(2)] - internal SByte sbyte_2; + internal sbyte sbyte_2; [FieldOffset(3)] - internal SByte sbyte_3; + internal sbyte sbyte_3; [FieldOffset(4)] - internal SByte sbyte_4; + internal sbyte sbyte_4; [FieldOffset(5)] - internal SByte sbyte_5; + internal sbyte sbyte_5; [FieldOffset(6)] - internal SByte sbyte_6; + internal sbyte sbyte_6; [FieldOffset(7)] - internal SByte sbyte_7; + internal sbyte sbyte_7; [FieldOffset(8)] - internal SByte sbyte_8; + internal sbyte sbyte_8; [FieldOffset(9)] - internal SByte sbyte_9; + internal sbyte sbyte_9; [FieldOffset(10)] - internal SByte sbyte_10; + internal sbyte sbyte_10; [FieldOffset(11)] - internal SByte sbyte_11; + internal sbyte sbyte_11; [FieldOffset(12)] - internal SByte sbyte_12; + internal sbyte sbyte_12; [FieldOffset(13)] - internal SByte sbyte_13; + internal sbyte sbyte_13; [FieldOffset(14)] - internal SByte sbyte_14; + internal sbyte sbyte_14; [FieldOffset(15)] - internal SByte sbyte_15; + internal sbyte sbyte_15; // Internal System.UInt16 Fields [FieldOffset(0)] - internal UInt16 uint16_0; + internal ushort uint16_0; [FieldOffset(2)] - internal UInt16 uint16_1; + internal ushort uint16_1; [FieldOffset(4)] - internal UInt16 uint16_2; + internal ushort uint16_2; [FieldOffset(6)] - internal UInt16 uint16_3; + internal ushort uint16_3; [FieldOffset(8)] - internal UInt16 uint16_4; + internal ushort uint16_4; [FieldOffset(10)] - internal UInt16 uint16_5; + internal ushort uint16_5; [FieldOffset(12)] - internal UInt16 uint16_6; + internal ushort uint16_6; [FieldOffset(14)] - internal UInt16 uint16_7; + internal ushort uint16_7; // Internal System.Int16 Fields [FieldOffset(0)] - internal Int16 int16_0; + internal short int16_0; [FieldOffset(2)] - internal Int16 int16_1; + internal short int16_1; [FieldOffset(4)] - internal Int16 int16_2; + internal short int16_2; [FieldOffset(6)] - internal Int16 int16_3; + internal short int16_3; [FieldOffset(8)] - internal Int16 int16_4; + internal short int16_4; [FieldOffset(10)] - internal Int16 int16_5; + internal short int16_5; [FieldOffset(12)] - internal Int16 int16_6; + internal short int16_6; [FieldOffset(14)] - internal Int16 int16_7; + internal short int16_7; // Internal System.UInt32 Fields [FieldOffset(0)] - internal UInt32 uint32_0; + internal uint uint32_0; [FieldOffset(4)] - internal UInt32 uint32_1; + internal uint uint32_1; [FieldOffset(8)] - internal UInt32 uint32_2; + internal uint uint32_2; [FieldOffset(12)] - internal UInt32 uint32_3; + internal uint uint32_3; // Internal System.Int32 Fields [FieldOffset(0)] - internal Int32 int32_0; + internal int int32_0; [FieldOffset(4)] - internal Int32 int32_1; + internal int int32_1; [FieldOffset(8)] - internal Int32 int32_2; + internal int int32_2; [FieldOffset(12)] - internal Int32 int32_3; + internal int int32_3; // Internal System.UInt64 Fields [FieldOffset(0)] - internal UInt64 uint64_0; + internal ulong uint64_0; [FieldOffset(8)] - internal UInt64 uint64_1; + internal ulong uint64_1; // Internal System.Int64 Fields [FieldOffset(0)] - internal Int64 int64_0; + internal long int64_0; [FieldOffset(8)] - internal Int64 int64_1; + internal long int64_1; // Internal System.Single Fields [FieldOffset(0)] - internal Single single_0; + internal float single_0; [FieldOffset(4)] - internal Single single_1; + internal float single_1; [FieldOffset(8)] - internal Single single_2; + internal float single_2; [FieldOffset(12)] - internal Single single_3; + internal float single_3; // Internal System.Double Fields [FieldOffset(0)] - internal Double double_0; + internal double double_0; [FieldOffset(8)] - internal Double double_1; + internal double double_1; #endregion Internal Storage Fields } diff --git a/src/System.Private.CoreLib/shared/System/Numerics/Vector.cs b/src/System.Private.CoreLib/shared/System/Numerics/Vector.cs index 42f86d92977..1ac7bb3e72b 100644 --- a/src/System.Private.CoreLib/shared/System/Numerics/Vector.cs +++ b/src/System.Private.CoreLib/shared/System/Numerics/Vector.cs @@ -109,45 +109,45 @@ private static unsafe int InitializeCount() int vectorSizeInBytes = (int)(byteBase - vectorBase); int typeSizeInBytes = -1; - if (typeof(T) == typeof(Byte)) + if (typeof(T) == typeof(byte)) { - typeSizeInBytes = sizeof(Byte); + typeSizeInBytes = sizeof(byte); } - else if (typeof(T) == typeof(SByte)) + else if (typeof(T) == typeof(sbyte)) { - typeSizeInBytes = sizeof(SByte); + typeSizeInBytes = sizeof(sbyte); } - else if (typeof(T) == typeof(UInt16)) + else if (typeof(T) == typeof(ushort)) { - typeSizeInBytes = sizeof(UInt16); + typeSizeInBytes = sizeof(ushort); } - else if (typeof(T) == typeof(Int16)) + else if (typeof(T) == typeof(short)) { - typeSizeInBytes = sizeof(Int16); + typeSizeInBytes = sizeof(short); } - else if (typeof(T) == typeof(UInt32)) + else if (typeof(T) == typeof(uint)) { - typeSizeInBytes = sizeof(UInt32); + typeSizeInBytes = sizeof(uint); } - else if (typeof(T) == typeof(Int32)) + else if (typeof(T) == typeof(int)) { - typeSizeInBytes = sizeof(Int32); + typeSizeInBytes = sizeof(int); } - else if (typeof(T) == typeof(UInt64)) + else if (typeof(T) == typeof(ulong)) { - typeSizeInBytes = sizeof(UInt64); + typeSizeInBytes = sizeof(ulong); } - else if (typeof(T) == typeof(Int64)) + else if (typeof(T) == typeof(long)) { - typeSizeInBytes = sizeof(Int64); + typeSizeInBytes = sizeof(long); } - else if (typeof(T) == typeof(Single)) + else if (typeof(T) == typeof(float)) { - typeSizeInBytes = sizeof(Single); + typeSizeInBytes = sizeof(float); } - else if (typeof(T) == typeof(Double)) + else if (typeof(T) == typeof(double)) { - typeSizeInBytes = sizeof(Double); + typeSizeInBytes = sizeof(double); } else { @@ -168,204 +168,204 @@ public unsafe Vector(T value) { if (Vector.IsHardwareAccelerated) { - if (typeof(T) == typeof(Byte)) + if (typeof(T) == typeof(byte)) { - fixed (Byte* basePtr = &this.register.byte_0) + fixed (byte* basePtr = &this.register.byte_0) { for (int g = 0; g < Count; g++) { - *(basePtr + g) = (Byte)(object)value; + *(basePtr + g) = (byte)(object)value; } } } - else if (typeof(T) == typeof(SByte)) + else if (typeof(T) == typeof(sbyte)) { - fixed (SByte* basePtr = &this.register.sbyte_0) + fixed (sbyte* basePtr = &this.register.sbyte_0) { for (int g = 0; g < Count; g++) { - *(basePtr + g) = (SByte)(object)value; + *(basePtr + g) = (sbyte)(object)value; } } } - else if (typeof(T) == typeof(UInt16)) + else if (typeof(T) == typeof(ushort)) { - fixed (UInt16* basePtr = &this.register.uint16_0) + fixed (ushort* basePtr = &this.register.uint16_0) { for (int g = 0; g < Count; g++) { - *(basePtr + g) = (UInt16)(object)value; + *(basePtr + g) = (ushort)(object)value; } } } - else if (typeof(T) == typeof(Int16)) + else if (typeof(T) == typeof(short)) { - fixed (Int16* basePtr = &this.register.int16_0) + fixed (short* basePtr = &this.register.int16_0) { for (int g = 0; g < Count; g++) { - *(basePtr + g) = (Int16)(object)value; + *(basePtr + g) = (short)(object)value; } } } - else if (typeof(T) == typeof(UInt32)) + else if (typeof(T) == typeof(uint)) { - fixed (UInt32* basePtr = &this.register.uint32_0) + fixed (uint* basePtr = &this.register.uint32_0) { for (int g = 0; g < Count; g++) { - *(basePtr + g) = (UInt32)(object)value; + *(basePtr + g) = (uint)(object)value; } } } - else if (typeof(T) == typeof(Int32)) + else if (typeof(T) == typeof(int)) { - fixed (Int32* basePtr = &this.register.int32_0) + fixed (int* basePtr = &this.register.int32_0) { for (int g = 0; g < Count; g++) { - *(basePtr + g) = (Int32)(object)value; + *(basePtr + g) = (int)(object)value; } } } - else if (typeof(T) == typeof(UInt64)) + else if (typeof(T) == typeof(ulong)) { - fixed (UInt64* basePtr = &this.register.uint64_0) + fixed (ulong* basePtr = &this.register.uint64_0) { for (int g = 0; g < Count; g++) { - *(basePtr + g) = (UInt64)(object)value; + *(basePtr + g) = (ulong)(object)value; } } } - else if (typeof(T) == typeof(Int64)) + else if (typeof(T) == typeof(long)) { - fixed (Int64* basePtr = &this.register.int64_0) + fixed (long* basePtr = &this.register.int64_0) { for (int g = 0; g < Count; g++) { - *(basePtr + g) = (Int64)(object)value; + *(basePtr + g) = (long)(object)value; } } } - else if (typeof(T) == typeof(Single)) + else if (typeof(T) == typeof(float)) { - fixed (Single* basePtr = &this.register.single_0) + fixed (float* basePtr = &this.register.single_0) { for (int g = 0; g < Count; g++) { - *(basePtr + g) = (Single)(object)value; + *(basePtr + g) = (float)(object)value; } } } - else if (typeof(T) == typeof(Double)) + else if (typeof(T) == typeof(double)) { - fixed (Double* basePtr = &this.register.double_0) + fixed (double* basePtr = &this.register.double_0) { for (int g = 0; g < Count; g++) { - *(basePtr + g) = (Double)(object)value; + *(basePtr + g) = (double)(object)value; } } } } else { - if (typeof(T) == typeof(Byte)) - { - register.byte_0 = (Byte)(object)value; - register.byte_1 = (Byte)(object)value; - register.byte_2 = (Byte)(object)value; - register.byte_3 = (Byte)(object)value; - register.byte_4 = (Byte)(object)value; - register.byte_5 = (Byte)(object)value; - register.byte_6 = (Byte)(object)value; - register.byte_7 = (Byte)(object)value; - register.byte_8 = (Byte)(object)value; - register.byte_9 = (Byte)(object)value; - register.byte_10 = (Byte)(object)value; - register.byte_11 = (Byte)(object)value; - register.byte_12 = (Byte)(object)value; - register.byte_13 = (Byte)(object)value; - register.byte_14 = (Byte)(object)value; - register.byte_15 = (Byte)(object)value; - } - else if (typeof(T) == typeof(SByte)) - { - register.sbyte_0 = (SByte)(object)value; - register.sbyte_1 = (SByte)(object)value; - register.sbyte_2 = (SByte)(object)value; - register.sbyte_3 = (SByte)(object)value; - register.sbyte_4 = (SByte)(object)value; - register.sbyte_5 = (SByte)(object)value; - register.sbyte_6 = (SByte)(object)value; - register.sbyte_7 = (SByte)(object)value; - register.sbyte_8 = (SByte)(object)value; - register.sbyte_9 = (SByte)(object)value; - register.sbyte_10 = (SByte)(object)value; - register.sbyte_11 = (SByte)(object)value; - register.sbyte_12 = (SByte)(object)value; - register.sbyte_13 = (SByte)(object)value; - register.sbyte_14 = (SByte)(object)value; - register.sbyte_15 = (SByte)(object)value; - } - else if (typeof(T) == typeof(UInt16)) - { - register.uint16_0 = (UInt16)(object)value; - register.uint16_1 = (UInt16)(object)value; - register.uint16_2 = (UInt16)(object)value; - register.uint16_3 = (UInt16)(object)value; - register.uint16_4 = (UInt16)(object)value; - register.uint16_5 = (UInt16)(object)value; - register.uint16_6 = (UInt16)(object)value; - register.uint16_7 = (UInt16)(object)value; - } - else if (typeof(T) == typeof(Int16)) - { - register.int16_0 = (Int16)(object)value; - register.int16_1 = (Int16)(object)value; - register.int16_2 = (Int16)(object)value; - register.int16_3 = (Int16)(object)value; - register.int16_4 = (Int16)(object)value; - register.int16_5 = (Int16)(object)value; - register.int16_6 = (Int16)(object)value; - register.int16_7 = (Int16)(object)value; - } - else if (typeof(T) == typeof(UInt32)) - { - register.uint32_0 = (UInt32)(object)value; - register.uint32_1 = (UInt32)(object)value; - register.uint32_2 = (UInt32)(object)value; - register.uint32_3 = (UInt32)(object)value; - } - else if (typeof(T) == typeof(Int32)) - { - register.int32_0 = (Int32)(object)value; - register.int32_1 = (Int32)(object)value; - register.int32_2 = (Int32)(object)value; - register.int32_3 = (Int32)(object)value; - } - else if (typeof(T) == typeof(UInt64)) - { - register.uint64_0 = (UInt64)(object)value; - register.uint64_1 = (UInt64)(object)value; - } - else if (typeof(T) == typeof(Int64)) - { - register.int64_0 = (Int64)(object)value; - register.int64_1 = (Int64)(object)value; - } - else if (typeof(T) == typeof(Single)) - { - register.single_0 = (Single)(object)value; - register.single_1 = (Single)(object)value; - register.single_2 = (Single)(object)value; - register.single_3 = (Single)(object)value; - } - else if (typeof(T) == typeof(Double)) - { - register.double_0 = (Double)(object)value; - register.double_1 = (Double)(object)value; + if (typeof(T) == typeof(byte)) + { + register.byte_0 = (byte)(object)value; + register.byte_1 = (byte)(object)value; + register.byte_2 = (byte)(object)value; + register.byte_3 = (byte)(object)value; + register.byte_4 = (byte)(object)value; + register.byte_5 = (byte)(object)value; + register.byte_6 = (byte)(object)value; + register.byte_7 = (byte)(object)value; + register.byte_8 = (byte)(object)value; + register.byte_9 = (byte)(object)value; + register.byte_10 = (byte)(object)value; + register.byte_11 = (byte)(object)value; + register.byte_12 = (byte)(object)value; + register.byte_13 = (byte)(object)value; + register.byte_14 = (byte)(object)value; + register.byte_15 = (byte)(object)value; + } + else if (typeof(T) == typeof(sbyte)) + { + register.sbyte_0 = (sbyte)(object)value; + register.sbyte_1 = (sbyte)(object)value; + register.sbyte_2 = (sbyte)(object)value; + register.sbyte_3 = (sbyte)(object)value; + register.sbyte_4 = (sbyte)(object)value; + register.sbyte_5 = (sbyte)(object)value; + register.sbyte_6 = (sbyte)(object)value; + register.sbyte_7 = (sbyte)(object)value; + register.sbyte_8 = (sbyte)(object)value; + register.sbyte_9 = (sbyte)(object)value; + register.sbyte_10 = (sbyte)(object)value; + register.sbyte_11 = (sbyte)(object)value; + register.sbyte_12 = (sbyte)(object)value; + register.sbyte_13 = (sbyte)(object)value; + register.sbyte_14 = (sbyte)(object)value; + register.sbyte_15 = (sbyte)(object)value; + } + else if (typeof(T) == typeof(ushort)) + { + register.uint16_0 = (ushort)(object)value; + register.uint16_1 = (ushort)(object)value; + register.uint16_2 = (ushort)(object)value; + register.uint16_3 = (ushort)(object)value; + register.uint16_4 = (ushort)(object)value; + register.uint16_5 = (ushort)(object)value; + register.uint16_6 = (ushort)(object)value; + register.uint16_7 = (ushort)(object)value; + } + else if (typeof(T) == typeof(short)) + { + register.int16_0 = (short)(object)value; + register.int16_1 = (short)(object)value; + register.int16_2 = (short)(object)value; + register.int16_3 = (short)(object)value; + register.int16_4 = (short)(object)value; + register.int16_5 = (short)(object)value; + register.int16_6 = (short)(object)value; + register.int16_7 = (short)(object)value; + } + else if (typeof(T) == typeof(uint)) + { + register.uint32_0 = (uint)(object)value; + register.uint32_1 = (uint)(object)value; + register.uint32_2 = (uint)(object)value; + register.uint32_3 = (uint)(object)value; + } + else if (typeof(T) == typeof(int)) + { + register.int32_0 = (int)(object)value; + register.int32_1 = (int)(object)value; + register.int32_2 = (int)(object)value; + register.int32_3 = (int)(object)value; + } + else if (typeof(T) == typeof(ulong)) + { + register.uint64_0 = (ulong)(object)value; + register.uint64_1 = (ulong)(object)value; + } + else if (typeof(T) == typeof(long)) + { + register.int64_0 = (long)(object)value; + register.int64_1 = (long)(object)value; + } + else if (typeof(T) == typeof(float)) + { + register.single_0 = (float)(object)value; + register.single_1 = (float)(object)value; + register.single_2 = (float)(object)value; + register.single_3 = (float)(object)value; + } + else if (typeof(T) == typeof(double)) + { + register.double_0 = (double)(object)value; + register.double_1 = (double)(object)value; } } } @@ -395,233 +395,233 @@ public unsafe Vector(T[] values, int index) if (Vector.IsHardwareAccelerated) { - if (typeof(T) == typeof(Byte)) + if (typeof(T) == typeof(byte)) { - fixed (Byte* basePtr = &this.register.byte_0) + fixed (byte* basePtr = &this.register.byte_0) { for (int g = 0; g < Count; g++) { - *(basePtr + g) = (Byte)(object)values[g + index]; + *(basePtr + g) = (byte)(object)values[g + index]; } } } - else if (typeof(T) == typeof(SByte)) + else if (typeof(T) == typeof(sbyte)) { - fixed (SByte* basePtr = &this.register.sbyte_0) + fixed (sbyte* basePtr = &this.register.sbyte_0) { for (int g = 0; g < Count; g++) { - *(basePtr + g) = (SByte)(object)values[g + index]; + *(basePtr + g) = (sbyte)(object)values[g + index]; } } } - else if (typeof(T) == typeof(UInt16)) + else if (typeof(T) == typeof(ushort)) { - fixed (UInt16* basePtr = &this.register.uint16_0) + fixed (ushort* basePtr = &this.register.uint16_0) { for (int g = 0; g < Count; g++) { - *(basePtr + g) = (UInt16)(object)values[g + index]; + *(basePtr + g) = (ushort)(object)values[g + index]; } } } - else if (typeof(T) == typeof(Int16)) + else if (typeof(T) == typeof(short)) { - fixed (Int16* basePtr = &this.register.int16_0) + fixed (short* basePtr = &this.register.int16_0) { for (int g = 0; g < Count; g++) { - *(basePtr + g) = (Int16)(object)values[g + index]; + *(basePtr + g) = (short)(object)values[g + index]; } } } - else if (typeof(T) == typeof(UInt32)) + else if (typeof(T) == typeof(uint)) { - fixed (UInt32* basePtr = &this.register.uint32_0) + fixed (uint* basePtr = &this.register.uint32_0) { for (int g = 0; g < Count; g++) { - *(basePtr + g) = (UInt32)(object)values[g + index]; + *(basePtr + g) = (uint)(object)values[g + index]; } } } - else if (typeof(T) == typeof(Int32)) + else if (typeof(T) == typeof(int)) { - fixed (Int32* basePtr = &this.register.int32_0) + fixed (int* basePtr = &this.register.int32_0) { for (int g = 0; g < Count; g++) { - *(basePtr + g) = (Int32)(object)values[g + index]; + *(basePtr + g) = (int)(object)values[g + index]; } } } - else if (typeof(T) == typeof(UInt64)) + else if (typeof(T) == typeof(ulong)) { - fixed (UInt64* basePtr = &this.register.uint64_0) + fixed (ulong* basePtr = &this.register.uint64_0) { for (int g = 0; g < Count; g++) { - *(basePtr + g) = (UInt64)(object)values[g + index]; + *(basePtr + g) = (ulong)(object)values[g + index]; } } } - else if (typeof(T) == typeof(Int64)) + else if (typeof(T) == typeof(long)) { - fixed (Int64* basePtr = &this.register.int64_0) + fixed (long* basePtr = &this.register.int64_0) { for (int g = 0; g < Count; g++) { - *(basePtr + g) = (Int64)(object)values[g + index]; + *(basePtr + g) = (long)(object)values[g + index]; } } } - else if (typeof(T) == typeof(Single)) + else if (typeof(T) == typeof(float)) { - fixed (Single* basePtr = &this.register.single_0) + fixed (float* basePtr = &this.register.single_0) { for (int g = 0; g < Count; g++) { - *(basePtr + g) = (Single)(object)values[g + index]; + *(basePtr + g) = (float)(object)values[g + index]; } } } - else if (typeof(T) == typeof(Double)) + else if (typeof(T) == typeof(double)) { - fixed (Double* basePtr = &this.register.double_0) + fixed (double* basePtr = &this.register.double_0) { for (int g = 0; g < Count; g++) { - *(basePtr + g) = (Double)(object)values[g + index]; + *(basePtr + g) = (double)(object)values[g + index]; } } } } else { - if (typeof(T) == typeof(Byte)) + if (typeof(T) == typeof(byte)) { - fixed (Byte* basePtr = &this.register.byte_0) + fixed (byte* basePtr = &this.register.byte_0) { - *(basePtr + 0) = (Byte)(object)values[0 + index]; - *(basePtr + 1) = (Byte)(object)values[1 + index]; - *(basePtr + 2) = (Byte)(object)values[2 + index]; - *(basePtr + 3) = (Byte)(object)values[3 + index]; - *(basePtr + 4) = (Byte)(object)values[4 + index]; - *(basePtr + 5) = (Byte)(object)values[5 + index]; - *(basePtr + 6) = (Byte)(object)values[6 + index]; - *(basePtr + 7) = (Byte)(object)values[7 + index]; - *(basePtr + 8) = (Byte)(object)values[8 + index]; - *(basePtr + 9) = (Byte)(object)values[9 + index]; - *(basePtr + 10) = (Byte)(object)values[10 + index]; - *(basePtr + 11) = (Byte)(object)values[11 + index]; - *(basePtr + 12) = (Byte)(object)values[12 + index]; - *(basePtr + 13) = (Byte)(object)values[13 + index]; - *(basePtr + 14) = (Byte)(object)values[14 + index]; - *(basePtr + 15) = (Byte)(object)values[15 + index]; + *(basePtr + 0) = (byte)(object)values[0 + index]; + *(basePtr + 1) = (byte)(object)values[1 + index]; + *(basePtr + 2) = (byte)(object)values[2 + index]; + *(basePtr + 3) = (byte)(object)values[3 + index]; + *(basePtr + 4) = (byte)(object)values[4 + index]; + *(basePtr + 5) = (byte)(object)values[5 + index]; + *(basePtr + 6) = (byte)(object)values[6 + index]; + *(basePtr + 7) = (byte)(object)values[7 + index]; + *(basePtr + 8) = (byte)(object)values[8 + index]; + *(basePtr + 9) = (byte)(object)values[9 + index]; + *(basePtr + 10) = (byte)(object)values[10 + index]; + *(basePtr + 11) = (byte)(object)values[11 + index]; + *(basePtr + 12) = (byte)(object)values[12 + index]; + *(basePtr + 13) = (byte)(object)values[13 + index]; + *(basePtr + 14) = (byte)(object)values[14 + index]; + *(basePtr + 15) = (byte)(object)values[15 + index]; } } - else if (typeof(T) == typeof(SByte)) + else if (typeof(T) == typeof(sbyte)) { - fixed (SByte* basePtr = &this.register.sbyte_0) + fixed (sbyte* basePtr = &this.register.sbyte_0) { - *(basePtr + 0) = (SByte)(object)values[0 + index]; - *(basePtr + 1) = (SByte)(object)values[1 + index]; - *(basePtr + 2) = (SByte)(object)values[2 + index]; - *(basePtr + 3) = (SByte)(object)values[3 + index]; - *(basePtr + 4) = (SByte)(object)values[4 + index]; - *(basePtr + 5) = (SByte)(object)values[5 + index]; - *(basePtr + 6) = (SByte)(object)values[6 + index]; - *(basePtr + 7) = (SByte)(object)values[7 + index]; - *(basePtr + 8) = (SByte)(object)values[8 + index]; - *(basePtr + 9) = (SByte)(object)values[9 + index]; - *(basePtr + 10) = (SByte)(object)values[10 + index]; - *(basePtr + 11) = (SByte)(object)values[11 + index]; - *(basePtr + 12) = (SByte)(object)values[12 + index]; - *(basePtr + 13) = (SByte)(object)values[13 + index]; - *(basePtr + 14) = (SByte)(object)values[14 + index]; - *(basePtr + 15) = (SByte)(object)values[15 + index]; + *(basePtr + 0) = (sbyte)(object)values[0 + index]; + *(basePtr + 1) = (sbyte)(object)values[1 + index]; + *(basePtr + 2) = (sbyte)(object)values[2 + index]; + *(basePtr + 3) = (sbyte)(object)values[3 + index]; + *(basePtr + 4) = (sbyte)(object)values[4 + index]; + *(basePtr + 5) = (sbyte)(object)values[5 + index]; + *(basePtr + 6) = (sbyte)(object)values[6 + index]; + *(basePtr + 7) = (sbyte)(object)values[7 + index]; + *(basePtr + 8) = (sbyte)(object)values[8 + index]; + *(basePtr + 9) = (sbyte)(object)values[9 + index]; + *(basePtr + 10) = (sbyte)(object)values[10 + index]; + *(basePtr + 11) = (sbyte)(object)values[11 + index]; + *(basePtr + 12) = (sbyte)(object)values[12 + index]; + *(basePtr + 13) = (sbyte)(object)values[13 + index]; + *(basePtr + 14) = (sbyte)(object)values[14 + index]; + *(basePtr + 15) = (sbyte)(object)values[15 + index]; } } - else if (typeof(T) == typeof(UInt16)) + else if (typeof(T) == typeof(ushort)) { - fixed (UInt16* basePtr = &this.register.uint16_0) + fixed (ushort* basePtr = &this.register.uint16_0) { - *(basePtr + 0) = (UInt16)(object)values[0 + index]; - *(basePtr + 1) = (UInt16)(object)values[1 + index]; - *(basePtr + 2) = (UInt16)(object)values[2 + index]; - *(basePtr + 3) = (UInt16)(object)values[3 + index]; - *(basePtr + 4) = (UInt16)(object)values[4 + index]; - *(basePtr + 5) = (UInt16)(object)values[5 + index]; - *(basePtr + 6) = (UInt16)(object)values[6 + index]; - *(basePtr + 7) = (UInt16)(object)values[7 + index]; + *(basePtr + 0) = (ushort)(object)values[0 + index]; + *(basePtr + 1) = (ushort)(object)values[1 + index]; + *(basePtr + 2) = (ushort)(object)values[2 + index]; + *(basePtr + 3) = (ushort)(object)values[3 + index]; + *(basePtr + 4) = (ushort)(object)values[4 + index]; + *(basePtr + 5) = (ushort)(object)values[5 + index]; + *(basePtr + 6) = (ushort)(object)values[6 + index]; + *(basePtr + 7) = (ushort)(object)values[7 + index]; } } - else if (typeof(T) == typeof(Int16)) + else if (typeof(T) == typeof(short)) { - fixed (Int16* basePtr = &this.register.int16_0) + fixed (short* basePtr = &this.register.int16_0) { - *(basePtr + 0) = (Int16)(object)values[0 + index]; - *(basePtr + 1) = (Int16)(object)values[1 + index]; - *(basePtr + 2) = (Int16)(object)values[2 + index]; - *(basePtr + 3) = (Int16)(object)values[3 + index]; - *(basePtr + 4) = (Int16)(object)values[4 + index]; - *(basePtr + 5) = (Int16)(object)values[5 + index]; - *(basePtr + 6) = (Int16)(object)values[6 + index]; - *(basePtr + 7) = (Int16)(object)values[7 + index]; + *(basePtr + 0) = (short)(object)values[0 + index]; + *(basePtr + 1) = (short)(object)values[1 + index]; + *(basePtr + 2) = (short)(object)values[2 + index]; + *(basePtr + 3) = (short)(object)values[3 + index]; + *(basePtr + 4) = (short)(object)values[4 + index]; + *(basePtr + 5) = (short)(object)values[5 + index]; + *(basePtr + 6) = (short)(object)values[6 + index]; + *(basePtr + 7) = (short)(object)values[7 + index]; } } - else if (typeof(T) == typeof(UInt32)) + else if (typeof(T) == typeof(uint)) { - fixed (UInt32* basePtr = &this.register.uint32_0) + fixed (uint* basePtr = &this.register.uint32_0) { - *(basePtr + 0) = (UInt32)(object)values[0 + index]; - *(basePtr + 1) = (UInt32)(object)values[1 + index]; - *(basePtr + 2) = (UInt32)(object)values[2 + index]; - *(basePtr + 3) = (UInt32)(object)values[3 + index]; + *(basePtr + 0) = (uint)(object)values[0 + index]; + *(basePtr + 1) = (uint)(object)values[1 + index]; + *(basePtr + 2) = (uint)(object)values[2 + index]; + *(basePtr + 3) = (uint)(object)values[3 + index]; } } - else if (typeof(T) == typeof(Int32)) + else if (typeof(T) == typeof(int)) { - fixed (Int32* basePtr = &this.register.int32_0) + fixed (int* basePtr = &this.register.int32_0) { - *(basePtr + 0) = (Int32)(object)values[0 + index]; - *(basePtr + 1) = (Int32)(object)values[1 + index]; - *(basePtr + 2) = (Int32)(object)values[2 + index]; - *(basePtr + 3) = (Int32)(object)values[3 + index]; + *(basePtr + 0) = (int)(object)values[0 + index]; + *(basePtr + 1) = (int)(object)values[1 + index]; + *(basePtr + 2) = (int)(object)values[2 + index]; + *(basePtr + 3) = (int)(object)values[3 + index]; } } - else if (typeof(T) == typeof(UInt64)) + else if (typeof(T) == typeof(ulong)) { - fixed (UInt64* basePtr = &this.register.uint64_0) + fixed (ulong* basePtr = &this.register.uint64_0) { - *(basePtr + 0) = (UInt64)(object)values[0 + index]; - *(basePtr + 1) = (UInt64)(object)values[1 + index]; + *(basePtr + 0) = (ulong)(object)values[0 + index]; + *(basePtr + 1) = (ulong)(object)values[1 + index]; } } - else if (typeof(T) == typeof(Int64)) + else if (typeof(T) == typeof(long)) { - fixed (Int64* basePtr = &this.register.int64_0) + fixed (long* basePtr = &this.register.int64_0) { - *(basePtr + 0) = (Int64)(object)values[0 + index]; - *(basePtr + 1) = (Int64)(object)values[1 + index]; + *(basePtr + 0) = (long)(object)values[0 + index]; + *(basePtr + 1) = (long)(object)values[1 + index]; } } - else if (typeof(T) == typeof(Single)) + else if (typeof(T) == typeof(float)) { - fixed (Single* basePtr = &this.register.single_0) + fixed (float* basePtr = &this.register.single_0) { - *(basePtr + 0) = (Single)(object)values[0 + index]; - *(basePtr + 1) = (Single)(object)values[1 + index]; - *(basePtr + 2) = (Single)(object)values[2 + index]; - *(basePtr + 3) = (Single)(object)values[3 + index]; + *(basePtr + 0) = (float)(object)values[0 + index]; + *(basePtr + 1) = (float)(object)values[1 + index]; + *(basePtr + 2) = (float)(object)values[2 + index]; + *(basePtr + 3) = (float)(object)values[3 + index]; } } - else if (typeof(T) == typeof(Double)) + else if (typeof(T) == typeof(double)) { - fixed (Double* basePtr = &this.register.double_0) + fixed (double* basePtr = &this.register.double_0) { - *(basePtr + 0) = (Double)(object)values[0 + index]; - *(basePtr + 1) = (Double)(object)values[1 + index]; + *(basePtr + 0) = (double)(object)values[0 + index]; + *(basePtr + 1) = (double)(object)values[1 + index]; } } } @@ -636,11 +636,11 @@ public unsafe Vector(T[] values, int index) internal unsafe Vector(void* dataPointer, int offset) : this() { - if (typeof(T) == typeof(Byte)) + if (typeof(T) == typeof(byte)) { - Byte* castedPtr = (Byte*)dataPointer; + byte* castedPtr = (byte*)dataPointer; castedPtr += offset; - fixed (Byte* registerBase = &this.register.byte_0) + fixed (byte* registerBase = &this.register.byte_0) { for (int g = 0; g < Count; g++) { @@ -648,11 +648,11 @@ internal unsafe Vector(void* dataPointer, int offset) } } } - else if (typeof(T) == typeof(SByte)) + else if (typeof(T) == typeof(sbyte)) { - SByte* castedPtr = (SByte*)dataPointer; + sbyte* castedPtr = (sbyte*)dataPointer; castedPtr += offset; - fixed (SByte* registerBase = &this.register.sbyte_0) + fixed (sbyte* registerBase = &this.register.sbyte_0) { for (int g = 0; g < Count; g++) { @@ -660,11 +660,11 @@ internal unsafe Vector(void* dataPointer, int offset) } } } - else if (typeof(T) == typeof(UInt16)) + else if (typeof(T) == typeof(ushort)) { - UInt16* castedPtr = (UInt16*)dataPointer; + ushort* castedPtr = (ushort*)dataPointer; castedPtr += offset; - fixed (UInt16* registerBase = &this.register.uint16_0) + fixed (ushort* registerBase = &this.register.uint16_0) { for (int g = 0; g < Count; g++) { @@ -672,11 +672,11 @@ internal unsafe Vector(void* dataPointer, int offset) } } } - else if (typeof(T) == typeof(Int16)) + else if (typeof(T) == typeof(short)) { - Int16* castedPtr = (Int16*)dataPointer; + short* castedPtr = (short*)dataPointer; castedPtr += offset; - fixed (Int16* registerBase = &this.register.int16_0) + fixed (short* registerBase = &this.register.int16_0) { for (int g = 0; g < Count; g++) { @@ -684,11 +684,11 @@ internal unsafe Vector(void* dataPointer, int offset) } } } - else if (typeof(T) == typeof(UInt32)) + else if (typeof(T) == typeof(uint)) { - UInt32* castedPtr = (UInt32*)dataPointer; + uint* castedPtr = (uint*)dataPointer; castedPtr += offset; - fixed (UInt32* registerBase = &this.register.uint32_0) + fixed (uint* registerBase = &this.register.uint32_0) { for (int g = 0; g < Count; g++) { @@ -696,11 +696,11 @@ internal unsafe Vector(void* dataPointer, int offset) } } } - else if (typeof(T) == typeof(Int32)) + else if (typeof(T) == typeof(int)) { - Int32* castedPtr = (Int32*)dataPointer; + int* castedPtr = (int*)dataPointer; castedPtr += offset; - fixed (Int32* registerBase = &this.register.int32_0) + fixed (int* registerBase = &this.register.int32_0) { for (int g = 0; g < Count; g++) { @@ -708,11 +708,11 @@ internal unsafe Vector(void* dataPointer, int offset) } } } - else if (typeof(T) == typeof(UInt64)) + else if (typeof(T) == typeof(ulong)) { - UInt64* castedPtr = (UInt64*)dataPointer; + ulong* castedPtr = (ulong*)dataPointer; castedPtr += offset; - fixed (UInt64* registerBase = &this.register.uint64_0) + fixed (ulong* registerBase = &this.register.uint64_0) { for (int g = 0; g < Count; g++) { @@ -720,11 +720,11 @@ internal unsafe Vector(void* dataPointer, int offset) } } } - else if (typeof(T) == typeof(Int64)) + else if (typeof(T) == typeof(long)) { - Int64* castedPtr = (Int64*)dataPointer; + long* castedPtr = (long*)dataPointer; castedPtr += offset; - fixed (Int64* registerBase = &this.register.int64_0) + fixed (long* registerBase = &this.register.int64_0) { for (int g = 0; g < Count; g++) { @@ -732,11 +732,11 @@ internal unsafe Vector(void* dataPointer, int offset) } } } - else if (typeof(T) == typeof(Single)) + else if (typeof(T) == typeof(float)) { - Single* castedPtr = (Single*)dataPointer; + float* castedPtr = (float*)dataPointer; castedPtr += offset; - fixed (Single* registerBase = &this.register.single_0) + fixed (float* registerBase = &this.register.single_0) { for (int g = 0; g < Count; g++) { @@ -744,11 +744,11 @@ internal unsafe Vector(void* dataPointer, int offset) } } } - else if (typeof(T) == typeof(Double)) + else if (typeof(T) == typeof(double)) { - Double* castedPtr = (Double*)dataPointer; + double* castedPtr = (double*)dataPointer; castedPtr += offset; - fixed (Double* registerBase = &this.register.double_0) + fixed (double* registerBase = &this.register.double_0) { for (int g = 0; g < Count; g++) { @@ -775,16 +775,16 @@ private Vector(ref Register existingRegister) public Vector(Span values) : this() { - if ((typeof(T) == typeof(Byte)) - || (typeof(T) == typeof(SByte)) - || (typeof(T) == typeof(UInt16)) - || (typeof(T) == typeof(Int16)) - || (typeof(T) == typeof(UInt32)) - || (typeof(T) == typeof(Int32)) - || (typeof(T) == typeof(UInt64)) - || (typeof(T) == typeof(Int64)) - || (typeof(T) == typeof(Single)) - || (typeof(T) == typeof(Double))) + if ((typeof(T) == typeof(byte)) + || (typeof(T) == typeof(sbyte)) + || (typeof(T) == typeof(ushort)) + || (typeof(T) == typeof(short)) + || (typeof(T) == typeof(uint)) + || (typeof(T) == typeof(int)) + || (typeof(T) == typeof(ulong)) + || (typeof(T) == typeof(long)) + || (typeof(T) == typeof(float)) + || (typeof(T) == typeof(double))) { if (values.Length < Count) { @@ -840,123 +840,123 @@ public unsafe void CopyTo(T[] destination, int startIndex) if (Vector.IsHardwareAccelerated) { - if (typeof(T) == typeof(Byte)) + if (typeof(T) == typeof(byte)) { - Byte[] byteArray = (Byte[])(object)destination; - fixed (Byte* destinationBase = byteArray) + byte[] byteArray = (byte[])(object)destination; + fixed (byte* destinationBase = byteArray) { for (int g = 0; g < Count; g++) { - destinationBase[startIndex + g] = (Byte)(object)this[g]; + destinationBase[startIndex + g] = (byte)(object)this[g]; } } } - else if (typeof(T) == typeof(SByte)) + else if (typeof(T) == typeof(sbyte)) { - SByte[] sbyteArray = (SByte[])(object)destination; - fixed (SByte* destinationBase = sbyteArray) + sbyte[] sbyteArray = (sbyte[])(object)destination; + fixed (sbyte* destinationBase = sbyteArray) { for (int g = 0; g < Count; g++) { - destinationBase[startIndex + g] = (SByte)(object)this[g]; + destinationBase[startIndex + g] = (sbyte)(object)this[g]; } } } - else if (typeof(T) == typeof(UInt16)) + else if (typeof(T) == typeof(ushort)) { - UInt16[] uint16Array = (UInt16[])(object)destination; - fixed (UInt16* destinationBase = uint16Array) + ushort[] uint16Array = (ushort[])(object)destination; + fixed (ushort* destinationBase = uint16Array) { for (int g = 0; g < Count; g++) { - destinationBase[startIndex + g] = (UInt16)(object)this[g]; + destinationBase[startIndex + g] = (ushort)(object)this[g]; } } } - else if (typeof(T) == typeof(Int16)) + else if (typeof(T) == typeof(short)) { - Int16[] int16Array = (Int16[])(object)destination; - fixed (Int16* destinationBase = int16Array) + short[] int16Array = (short[])(object)destination; + fixed (short* destinationBase = int16Array) { for (int g = 0; g < Count; g++) { - destinationBase[startIndex + g] = (Int16)(object)this[g]; + destinationBase[startIndex + g] = (short)(object)this[g]; } } } - else if (typeof(T) == typeof(UInt32)) + else if (typeof(T) == typeof(uint)) { - UInt32[] uint32Array = (UInt32[])(object)destination; - fixed (UInt32* destinationBase = uint32Array) + uint[] uint32Array = (uint[])(object)destination; + fixed (uint* destinationBase = uint32Array) { for (int g = 0; g < Count; g++) { - destinationBase[startIndex + g] = (UInt32)(object)this[g]; + destinationBase[startIndex + g] = (uint)(object)this[g]; } } } - else if (typeof(T) == typeof(Int32)) + else if (typeof(T) == typeof(int)) { - Int32[] int32Array = (Int32[])(object)destination; - fixed (Int32* destinationBase = int32Array) + int[] int32Array = (int[])(object)destination; + fixed (int* destinationBase = int32Array) { for (int g = 0; g < Count; g++) { - destinationBase[startIndex + g] = (Int32)(object)this[g]; + destinationBase[startIndex + g] = (int)(object)this[g]; } } } - else if (typeof(T) == typeof(UInt64)) + else if (typeof(T) == typeof(ulong)) { - UInt64[] uint64Array = (UInt64[])(object)destination; - fixed (UInt64* destinationBase = uint64Array) + ulong[] uint64Array = (ulong[])(object)destination; + fixed (ulong* destinationBase = uint64Array) { for (int g = 0; g < Count; g++) { - destinationBase[startIndex + g] = (UInt64)(object)this[g]; + destinationBase[startIndex + g] = (ulong)(object)this[g]; } } } - else if (typeof(T) == typeof(Int64)) + else if (typeof(T) == typeof(long)) { - Int64[] int64Array = (Int64[])(object)destination; - fixed (Int64* destinationBase = int64Array) + long[] int64Array = (long[])(object)destination; + fixed (long* destinationBase = int64Array) { for (int g = 0; g < Count; g++) { - destinationBase[startIndex + g] = (Int64)(object)this[g]; + destinationBase[startIndex + g] = (long)(object)this[g]; } } } - else if (typeof(T) == typeof(Single)) + else if (typeof(T) == typeof(float)) { - Single[] singleArray = (Single[])(object)destination; - fixed (Single* destinationBase = singleArray) + float[] singleArray = (float[])(object)destination; + fixed (float* destinationBase = singleArray) { for (int g = 0; g < Count; g++) { - destinationBase[startIndex + g] = (Single)(object)this[g]; + destinationBase[startIndex + g] = (float)(object)this[g]; } } } - else if (typeof(T) == typeof(Double)) + else if (typeof(T) == typeof(double)) { - Double[] doubleArray = (Double[])(object)destination; - fixed (Double* destinationBase = doubleArray) + double[] doubleArray = (double[])(object)destination; + fixed (double* destinationBase = doubleArray) { for (int g = 0; g < Count; g++) { - destinationBase[startIndex + g] = (Double)(object)this[g]; + destinationBase[startIndex + g] = (double)(object)this[g]; } } } } else { - if (typeof(T) == typeof(Byte)) + if (typeof(T) == typeof(byte)) { - Byte[] byteArray = (Byte[])(object)destination; - fixed (Byte* destinationBase = byteArray) + byte[] byteArray = (byte[])(object)destination; + fixed (byte* destinationBase = byteArray) { destinationBase[startIndex + 0] = this.register.byte_0; destinationBase[startIndex + 1] = this.register.byte_1; @@ -976,10 +976,10 @@ public unsafe void CopyTo(T[] destination, int startIndex) destinationBase[startIndex + 15] = this.register.byte_15; } } - else if (typeof(T) == typeof(SByte)) + else if (typeof(T) == typeof(sbyte)) { - SByte[] sbyteArray = (SByte[])(object)destination; - fixed (SByte* destinationBase = sbyteArray) + sbyte[] sbyteArray = (sbyte[])(object)destination; + fixed (sbyte* destinationBase = sbyteArray) { destinationBase[startIndex + 0] = this.register.sbyte_0; destinationBase[startIndex + 1] = this.register.sbyte_1; @@ -999,10 +999,10 @@ public unsafe void CopyTo(T[] destination, int startIndex) destinationBase[startIndex + 15] = this.register.sbyte_15; } } - else if (typeof(T) == typeof(UInt16)) + else if (typeof(T) == typeof(ushort)) { - UInt16[] uint16Array = (UInt16[])(object)destination; - fixed (UInt16* destinationBase = uint16Array) + ushort[] uint16Array = (ushort[])(object)destination; + fixed (ushort* destinationBase = uint16Array) { destinationBase[startIndex + 0] = this.register.uint16_0; destinationBase[startIndex + 1] = this.register.uint16_1; @@ -1014,10 +1014,10 @@ public unsafe void CopyTo(T[] destination, int startIndex) destinationBase[startIndex + 7] = this.register.uint16_7; } } - else if (typeof(T) == typeof(Int16)) + else if (typeof(T) == typeof(short)) { - Int16[] int16Array = (Int16[])(object)destination; - fixed (Int16* destinationBase = int16Array) + short[] int16Array = (short[])(object)destination; + fixed (short* destinationBase = int16Array) { destinationBase[startIndex + 0] = this.register.int16_0; destinationBase[startIndex + 1] = this.register.int16_1; @@ -1029,10 +1029,10 @@ public unsafe void CopyTo(T[] destination, int startIndex) destinationBase[startIndex + 7] = this.register.int16_7; } } - else if (typeof(T) == typeof(UInt32)) + else if (typeof(T) == typeof(uint)) { - UInt32[] uint32Array = (UInt32[])(object)destination; - fixed (UInt32* destinationBase = uint32Array) + uint[] uint32Array = (uint[])(object)destination; + fixed (uint* destinationBase = uint32Array) { destinationBase[startIndex + 0] = this.register.uint32_0; destinationBase[startIndex + 1] = this.register.uint32_1; @@ -1040,10 +1040,10 @@ public unsafe void CopyTo(T[] destination, int startIndex) destinationBase[startIndex + 3] = this.register.uint32_3; } } - else if (typeof(T) == typeof(Int32)) + else if (typeof(T) == typeof(int)) { - Int32[] int32Array = (Int32[])(object)destination; - fixed (Int32* destinationBase = int32Array) + int[] int32Array = (int[])(object)destination; + fixed (int* destinationBase = int32Array) { destinationBase[startIndex + 0] = this.register.int32_0; destinationBase[startIndex + 1] = this.register.int32_1; @@ -1051,28 +1051,28 @@ public unsafe void CopyTo(T[] destination, int startIndex) destinationBase[startIndex + 3] = this.register.int32_3; } } - else if (typeof(T) == typeof(UInt64)) + else if (typeof(T) == typeof(ulong)) { - UInt64[] uint64Array = (UInt64[])(object)destination; - fixed (UInt64* destinationBase = uint64Array) + ulong[] uint64Array = (ulong[])(object)destination; + fixed (ulong* destinationBase = uint64Array) { destinationBase[startIndex + 0] = this.register.uint64_0; destinationBase[startIndex + 1] = this.register.uint64_1; } } - else if (typeof(T) == typeof(Int64)) + else if (typeof(T) == typeof(long)) { - Int64[] int64Array = (Int64[])(object)destination; - fixed (Int64* destinationBase = int64Array) + long[] int64Array = (long[])(object)destination; + fixed (long* destinationBase = int64Array) { destinationBase[startIndex + 0] = this.register.int64_0; destinationBase[startIndex + 1] = this.register.int64_1; } } - else if (typeof(T) == typeof(Single)) + else if (typeof(T) == typeof(float)) { - Single[] singleArray = (Single[])(object)destination; - fixed (Single* destinationBase = singleArray) + float[] singleArray = (float[])(object)destination; + fixed (float* destinationBase = singleArray) { destinationBase[startIndex + 0] = this.register.single_0; destinationBase[startIndex + 1] = this.register.single_1; @@ -1080,10 +1080,10 @@ public unsafe void CopyTo(T[] destination, int startIndex) destinationBase[startIndex + 3] = this.register.single_3; } } - else if (typeof(T) == typeof(Double)) + else if (typeof(T) == typeof(double)) { - Double[] doubleArray = (Double[])(object)destination; - fixed (Double* destinationBase = doubleArray) + double[] doubleArray = (double[])(object)destination; + fixed (double* destinationBase = doubleArray) { destinationBase[startIndex + 0] = this.register.double_0; destinationBase[startIndex + 1] = this.register.double_1; @@ -1104,72 +1104,72 @@ public unsafe void CopyTo(T[] destination, int startIndex) { throw new IndexOutOfRangeException(SR.Format(SR.Arg_ArgumentOutOfRangeException, index)); } - if (typeof(T) == typeof(Byte)) + if (typeof(T) == typeof(byte)) { - fixed (Byte* basePtr = &this.register.byte_0) + fixed (byte* basePtr = &this.register.byte_0) { return (T)(object)*(basePtr + index); } } - else if (typeof(T) == typeof(SByte)) + else if (typeof(T) == typeof(sbyte)) { - fixed (SByte* basePtr = &this.register.sbyte_0) + fixed (sbyte* basePtr = &this.register.sbyte_0) { return (T)(object)*(basePtr + index); } } - else if (typeof(T) == typeof(UInt16)) + else if (typeof(T) == typeof(ushort)) { - fixed (UInt16* basePtr = &this.register.uint16_0) + fixed (ushort* basePtr = &this.register.uint16_0) { return (T)(object)*(basePtr + index); } } - else if (typeof(T) == typeof(Int16)) + else if (typeof(T) == typeof(short)) { - fixed (Int16* basePtr = &this.register.int16_0) + fixed (short* basePtr = &this.register.int16_0) { return (T)(object)*(basePtr + index); } } - else if (typeof(T) == typeof(UInt32)) + else if (typeof(T) == typeof(uint)) { - fixed (UInt32* basePtr = &this.register.uint32_0) + fixed (uint* basePtr = &this.register.uint32_0) { return (T)(object)*(basePtr + index); } } - else if (typeof(T) == typeof(Int32)) + else if (typeof(T) == typeof(int)) { - fixed (Int32* basePtr = &this.register.int32_0) + fixed (int* basePtr = &this.register.int32_0) { return (T)(object)*(basePtr + index); } } - else if (typeof(T) == typeof(UInt64)) + else if (typeof(T) == typeof(ulong)) { - fixed (UInt64* basePtr = &this.register.uint64_0) + fixed (ulong* basePtr = &this.register.uint64_0) { return (T)(object)*(basePtr + index); } } - else if (typeof(T) == typeof(Int64)) + else if (typeof(T) == typeof(long)) { - fixed (Int64* basePtr = &this.register.int64_0) + fixed (long* basePtr = &this.register.int64_0) { return (T)(object)*(basePtr + index); } } - else if (typeof(T) == typeof(Single)) + else if (typeof(T) == typeof(float)) { - fixed (Single* basePtr = &this.register.single_0) + fixed (float* basePtr = &this.register.single_0) { return (T)(object)*(basePtr + index); } } - else if (typeof(T) == typeof(Double)) + else if (typeof(T) == typeof(double)) { - fixed (Double* basePtr = &this.register.double_0) + fixed (double* basePtr = &this.register.double_0) { return (T)(object)*(basePtr + index); } @@ -1217,7 +1217,7 @@ public bool Equals(Vector other) } else { - if (typeof(T) == typeof(Byte)) + if (typeof(T) == typeof(byte)) { return this.register.byte_0 == other.register.byte_0 @@ -1237,7 +1237,7 @@ public bool Equals(Vector other) && this.register.byte_14 == other.register.byte_14 && this.register.byte_15 == other.register.byte_15; } - else if (typeof(T) == typeof(SByte)) + else if (typeof(T) == typeof(sbyte)) { return this.register.sbyte_0 == other.register.sbyte_0 @@ -1257,7 +1257,7 @@ public bool Equals(Vector other) && this.register.sbyte_14 == other.register.sbyte_14 && this.register.sbyte_15 == other.register.sbyte_15; } - else if (typeof(T) == typeof(UInt16)) + else if (typeof(T) == typeof(ushort)) { return this.register.uint16_0 == other.register.uint16_0 @@ -1269,7 +1269,7 @@ public bool Equals(Vector other) && this.register.uint16_6 == other.register.uint16_6 && this.register.uint16_7 == other.register.uint16_7; } - else if (typeof(T) == typeof(Int16)) + else if (typeof(T) == typeof(short)) { return this.register.int16_0 == other.register.int16_0 @@ -1281,7 +1281,7 @@ public bool Equals(Vector other) && this.register.int16_6 == other.register.int16_6 && this.register.int16_7 == other.register.int16_7; } - else if (typeof(T) == typeof(UInt32)) + else if (typeof(T) == typeof(uint)) { return this.register.uint32_0 == other.register.uint32_0 @@ -1289,7 +1289,7 @@ public bool Equals(Vector other) && this.register.uint32_2 == other.register.uint32_2 && this.register.uint32_3 == other.register.uint32_3; } - else if (typeof(T) == typeof(Int32)) + else if (typeof(T) == typeof(int)) { return this.register.int32_0 == other.register.int32_0 @@ -1297,19 +1297,19 @@ public bool Equals(Vector other) && this.register.int32_2 == other.register.int32_2 && this.register.int32_3 == other.register.int32_3; } - else if (typeof(T) == typeof(UInt64)) + else if (typeof(T) == typeof(ulong)) { return this.register.uint64_0 == other.register.uint64_0 && this.register.uint64_1 == other.register.uint64_1; } - else if (typeof(T) == typeof(Int64)) + else if (typeof(T) == typeof(long)) { return this.register.int64_0 == other.register.int64_0 && this.register.int64_1 == other.register.int64_1; } - else if (typeof(T) == typeof(Single)) + else if (typeof(T) == typeof(float)) { return this.register.single_0 == other.register.single_0 @@ -1317,7 +1317,7 @@ public bool Equals(Vector other) && this.register.single_2 == other.register.single_2 && this.register.single_3 == other.register.single_3; } - else if (typeof(T) == typeof(Double)) + else if (typeof(T) == typeof(double)) { return this.register.double_0 == other.register.double_0 @@ -1340,83 +1340,83 @@ public override int GetHashCode() if (Vector.IsHardwareAccelerated) { - if (typeof(T) == typeof(Byte)) + if (typeof(T) == typeof(byte)) { for (int g = 0; g < Count; g++) { - hash = HashHelpers.Combine(hash, ((Byte)(object)this[g]).GetHashCode()); + hash = HashHelpers.Combine(hash, ((byte)(object)this[g]).GetHashCode()); } return hash; } - else if (typeof(T) == typeof(SByte)) + else if (typeof(T) == typeof(sbyte)) { for (int g = 0; g < Count; g++) { - hash = HashHelpers.Combine(hash, ((SByte)(object)this[g]).GetHashCode()); + hash = HashHelpers.Combine(hash, ((sbyte)(object)this[g]).GetHashCode()); } return hash; } - else if (typeof(T) == typeof(UInt16)) + else if (typeof(T) == typeof(ushort)) { for (int g = 0; g < Count; g++) { - hash = HashHelpers.Combine(hash, ((UInt16)(object)this[g]).GetHashCode()); + hash = HashHelpers.Combine(hash, ((ushort)(object)this[g]).GetHashCode()); } return hash; } - else if (typeof(T) == typeof(Int16)) + else if (typeof(T) == typeof(short)) { for (int g = 0; g < Count; g++) { - hash = HashHelpers.Combine(hash, ((Int16)(object)this[g]).GetHashCode()); + hash = HashHelpers.Combine(hash, ((short)(object)this[g]).GetHashCode()); } return hash; } - else if (typeof(T) == typeof(UInt32)) + else if (typeof(T) == typeof(uint)) { for (int g = 0; g < Count; g++) { - hash = HashHelpers.Combine(hash, ((UInt32)(object)this[g]).GetHashCode()); + hash = HashHelpers.Combine(hash, ((uint)(object)this[g]).GetHashCode()); } return hash; } - else if (typeof(T) == typeof(Int32)) + else if (typeof(T) == typeof(int)) { for (int g = 0; g < Count; g++) { - hash = HashHelpers.Combine(hash, ((Int32)(object)this[g]).GetHashCode()); + hash = HashHelpers.Combine(hash, ((int)(object)this[g]).GetHashCode()); } return hash; } - else if (typeof(T) == typeof(UInt64)) + else if (typeof(T) == typeof(ulong)) { for (int g = 0; g < Count; g++) { - hash = HashHelpers.Combine(hash, ((UInt64)(object)this[g]).GetHashCode()); + hash = HashHelpers.Combine(hash, ((ulong)(object)this[g]).GetHashCode()); } return hash; } - else if (typeof(T) == typeof(Int64)) + else if (typeof(T) == typeof(long)) { for (int g = 0; g < Count; g++) { - hash = HashHelpers.Combine(hash, ((Int64)(object)this[g]).GetHashCode()); + hash = HashHelpers.Combine(hash, ((long)(object)this[g]).GetHashCode()); } return hash; } - else if (typeof(T) == typeof(Single)) + else if (typeof(T) == typeof(float)) { for (int g = 0; g < Count; g++) { - hash = HashHelpers.Combine(hash, ((Single)(object)this[g]).GetHashCode()); + hash = HashHelpers.Combine(hash, ((float)(object)this[g]).GetHashCode()); } return hash; } - else if (typeof(T) == typeof(Double)) + else if (typeof(T) == typeof(double)) { for (int g = 0; g < Count; g++) { - hash = HashHelpers.Combine(hash, ((Double)(object)this[g]).GetHashCode()); + hash = HashHelpers.Combine(hash, ((double)(object)this[g]).GetHashCode()); } return hash; } @@ -1427,7 +1427,7 @@ public override int GetHashCode() } else { - if (typeof(T) == typeof(Byte)) + if (typeof(T) == typeof(byte)) { hash = HashHelpers.Combine(hash, this.register.byte_0.GetHashCode()); hash = HashHelpers.Combine(hash, this.register.byte_1.GetHashCode()); @@ -1447,7 +1447,7 @@ public override int GetHashCode() hash = HashHelpers.Combine(hash, this.register.byte_15.GetHashCode()); return hash; } - else if (typeof(T) == typeof(SByte)) + else if (typeof(T) == typeof(sbyte)) { hash = HashHelpers.Combine(hash, this.register.sbyte_0.GetHashCode()); hash = HashHelpers.Combine(hash, this.register.sbyte_1.GetHashCode()); @@ -1467,7 +1467,7 @@ public override int GetHashCode() hash = HashHelpers.Combine(hash, this.register.sbyte_15.GetHashCode()); return hash; } - else if (typeof(T) == typeof(UInt16)) + else if (typeof(T) == typeof(ushort)) { hash = HashHelpers.Combine(hash, this.register.uint16_0.GetHashCode()); hash = HashHelpers.Combine(hash, this.register.uint16_1.GetHashCode()); @@ -1479,7 +1479,7 @@ public override int GetHashCode() hash = HashHelpers.Combine(hash, this.register.uint16_7.GetHashCode()); return hash; } - else if (typeof(T) == typeof(Int16)) + else if (typeof(T) == typeof(short)) { hash = HashHelpers.Combine(hash, this.register.int16_0.GetHashCode()); hash = HashHelpers.Combine(hash, this.register.int16_1.GetHashCode()); @@ -1491,7 +1491,7 @@ public override int GetHashCode() hash = HashHelpers.Combine(hash, this.register.int16_7.GetHashCode()); return hash; } - else if (typeof(T) == typeof(UInt32)) + else if (typeof(T) == typeof(uint)) { hash = HashHelpers.Combine(hash, this.register.uint32_0.GetHashCode()); hash = HashHelpers.Combine(hash, this.register.uint32_1.GetHashCode()); @@ -1499,7 +1499,7 @@ public override int GetHashCode() hash = HashHelpers.Combine(hash, this.register.uint32_3.GetHashCode()); return hash; } - else if (typeof(T) == typeof(Int32)) + else if (typeof(T) == typeof(int)) { hash = HashHelpers.Combine(hash, this.register.int32_0.GetHashCode()); hash = HashHelpers.Combine(hash, this.register.int32_1.GetHashCode()); @@ -1507,19 +1507,19 @@ public override int GetHashCode() hash = HashHelpers.Combine(hash, this.register.int32_3.GetHashCode()); return hash; } - else if (typeof(T) == typeof(UInt64)) + else if (typeof(T) == typeof(ulong)) { hash = HashHelpers.Combine(hash, this.register.uint64_0.GetHashCode()); hash = HashHelpers.Combine(hash, this.register.uint64_1.GetHashCode()); return hash; } - else if (typeof(T) == typeof(Int64)) + else if (typeof(T) == typeof(long)) { hash = HashHelpers.Combine(hash, this.register.int64_0.GetHashCode()); hash = HashHelpers.Combine(hash, this.register.int64_1.GetHashCode()); return hash; } - else if (typeof(T) == typeof(Single)) + else if (typeof(T) == typeof(float)) { hash = HashHelpers.Combine(hash, this.register.single_0.GetHashCode()); hash = HashHelpers.Combine(hash, this.register.single_1.GetHashCode()); @@ -1527,7 +1527,7 @@ public override int GetHashCode() hash = HashHelpers.Combine(hash, this.register.single_3.GetHashCode()); return hash; } - else if (typeof(T) == typeof(Double)) + else if (typeof(T) == typeof(double)) { hash = HashHelpers.Combine(hash, this.register.double_0.GetHashCode()); hash = HashHelpers.Combine(hash, this.register.double_1.GetHashCode()); @@ -1597,93 +1597,93 @@ public string ToString(string format, IFormatProvider formatProvider) { if (Vector.IsHardwareAccelerated) { - if (typeof(T) == typeof(Byte)) + if (typeof(T) == typeof(byte)) { - Byte* dataPtr = stackalloc Byte[Count]; + byte* dataPtr = stackalloc byte[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (Byte)(object)ScalarAdd(left[g], right[g]); + dataPtr[g] = (byte)(object)ScalarAdd(left[g], right[g]); } return new Vector(dataPtr); } - else if (typeof(T) == typeof(SByte)) + else if (typeof(T) == typeof(sbyte)) { - SByte* dataPtr = stackalloc SByte[Count]; + sbyte* dataPtr = stackalloc sbyte[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (SByte)(object)ScalarAdd(left[g], right[g]); + dataPtr[g] = (sbyte)(object)ScalarAdd(left[g], right[g]); } return new Vector(dataPtr); } - else if (typeof(T) == typeof(UInt16)) + else if (typeof(T) == typeof(ushort)) { - UInt16* dataPtr = stackalloc UInt16[Count]; + ushort* dataPtr = stackalloc ushort[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (UInt16)(object)ScalarAdd(left[g], right[g]); + dataPtr[g] = (ushort)(object)ScalarAdd(left[g], right[g]); } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Int16)) + else if (typeof(T) == typeof(short)) { - Int16* dataPtr = stackalloc Int16[Count]; + short* dataPtr = stackalloc short[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (Int16)(object)ScalarAdd(left[g], right[g]); + dataPtr[g] = (short)(object)ScalarAdd(left[g], right[g]); } return new Vector(dataPtr); } - else if (typeof(T) == typeof(UInt32)) + else if (typeof(T) == typeof(uint)) { - UInt32* dataPtr = stackalloc UInt32[Count]; + uint* dataPtr = stackalloc uint[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (UInt32)(object)ScalarAdd(left[g], right[g]); + dataPtr[g] = (uint)(object)ScalarAdd(left[g], right[g]); } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Int32)) + else if (typeof(T) == typeof(int)) { - Int32* dataPtr = stackalloc Int32[Count]; + int* dataPtr = stackalloc int[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (Int32)(object)ScalarAdd(left[g], right[g]); + dataPtr[g] = (int)(object)ScalarAdd(left[g], right[g]); } return new Vector(dataPtr); } - else if (typeof(T) == typeof(UInt64)) + else if (typeof(T) == typeof(ulong)) { - UInt64* dataPtr = stackalloc UInt64[Count]; + ulong* dataPtr = stackalloc ulong[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (UInt64)(object)ScalarAdd(left[g], right[g]); + dataPtr[g] = (ulong)(object)ScalarAdd(left[g], right[g]); } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Int64)) + else if (typeof(T) == typeof(long)) { - Int64* dataPtr = stackalloc Int64[Count]; + long* dataPtr = stackalloc long[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (Int64)(object)ScalarAdd(left[g], right[g]); + dataPtr[g] = (long)(object)ScalarAdd(left[g], right[g]); } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Single)) + else if (typeof(T) == typeof(float)) { - Single* dataPtr = stackalloc Single[Count]; + float* dataPtr = stackalloc float[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (Single)(object)ScalarAdd(left[g], right[g]); + dataPtr[g] = (float)(object)ScalarAdd(left[g], right[g]); } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Double)) + else if (typeof(T) == typeof(double)) { - Double* dataPtr = stackalloc Double[Count]; + double* dataPtr = stackalloc double[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (Double)(object)ScalarAdd(left[g], right[g]); + dataPtr[g] = (double)(object)ScalarAdd(left[g], right[g]); } return new Vector(dataPtr); } @@ -1695,101 +1695,101 @@ public string ToString(string format, IFormatProvider formatProvider) else { Vector sum = new Vector(); - if (typeof(T) == typeof(Byte)) - { - sum.register.byte_0 = (Byte)(left.register.byte_0 + right.register.byte_0); - sum.register.byte_1 = (Byte)(left.register.byte_1 + right.register.byte_1); - sum.register.byte_2 = (Byte)(left.register.byte_2 + right.register.byte_2); - sum.register.byte_3 = (Byte)(left.register.byte_3 + right.register.byte_3); - sum.register.byte_4 = (Byte)(left.register.byte_4 + right.register.byte_4); - sum.register.byte_5 = (Byte)(left.register.byte_5 + right.register.byte_5); - sum.register.byte_6 = (Byte)(left.register.byte_6 + right.register.byte_6); - sum.register.byte_7 = (Byte)(left.register.byte_7 + right.register.byte_7); - sum.register.byte_8 = (Byte)(left.register.byte_8 + right.register.byte_8); - sum.register.byte_9 = (Byte)(left.register.byte_9 + right.register.byte_9); - sum.register.byte_10 = (Byte)(left.register.byte_10 + right.register.byte_10); - sum.register.byte_11 = (Byte)(left.register.byte_11 + right.register.byte_11); - sum.register.byte_12 = (Byte)(left.register.byte_12 + right.register.byte_12); - sum.register.byte_13 = (Byte)(left.register.byte_13 + right.register.byte_13); - sum.register.byte_14 = (Byte)(left.register.byte_14 + right.register.byte_14); - sum.register.byte_15 = (Byte)(left.register.byte_15 + right.register.byte_15); - } - else if (typeof(T) == typeof(SByte)) - { - sum.register.sbyte_0 = (SByte)(left.register.sbyte_0 + right.register.sbyte_0); - sum.register.sbyte_1 = (SByte)(left.register.sbyte_1 + right.register.sbyte_1); - sum.register.sbyte_2 = (SByte)(left.register.sbyte_2 + right.register.sbyte_2); - sum.register.sbyte_3 = (SByte)(left.register.sbyte_3 + right.register.sbyte_3); - sum.register.sbyte_4 = (SByte)(left.register.sbyte_4 + right.register.sbyte_4); - sum.register.sbyte_5 = (SByte)(left.register.sbyte_5 + right.register.sbyte_5); - sum.register.sbyte_6 = (SByte)(left.register.sbyte_6 + right.register.sbyte_6); - sum.register.sbyte_7 = (SByte)(left.register.sbyte_7 + right.register.sbyte_7); - sum.register.sbyte_8 = (SByte)(left.register.sbyte_8 + right.register.sbyte_8); - sum.register.sbyte_9 = (SByte)(left.register.sbyte_9 + right.register.sbyte_9); - sum.register.sbyte_10 = (SByte)(left.register.sbyte_10 + right.register.sbyte_10); - sum.register.sbyte_11 = (SByte)(left.register.sbyte_11 + right.register.sbyte_11); - sum.register.sbyte_12 = (SByte)(left.register.sbyte_12 + right.register.sbyte_12); - sum.register.sbyte_13 = (SByte)(left.register.sbyte_13 + right.register.sbyte_13); - sum.register.sbyte_14 = (SByte)(left.register.sbyte_14 + right.register.sbyte_14); - sum.register.sbyte_15 = (SByte)(left.register.sbyte_15 + right.register.sbyte_15); - } - else if (typeof(T) == typeof(UInt16)) - { - sum.register.uint16_0 = (UInt16)(left.register.uint16_0 + right.register.uint16_0); - sum.register.uint16_1 = (UInt16)(left.register.uint16_1 + right.register.uint16_1); - sum.register.uint16_2 = (UInt16)(left.register.uint16_2 + right.register.uint16_2); - sum.register.uint16_3 = (UInt16)(left.register.uint16_3 + right.register.uint16_3); - sum.register.uint16_4 = (UInt16)(left.register.uint16_4 + right.register.uint16_4); - sum.register.uint16_5 = (UInt16)(left.register.uint16_5 + right.register.uint16_5); - sum.register.uint16_6 = (UInt16)(left.register.uint16_6 + right.register.uint16_6); - sum.register.uint16_7 = (UInt16)(left.register.uint16_7 + right.register.uint16_7); - } - else if (typeof(T) == typeof(Int16)) - { - sum.register.int16_0 = (Int16)(left.register.int16_0 + right.register.int16_0); - sum.register.int16_1 = (Int16)(left.register.int16_1 + right.register.int16_1); - sum.register.int16_2 = (Int16)(left.register.int16_2 + right.register.int16_2); - sum.register.int16_3 = (Int16)(left.register.int16_3 + right.register.int16_3); - sum.register.int16_4 = (Int16)(left.register.int16_4 + right.register.int16_4); - sum.register.int16_5 = (Int16)(left.register.int16_5 + right.register.int16_5); - sum.register.int16_6 = (Int16)(left.register.int16_6 + right.register.int16_6); - sum.register.int16_7 = (Int16)(left.register.int16_7 + right.register.int16_7); - } - else if (typeof(T) == typeof(UInt32)) - { - sum.register.uint32_0 = (UInt32)(left.register.uint32_0 + right.register.uint32_0); - sum.register.uint32_1 = (UInt32)(left.register.uint32_1 + right.register.uint32_1); - sum.register.uint32_2 = (UInt32)(left.register.uint32_2 + right.register.uint32_2); - sum.register.uint32_3 = (UInt32)(left.register.uint32_3 + right.register.uint32_3); - } - else if (typeof(T) == typeof(Int32)) - { - sum.register.int32_0 = (Int32)(left.register.int32_0 + right.register.int32_0); - sum.register.int32_1 = (Int32)(left.register.int32_1 + right.register.int32_1); - sum.register.int32_2 = (Int32)(left.register.int32_2 + right.register.int32_2); - sum.register.int32_3 = (Int32)(left.register.int32_3 + right.register.int32_3); - } - else if (typeof(T) == typeof(UInt64)) - { - sum.register.uint64_0 = (UInt64)(left.register.uint64_0 + right.register.uint64_0); - sum.register.uint64_1 = (UInt64)(left.register.uint64_1 + right.register.uint64_1); - } - else if (typeof(T) == typeof(Int64)) - { - sum.register.int64_0 = (Int64)(left.register.int64_0 + right.register.int64_0); - sum.register.int64_1 = (Int64)(left.register.int64_1 + right.register.int64_1); - } - else if (typeof(T) == typeof(Single)) - { - sum.register.single_0 = (Single)(left.register.single_0 + right.register.single_0); - sum.register.single_1 = (Single)(left.register.single_1 + right.register.single_1); - sum.register.single_2 = (Single)(left.register.single_2 + right.register.single_2); - sum.register.single_3 = (Single)(left.register.single_3 + right.register.single_3); - } - else if (typeof(T) == typeof(Double)) - { - sum.register.double_0 = (Double)(left.register.double_0 + right.register.double_0); - sum.register.double_1 = (Double)(left.register.double_1 + right.register.double_1); + if (typeof(T) == typeof(byte)) + { + sum.register.byte_0 = (byte)(left.register.byte_0 + right.register.byte_0); + sum.register.byte_1 = (byte)(left.register.byte_1 + right.register.byte_1); + sum.register.byte_2 = (byte)(left.register.byte_2 + right.register.byte_2); + sum.register.byte_3 = (byte)(left.register.byte_3 + right.register.byte_3); + sum.register.byte_4 = (byte)(left.register.byte_4 + right.register.byte_4); + sum.register.byte_5 = (byte)(left.register.byte_5 + right.register.byte_5); + sum.register.byte_6 = (byte)(left.register.byte_6 + right.register.byte_6); + sum.register.byte_7 = (byte)(left.register.byte_7 + right.register.byte_7); + sum.register.byte_8 = (byte)(left.register.byte_8 + right.register.byte_8); + sum.register.byte_9 = (byte)(left.register.byte_9 + right.register.byte_9); + sum.register.byte_10 = (byte)(left.register.byte_10 + right.register.byte_10); + sum.register.byte_11 = (byte)(left.register.byte_11 + right.register.byte_11); + sum.register.byte_12 = (byte)(left.register.byte_12 + right.register.byte_12); + sum.register.byte_13 = (byte)(left.register.byte_13 + right.register.byte_13); + sum.register.byte_14 = (byte)(left.register.byte_14 + right.register.byte_14); + sum.register.byte_15 = (byte)(left.register.byte_15 + right.register.byte_15); + } + else if (typeof(T) == typeof(sbyte)) + { + sum.register.sbyte_0 = (sbyte)(left.register.sbyte_0 + right.register.sbyte_0); + sum.register.sbyte_1 = (sbyte)(left.register.sbyte_1 + right.register.sbyte_1); + sum.register.sbyte_2 = (sbyte)(left.register.sbyte_2 + right.register.sbyte_2); + sum.register.sbyte_3 = (sbyte)(left.register.sbyte_3 + right.register.sbyte_3); + sum.register.sbyte_4 = (sbyte)(left.register.sbyte_4 + right.register.sbyte_4); + sum.register.sbyte_5 = (sbyte)(left.register.sbyte_5 + right.register.sbyte_5); + sum.register.sbyte_6 = (sbyte)(left.register.sbyte_6 + right.register.sbyte_6); + sum.register.sbyte_7 = (sbyte)(left.register.sbyte_7 + right.register.sbyte_7); + sum.register.sbyte_8 = (sbyte)(left.register.sbyte_8 + right.register.sbyte_8); + sum.register.sbyte_9 = (sbyte)(left.register.sbyte_9 + right.register.sbyte_9); + sum.register.sbyte_10 = (sbyte)(left.register.sbyte_10 + right.register.sbyte_10); + sum.register.sbyte_11 = (sbyte)(left.register.sbyte_11 + right.register.sbyte_11); + sum.register.sbyte_12 = (sbyte)(left.register.sbyte_12 + right.register.sbyte_12); + sum.register.sbyte_13 = (sbyte)(left.register.sbyte_13 + right.register.sbyte_13); + sum.register.sbyte_14 = (sbyte)(left.register.sbyte_14 + right.register.sbyte_14); + sum.register.sbyte_15 = (sbyte)(left.register.sbyte_15 + right.register.sbyte_15); + } + else if (typeof(T) == typeof(ushort)) + { + sum.register.uint16_0 = (ushort)(left.register.uint16_0 + right.register.uint16_0); + sum.register.uint16_1 = (ushort)(left.register.uint16_1 + right.register.uint16_1); + sum.register.uint16_2 = (ushort)(left.register.uint16_2 + right.register.uint16_2); + sum.register.uint16_3 = (ushort)(left.register.uint16_3 + right.register.uint16_3); + sum.register.uint16_4 = (ushort)(left.register.uint16_4 + right.register.uint16_4); + sum.register.uint16_5 = (ushort)(left.register.uint16_5 + right.register.uint16_5); + sum.register.uint16_6 = (ushort)(left.register.uint16_6 + right.register.uint16_6); + sum.register.uint16_7 = (ushort)(left.register.uint16_7 + right.register.uint16_7); + } + else if (typeof(T) == typeof(short)) + { + sum.register.int16_0 = (short)(left.register.int16_0 + right.register.int16_0); + sum.register.int16_1 = (short)(left.register.int16_1 + right.register.int16_1); + sum.register.int16_2 = (short)(left.register.int16_2 + right.register.int16_2); + sum.register.int16_3 = (short)(left.register.int16_3 + right.register.int16_3); + sum.register.int16_4 = (short)(left.register.int16_4 + right.register.int16_4); + sum.register.int16_5 = (short)(left.register.int16_5 + right.register.int16_5); + sum.register.int16_6 = (short)(left.register.int16_6 + right.register.int16_6); + sum.register.int16_7 = (short)(left.register.int16_7 + right.register.int16_7); + } + else if (typeof(T) == typeof(uint)) + { + sum.register.uint32_0 = (uint)(left.register.uint32_0 + right.register.uint32_0); + sum.register.uint32_1 = (uint)(left.register.uint32_1 + right.register.uint32_1); + sum.register.uint32_2 = (uint)(left.register.uint32_2 + right.register.uint32_2); + sum.register.uint32_3 = (uint)(left.register.uint32_3 + right.register.uint32_3); + } + else if (typeof(T) == typeof(int)) + { + sum.register.int32_0 = (int)(left.register.int32_0 + right.register.int32_0); + sum.register.int32_1 = (int)(left.register.int32_1 + right.register.int32_1); + sum.register.int32_2 = (int)(left.register.int32_2 + right.register.int32_2); + sum.register.int32_3 = (int)(left.register.int32_3 + right.register.int32_3); + } + else if (typeof(T) == typeof(ulong)) + { + sum.register.uint64_0 = (ulong)(left.register.uint64_0 + right.register.uint64_0); + sum.register.uint64_1 = (ulong)(left.register.uint64_1 + right.register.uint64_1); + } + else if (typeof(T) == typeof(long)) + { + sum.register.int64_0 = (long)(left.register.int64_0 + right.register.int64_0); + sum.register.int64_1 = (long)(left.register.int64_1 + right.register.int64_1); + } + else if (typeof(T) == typeof(float)) + { + sum.register.single_0 = (float)(left.register.single_0 + right.register.single_0); + sum.register.single_1 = (float)(left.register.single_1 + right.register.single_1); + sum.register.single_2 = (float)(left.register.single_2 + right.register.single_2); + sum.register.single_3 = (float)(left.register.single_3 + right.register.single_3); + } + else if (typeof(T) == typeof(double)) + { + sum.register.double_0 = (double)(left.register.double_0 + right.register.double_0); + sum.register.double_1 = (double)(left.register.double_1 + right.register.double_1); } return sum; } @@ -1808,93 +1808,93 @@ public string ToString(string format, IFormatProvider formatProvider) { if (Vector.IsHardwareAccelerated) { - if (typeof(T) == typeof(Byte)) + if (typeof(T) == typeof(byte)) { - Byte* dataPtr = stackalloc Byte[Count]; + byte* dataPtr = stackalloc byte[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (Byte)(object)ScalarSubtract(left[g], right[g]); + dataPtr[g] = (byte)(object)ScalarSubtract(left[g], right[g]); } return new Vector(dataPtr); } - else if (typeof(T) == typeof(SByte)) + else if (typeof(T) == typeof(sbyte)) { - SByte* dataPtr = stackalloc SByte[Count]; + sbyte* dataPtr = stackalloc sbyte[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (SByte)(object)ScalarSubtract(left[g], right[g]); + dataPtr[g] = (sbyte)(object)ScalarSubtract(left[g], right[g]); } return new Vector(dataPtr); } - else if (typeof(T) == typeof(UInt16)) + else if (typeof(T) == typeof(ushort)) { - UInt16* dataPtr = stackalloc UInt16[Count]; + ushort* dataPtr = stackalloc ushort[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (UInt16)(object)ScalarSubtract(left[g], right[g]); + dataPtr[g] = (ushort)(object)ScalarSubtract(left[g], right[g]); } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Int16)) + else if (typeof(T) == typeof(short)) { - Int16* dataPtr = stackalloc Int16[Count]; + short* dataPtr = stackalloc short[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (Int16)(object)ScalarSubtract(left[g], right[g]); + dataPtr[g] = (short)(object)ScalarSubtract(left[g], right[g]); } return new Vector(dataPtr); } - else if (typeof(T) == typeof(UInt32)) + else if (typeof(T) == typeof(uint)) { - UInt32* dataPtr = stackalloc UInt32[Count]; + uint* dataPtr = stackalloc uint[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (UInt32)(object)ScalarSubtract(left[g], right[g]); + dataPtr[g] = (uint)(object)ScalarSubtract(left[g], right[g]); } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Int32)) + else if (typeof(T) == typeof(int)) { - Int32* dataPtr = stackalloc Int32[Count]; + int* dataPtr = stackalloc int[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (Int32)(object)ScalarSubtract(left[g], right[g]); + dataPtr[g] = (int)(object)ScalarSubtract(left[g], right[g]); } return new Vector(dataPtr); } - else if (typeof(T) == typeof(UInt64)) + else if (typeof(T) == typeof(ulong)) { - UInt64* dataPtr = stackalloc UInt64[Count]; + ulong* dataPtr = stackalloc ulong[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (UInt64)(object)ScalarSubtract(left[g], right[g]); + dataPtr[g] = (ulong)(object)ScalarSubtract(left[g], right[g]); } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Int64)) + else if (typeof(T) == typeof(long)) { - Int64* dataPtr = stackalloc Int64[Count]; + long* dataPtr = stackalloc long[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (Int64)(object)ScalarSubtract(left[g], right[g]); + dataPtr[g] = (long)(object)ScalarSubtract(left[g], right[g]); } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Single)) + else if (typeof(T) == typeof(float)) { - Single* dataPtr = stackalloc Single[Count]; + float* dataPtr = stackalloc float[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (Single)(object)ScalarSubtract(left[g], right[g]); + dataPtr[g] = (float)(object)ScalarSubtract(left[g], right[g]); } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Double)) + else if (typeof(T) == typeof(double)) { - Double* dataPtr = stackalloc Double[Count]; + double* dataPtr = stackalloc double[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (Double)(object)ScalarSubtract(left[g], right[g]); + dataPtr[g] = (double)(object)ScalarSubtract(left[g], right[g]); } return new Vector(dataPtr); } @@ -1906,101 +1906,101 @@ public string ToString(string format, IFormatProvider formatProvider) else { Vector difference = new Vector(); - if (typeof(T) == typeof(Byte)) - { - difference.register.byte_0 = (Byte)(left.register.byte_0 - right.register.byte_0); - difference.register.byte_1 = (Byte)(left.register.byte_1 - right.register.byte_1); - difference.register.byte_2 = (Byte)(left.register.byte_2 - right.register.byte_2); - difference.register.byte_3 = (Byte)(left.register.byte_3 - right.register.byte_3); - difference.register.byte_4 = (Byte)(left.register.byte_4 - right.register.byte_4); - difference.register.byte_5 = (Byte)(left.register.byte_5 - right.register.byte_5); - difference.register.byte_6 = (Byte)(left.register.byte_6 - right.register.byte_6); - difference.register.byte_7 = (Byte)(left.register.byte_7 - right.register.byte_7); - difference.register.byte_8 = (Byte)(left.register.byte_8 - right.register.byte_8); - difference.register.byte_9 = (Byte)(left.register.byte_9 - right.register.byte_9); - difference.register.byte_10 = (Byte)(left.register.byte_10 - right.register.byte_10); - difference.register.byte_11 = (Byte)(left.register.byte_11 - right.register.byte_11); - difference.register.byte_12 = (Byte)(left.register.byte_12 - right.register.byte_12); - difference.register.byte_13 = (Byte)(left.register.byte_13 - right.register.byte_13); - difference.register.byte_14 = (Byte)(left.register.byte_14 - right.register.byte_14); - difference.register.byte_15 = (Byte)(left.register.byte_15 - right.register.byte_15); - } - else if (typeof(T) == typeof(SByte)) - { - difference.register.sbyte_0 = (SByte)(left.register.sbyte_0 - right.register.sbyte_0); - difference.register.sbyte_1 = (SByte)(left.register.sbyte_1 - right.register.sbyte_1); - difference.register.sbyte_2 = (SByte)(left.register.sbyte_2 - right.register.sbyte_2); - difference.register.sbyte_3 = (SByte)(left.register.sbyte_3 - right.register.sbyte_3); - difference.register.sbyte_4 = (SByte)(left.register.sbyte_4 - right.register.sbyte_4); - difference.register.sbyte_5 = (SByte)(left.register.sbyte_5 - right.register.sbyte_5); - difference.register.sbyte_6 = (SByte)(left.register.sbyte_6 - right.register.sbyte_6); - difference.register.sbyte_7 = (SByte)(left.register.sbyte_7 - right.register.sbyte_7); - difference.register.sbyte_8 = (SByte)(left.register.sbyte_8 - right.register.sbyte_8); - difference.register.sbyte_9 = (SByte)(left.register.sbyte_9 - right.register.sbyte_9); - difference.register.sbyte_10 = (SByte)(left.register.sbyte_10 - right.register.sbyte_10); - difference.register.sbyte_11 = (SByte)(left.register.sbyte_11 - right.register.sbyte_11); - difference.register.sbyte_12 = (SByte)(left.register.sbyte_12 - right.register.sbyte_12); - difference.register.sbyte_13 = (SByte)(left.register.sbyte_13 - right.register.sbyte_13); - difference.register.sbyte_14 = (SByte)(left.register.sbyte_14 - right.register.sbyte_14); - difference.register.sbyte_15 = (SByte)(left.register.sbyte_15 - right.register.sbyte_15); - } - else if (typeof(T) == typeof(UInt16)) - { - difference.register.uint16_0 = (UInt16)(left.register.uint16_0 - right.register.uint16_0); - difference.register.uint16_1 = (UInt16)(left.register.uint16_1 - right.register.uint16_1); - difference.register.uint16_2 = (UInt16)(left.register.uint16_2 - right.register.uint16_2); - difference.register.uint16_3 = (UInt16)(left.register.uint16_3 - right.register.uint16_3); - difference.register.uint16_4 = (UInt16)(left.register.uint16_4 - right.register.uint16_4); - difference.register.uint16_5 = (UInt16)(left.register.uint16_5 - right.register.uint16_5); - difference.register.uint16_6 = (UInt16)(left.register.uint16_6 - right.register.uint16_6); - difference.register.uint16_7 = (UInt16)(left.register.uint16_7 - right.register.uint16_7); - } - else if (typeof(T) == typeof(Int16)) - { - difference.register.int16_0 = (Int16)(left.register.int16_0 - right.register.int16_0); - difference.register.int16_1 = (Int16)(left.register.int16_1 - right.register.int16_1); - difference.register.int16_2 = (Int16)(left.register.int16_2 - right.register.int16_2); - difference.register.int16_3 = (Int16)(left.register.int16_3 - right.register.int16_3); - difference.register.int16_4 = (Int16)(left.register.int16_4 - right.register.int16_4); - difference.register.int16_5 = (Int16)(left.register.int16_5 - right.register.int16_5); - difference.register.int16_6 = (Int16)(left.register.int16_6 - right.register.int16_6); - difference.register.int16_7 = (Int16)(left.register.int16_7 - right.register.int16_7); - } - else if (typeof(T) == typeof(UInt32)) - { - difference.register.uint32_0 = (UInt32)(left.register.uint32_0 - right.register.uint32_0); - difference.register.uint32_1 = (UInt32)(left.register.uint32_1 - right.register.uint32_1); - difference.register.uint32_2 = (UInt32)(left.register.uint32_2 - right.register.uint32_2); - difference.register.uint32_3 = (UInt32)(left.register.uint32_3 - right.register.uint32_3); - } - else if (typeof(T) == typeof(Int32)) - { - difference.register.int32_0 = (Int32)(left.register.int32_0 - right.register.int32_0); - difference.register.int32_1 = (Int32)(left.register.int32_1 - right.register.int32_1); - difference.register.int32_2 = (Int32)(left.register.int32_2 - right.register.int32_2); - difference.register.int32_3 = (Int32)(left.register.int32_3 - right.register.int32_3); - } - else if (typeof(T) == typeof(UInt64)) - { - difference.register.uint64_0 = (UInt64)(left.register.uint64_0 - right.register.uint64_0); - difference.register.uint64_1 = (UInt64)(left.register.uint64_1 - right.register.uint64_1); - } - else if (typeof(T) == typeof(Int64)) - { - difference.register.int64_0 = (Int64)(left.register.int64_0 - right.register.int64_0); - difference.register.int64_1 = (Int64)(left.register.int64_1 - right.register.int64_1); - } - else if (typeof(T) == typeof(Single)) - { - difference.register.single_0 = (Single)(left.register.single_0 - right.register.single_0); - difference.register.single_1 = (Single)(left.register.single_1 - right.register.single_1); - difference.register.single_2 = (Single)(left.register.single_2 - right.register.single_2); - difference.register.single_3 = (Single)(left.register.single_3 - right.register.single_3); - } - else if (typeof(T) == typeof(Double)) - { - difference.register.double_0 = (Double)(left.register.double_0 - right.register.double_0); - difference.register.double_1 = (Double)(left.register.double_1 - right.register.double_1); + if (typeof(T) == typeof(byte)) + { + difference.register.byte_0 = (byte)(left.register.byte_0 - right.register.byte_0); + difference.register.byte_1 = (byte)(left.register.byte_1 - right.register.byte_1); + difference.register.byte_2 = (byte)(left.register.byte_2 - right.register.byte_2); + difference.register.byte_3 = (byte)(left.register.byte_3 - right.register.byte_3); + difference.register.byte_4 = (byte)(left.register.byte_4 - right.register.byte_4); + difference.register.byte_5 = (byte)(left.register.byte_5 - right.register.byte_5); + difference.register.byte_6 = (byte)(left.register.byte_6 - right.register.byte_6); + difference.register.byte_7 = (byte)(left.register.byte_7 - right.register.byte_7); + difference.register.byte_8 = (byte)(left.register.byte_8 - right.register.byte_8); + difference.register.byte_9 = (byte)(left.register.byte_9 - right.register.byte_9); + difference.register.byte_10 = (byte)(left.register.byte_10 - right.register.byte_10); + difference.register.byte_11 = (byte)(left.register.byte_11 - right.register.byte_11); + difference.register.byte_12 = (byte)(left.register.byte_12 - right.register.byte_12); + difference.register.byte_13 = (byte)(left.register.byte_13 - right.register.byte_13); + difference.register.byte_14 = (byte)(left.register.byte_14 - right.register.byte_14); + difference.register.byte_15 = (byte)(left.register.byte_15 - right.register.byte_15); + } + else if (typeof(T) == typeof(sbyte)) + { + difference.register.sbyte_0 = (sbyte)(left.register.sbyte_0 - right.register.sbyte_0); + difference.register.sbyte_1 = (sbyte)(left.register.sbyte_1 - right.register.sbyte_1); + difference.register.sbyte_2 = (sbyte)(left.register.sbyte_2 - right.register.sbyte_2); + difference.register.sbyte_3 = (sbyte)(left.register.sbyte_3 - right.register.sbyte_3); + difference.register.sbyte_4 = (sbyte)(left.register.sbyte_4 - right.register.sbyte_4); + difference.register.sbyte_5 = (sbyte)(left.register.sbyte_5 - right.register.sbyte_5); + difference.register.sbyte_6 = (sbyte)(left.register.sbyte_6 - right.register.sbyte_6); + difference.register.sbyte_7 = (sbyte)(left.register.sbyte_7 - right.register.sbyte_7); + difference.register.sbyte_8 = (sbyte)(left.register.sbyte_8 - right.register.sbyte_8); + difference.register.sbyte_9 = (sbyte)(left.register.sbyte_9 - right.register.sbyte_9); + difference.register.sbyte_10 = (sbyte)(left.register.sbyte_10 - right.register.sbyte_10); + difference.register.sbyte_11 = (sbyte)(left.register.sbyte_11 - right.register.sbyte_11); + difference.register.sbyte_12 = (sbyte)(left.register.sbyte_12 - right.register.sbyte_12); + difference.register.sbyte_13 = (sbyte)(left.register.sbyte_13 - right.register.sbyte_13); + difference.register.sbyte_14 = (sbyte)(left.register.sbyte_14 - right.register.sbyte_14); + difference.register.sbyte_15 = (sbyte)(left.register.sbyte_15 - right.register.sbyte_15); + } + else if (typeof(T) == typeof(ushort)) + { + difference.register.uint16_0 = (ushort)(left.register.uint16_0 - right.register.uint16_0); + difference.register.uint16_1 = (ushort)(left.register.uint16_1 - right.register.uint16_1); + difference.register.uint16_2 = (ushort)(left.register.uint16_2 - right.register.uint16_2); + difference.register.uint16_3 = (ushort)(left.register.uint16_3 - right.register.uint16_3); + difference.register.uint16_4 = (ushort)(left.register.uint16_4 - right.register.uint16_4); + difference.register.uint16_5 = (ushort)(left.register.uint16_5 - right.register.uint16_5); + difference.register.uint16_6 = (ushort)(left.register.uint16_6 - right.register.uint16_6); + difference.register.uint16_7 = (ushort)(left.register.uint16_7 - right.register.uint16_7); + } + else if (typeof(T) == typeof(short)) + { + difference.register.int16_0 = (short)(left.register.int16_0 - right.register.int16_0); + difference.register.int16_1 = (short)(left.register.int16_1 - right.register.int16_1); + difference.register.int16_2 = (short)(left.register.int16_2 - right.register.int16_2); + difference.register.int16_3 = (short)(left.register.int16_3 - right.register.int16_3); + difference.register.int16_4 = (short)(left.register.int16_4 - right.register.int16_4); + difference.register.int16_5 = (short)(left.register.int16_5 - right.register.int16_5); + difference.register.int16_6 = (short)(left.register.int16_6 - right.register.int16_6); + difference.register.int16_7 = (short)(left.register.int16_7 - right.register.int16_7); + } + else if (typeof(T) == typeof(uint)) + { + difference.register.uint32_0 = (uint)(left.register.uint32_0 - right.register.uint32_0); + difference.register.uint32_1 = (uint)(left.register.uint32_1 - right.register.uint32_1); + difference.register.uint32_2 = (uint)(left.register.uint32_2 - right.register.uint32_2); + difference.register.uint32_3 = (uint)(left.register.uint32_3 - right.register.uint32_3); + } + else if (typeof(T) == typeof(int)) + { + difference.register.int32_0 = (int)(left.register.int32_0 - right.register.int32_0); + difference.register.int32_1 = (int)(left.register.int32_1 - right.register.int32_1); + difference.register.int32_2 = (int)(left.register.int32_2 - right.register.int32_2); + difference.register.int32_3 = (int)(left.register.int32_3 - right.register.int32_3); + } + else if (typeof(T) == typeof(ulong)) + { + difference.register.uint64_0 = (ulong)(left.register.uint64_0 - right.register.uint64_0); + difference.register.uint64_1 = (ulong)(left.register.uint64_1 - right.register.uint64_1); + } + else if (typeof(T) == typeof(long)) + { + difference.register.int64_0 = (long)(left.register.int64_0 - right.register.int64_0); + difference.register.int64_1 = (long)(left.register.int64_1 - right.register.int64_1); + } + else if (typeof(T) == typeof(float)) + { + difference.register.single_0 = (float)(left.register.single_0 - right.register.single_0); + difference.register.single_1 = (float)(left.register.single_1 - right.register.single_1); + difference.register.single_2 = (float)(left.register.single_2 - right.register.single_2); + difference.register.single_3 = (float)(left.register.single_3 - right.register.single_3); + } + else if (typeof(T) == typeof(double)) + { + difference.register.double_0 = (double)(left.register.double_0 - right.register.double_0); + difference.register.double_1 = (double)(left.register.double_1 - right.register.double_1); } return difference; } @@ -2020,93 +2020,93 @@ public string ToString(string format, IFormatProvider formatProvider) { if (Vector.IsHardwareAccelerated) { - if (typeof(T) == typeof(Byte)) + if (typeof(T) == typeof(byte)) { - Byte* dataPtr = stackalloc Byte[Count]; + byte* dataPtr = stackalloc byte[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (Byte)(object)ScalarMultiply(left[g], right[g]); + dataPtr[g] = (byte)(object)ScalarMultiply(left[g], right[g]); } return new Vector(dataPtr); } - else if (typeof(T) == typeof(SByte)) + else if (typeof(T) == typeof(sbyte)) { - SByte* dataPtr = stackalloc SByte[Count]; + sbyte* dataPtr = stackalloc sbyte[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (SByte)(object)ScalarMultiply(left[g], right[g]); + dataPtr[g] = (sbyte)(object)ScalarMultiply(left[g], right[g]); } return new Vector(dataPtr); } - else if (typeof(T) == typeof(UInt16)) + else if (typeof(T) == typeof(ushort)) { - UInt16* dataPtr = stackalloc UInt16[Count]; + ushort* dataPtr = stackalloc ushort[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (UInt16)(object)ScalarMultiply(left[g], right[g]); + dataPtr[g] = (ushort)(object)ScalarMultiply(left[g], right[g]); } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Int16)) + else if (typeof(T) == typeof(short)) { - Int16* dataPtr = stackalloc Int16[Count]; + short* dataPtr = stackalloc short[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (Int16)(object)ScalarMultiply(left[g], right[g]); + dataPtr[g] = (short)(object)ScalarMultiply(left[g], right[g]); } return new Vector(dataPtr); } - else if (typeof(T) == typeof(UInt32)) + else if (typeof(T) == typeof(uint)) { - UInt32* dataPtr = stackalloc UInt32[Count]; + uint* dataPtr = stackalloc uint[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (UInt32)(object)ScalarMultiply(left[g], right[g]); + dataPtr[g] = (uint)(object)ScalarMultiply(left[g], right[g]); } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Int32)) + else if (typeof(T) == typeof(int)) { - Int32* dataPtr = stackalloc Int32[Count]; + int* dataPtr = stackalloc int[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (Int32)(object)ScalarMultiply(left[g], right[g]); + dataPtr[g] = (int)(object)ScalarMultiply(left[g], right[g]); } return new Vector(dataPtr); } - else if (typeof(T) == typeof(UInt64)) + else if (typeof(T) == typeof(ulong)) { - UInt64* dataPtr = stackalloc UInt64[Count]; + ulong* dataPtr = stackalloc ulong[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (UInt64)(object)ScalarMultiply(left[g], right[g]); + dataPtr[g] = (ulong)(object)ScalarMultiply(left[g], right[g]); } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Int64)) + else if (typeof(T) == typeof(long)) { - Int64* dataPtr = stackalloc Int64[Count]; + long* dataPtr = stackalloc long[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (Int64)(object)ScalarMultiply(left[g], right[g]); + dataPtr[g] = (long)(object)ScalarMultiply(left[g], right[g]); } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Single)) + else if (typeof(T) == typeof(float)) { - Single* dataPtr = stackalloc Single[Count]; + float* dataPtr = stackalloc float[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (Single)(object)ScalarMultiply(left[g], right[g]); + dataPtr[g] = (float)(object)ScalarMultiply(left[g], right[g]); } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Double)) + else if (typeof(T) == typeof(double)) { - Double* dataPtr = stackalloc Double[Count]; + double* dataPtr = stackalloc double[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (Double)(object)ScalarMultiply(left[g], right[g]); + dataPtr[g] = (double)(object)ScalarMultiply(left[g], right[g]); } return new Vector(dataPtr); } @@ -2118,101 +2118,101 @@ public string ToString(string format, IFormatProvider formatProvider) else { Vector product = new Vector(); - if (typeof(T) == typeof(Byte)) - { - product.register.byte_0 = (Byte)(left.register.byte_0 * right.register.byte_0); - product.register.byte_1 = (Byte)(left.register.byte_1 * right.register.byte_1); - product.register.byte_2 = (Byte)(left.register.byte_2 * right.register.byte_2); - product.register.byte_3 = (Byte)(left.register.byte_3 * right.register.byte_3); - product.register.byte_4 = (Byte)(left.register.byte_4 * right.register.byte_4); - product.register.byte_5 = (Byte)(left.register.byte_5 * right.register.byte_5); - product.register.byte_6 = (Byte)(left.register.byte_6 * right.register.byte_6); - product.register.byte_7 = (Byte)(left.register.byte_7 * right.register.byte_7); - product.register.byte_8 = (Byte)(left.register.byte_8 * right.register.byte_8); - product.register.byte_9 = (Byte)(left.register.byte_9 * right.register.byte_9); - product.register.byte_10 = (Byte)(left.register.byte_10 * right.register.byte_10); - product.register.byte_11 = (Byte)(left.register.byte_11 * right.register.byte_11); - product.register.byte_12 = (Byte)(left.register.byte_12 * right.register.byte_12); - product.register.byte_13 = (Byte)(left.register.byte_13 * right.register.byte_13); - product.register.byte_14 = (Byte)(left.register.byte_14 * right.register.byte_14); - product.register.byte_15 = (Byte)(left.register.byte_15 * right.register.byte_15); - } - else if (typeof(T) == typeof(SByte)) - { - product.register.sbyte_0 = (SByte)(left.register.sbyte_0 * right.register.sbyte_0); - product.register.sbyte_1 = (SByte)(left.register.sbyte_1 * right.register.sbyte_1); - product.register.sbyte_2 = (SByte)(left.register.sbyte_2 * right.register.sbyte_2); - product.register.sbyte_3 = (SByte)(left.register.sbyte_3 * right.register.sbyte_3); - product.register.sbyte_4 = (SByte)(left.register.sbyte_4 * right.register.sbyte_4); - product.register.sbyte_5 = (SByte)(left.register.sbyte_5 * right.register.sbyte_5); - product.register.sbyte_6 = (SByte)(left.register.sbyte_6 * right.register.sbyte_6); - product.register.sbyte_7 = (SByte)(left.register.sbyte_7 * right.register.sbyte_7); - product.register.sbyte_8 = (SByte)(left.register.sbyte_8 * right.register.sbyte_8); - product.register.sbyte_9 = (SByte)(left.register.sbyte_9 * right.register.sbyte_9); - product.register.sbyte_10 = (SByte)(left.register.sbyte_10 * right.register.sbyte_10); - product.register.sbyte_11 = (SByte)(left.register.sbyte_11 * right.register.sbyte_11); - product.register.sbyte_12 = (SByte)(left.register.sbyte_12 * right.register.sbyte_12); - product.register.sbyte_13 = (SByte)(left.register.sbyte_13 * right.register.sbyte_13); - product.register.sbyte_14 = (SByte)(left.register.sbyte_14 * right.register.sbyte_14); - product.register.sbyte_15 = (SByte)(left.register.sbyte_15 * right.register.sbyte_15); - } - else if (typeof(T) == typeof(UInt16)) - { - product.register.uint16_0 = (UInt16)(left.register.uint16_0 * right.register.uint16_0); - product.register.uint16_1 = (UInt16)(left.register.uint16_1 * right.register.uint16_1); - product.register.uint16_2 = (UInt16)(left.register.uint16_2 * right.register.uint16_2); - product.register.uint16_3 = (UInt16)(left.register.uint16_3 * right.register.uint16_3); - product.register.uint16_4 = (UInt16)(left.register.uint16_4 * right.register.uint16_4); - product.register.uint16_5 = (UInt16)(left.register.uint16_5 * right.register.uint16_5); - product.register.uint16_6 = (UInt16)(left.register.uint16_6 * right.register.uint16_6); - product.register.uint16_7 = (UInt16)(left.register.uint16_7 * right.register.uint16_7); - } - else if (typeof(T) == typeof(Int16)) - { - product.register.int16_0 = (Int16)(left.register.int16_0 * right.register.int16_0); - product.register.int16_1 = (Int16)(left.register.int16_1 * right.register.int16_1); - product.register.int16_2 = (Int16)(left.register.int16_2 * right.register.int16_2); - product.register.int16_3 = (Int16)(left.register.int16_3 * right.register.int16_3); - product.register.int16_4 = (Int16)(left.register.int16_4 * right.register.int16_4); - product.register.int16_5 = (Int16)(left.register.int16_5 * right.register.int16_5); - product.register.int16_6 = (Int16)(left.register.int16_6 * right.register.int16_6); - product.register.int16_7 = (Int16)(left.register.int16_7 * right.register.int16_7); - } - else if (typeof(T) == typeof(UInt32)) - { - product.register.uint32_0 = (UInt32)(left.register.uint32_0 * right.register.uint32_0); - product.register.uint32_1 = (UInt32)(left.register.uint32_1 * right.register.uint32_1); - product.register.uint32_2 = (UInt32)(left.register.uint32_2 * right.register.uint32_2); - product.register.uint32_3 = (UInt32)(left.register.uint32_3 * right.register.uint32_3); - } - else if (typeof(T) == typeof(Int32)) - { - product.register.int32_0 = (Int32)(left.register.int32_0 * right.register.int32_0); - product.register.int32_1 = (Int32)(left.register.int32_1 * right.register.int32_1); - product.register.int32_2 = (Int32)(left.register.int32_2 * right.register.int32_2); - product.register.int32_3 = (Int32)(left.register.int32_3 * right.register.int32_3); - } - else if (typeof(T) == typeof(UInt64)) - { - product.register.uint64_0 = (UInt64)(left.register.uint64_0 * right.register.uint64_0); - product.register.uint64_1 = (UInt64)(left.register.uint64_1 * right.register.uint64_1); - } - else if (typeof(T) == typeof(Int64)) - { - product.register.int64_0 = (Int64)(left.register.int64_0 * right.register.int64_0); - product.register.int64_1 = (Int64)(left.register.int64_1 * right.register.int64_1); - } - else if (typeof(T) == typeof(Single)) - { - product.register.single_0 = (Single)(left.register.single_0 * right.register.single_0); - product.register.single_1 = (Single)(left.register.single_1 * right.register.single_1); - product.register.single_2 = (Single)(left.register.single_2 * right.register.single_2); - product.register.single_3 = (Single)(left.register.single_3 * right.register.single_3); - } - else if (typeof(T) == typeof(Double)) - { - product.register.double_0 = (Double)(left.register.double_0 * right.register.double_0); - product.register.double_1 = (Double)(left.register.double_1 * right.register.double_1); + if (typeof(T) == typeof(byte)) + { + product.register.byte_0 = (byte)(left.register.byte_0 * right.register.byte_0); + product.register.byte_1 = (byte)(left.register.byte_1 * right.register.byte_1); + product.register.byte_2 = (byte)(left.register.byte_2 * right.register.byte_2); + product.register.byte_3 = (byte)(left.register.byte_3 * right.register.byte_3); + product.register.byte_4 = (byte)(left.register.byte_4 * right.register.byte_4); + product.register.byte_5 = (byte)(left.register.byte_5 * right.register.byte_5); + product.register.byte_6 = (byte)(left.register.byte_6 * right.register.byte_6); + product.register.byte_7 = (byte)(left.register.byte_7 * right.register.byte_7); + product.register.byte_8 = (byte)(left.register.byte_8 * right.register.byte_8); + product.register.byte_9 = (byte)(left.register.byte_9 * right.register.byte_9); + product.register.byte_10 = (byte)(left.register.byte_10 * right.register.byte_10); + product.register.byte_11 = (byte)(left.register.byte_11 * right.register.byte_11); + product.register.byte_12 = (byte)(left.register.byte_12 * right.register.byte_12); + product.register.byte_13 = (byte)(left.register.byte_13 * right.register.byte_13); + product.register.byte_14 = (byte)(left.register.byte_14 * right.register.byte_14); + product.register.byte_15 = (byte)(left.register.byte_15 * right.register.byte_15); + } + else if (typeof(T) == typeof(sbyte)) + { + product.register.sbyte_0 = (sbyte)(left.register.sbyte_0 * right.register.sbyte_0); + product.register.sbyte_1 = (sbyte)(left.register.sbyte_1 * right.register.sbyte_1); + product.register.sbyte_2 = (sbyte)(left.register.sbyte_2 * right.register.sbyte_2); + product.register.sbyte_3 = (sbyte)(left.register.sbyte_3 * right.register.sbyte_3); + product.register.sbyte_4 = (sbyte)(left.register.sbyte_4 * right.register.sbyte_4); + product.register.sbyte_5 = (sbyte)(left.register.sbyte_5 * right.register.sbyte_5); + product.register.sbyte_6 = (sbyte)(left.register.sbyte_6 * right.register.sbyte_6); + product.register.sbyte_7 = (sbyte)(left.register.sbyte_7 * right.register.sbyte_7); + product.register.sbyte_8 = (sbyte)(left.register.sbyte_8 * right.register.sbyte_8); + product.register.sbyte_9 = (sbyte)(left.register.sbyte_9 * right.register.sbyte_9); + product.register.sbyte_10 = (sbyte)(left.register.sbyte_10 * right.register.sbyte_10); + product.register.sbyte_11 = (sbyte)(left.register.sbyte_11 * right.register.sbyte_11); + product.register.sbyte_12 = (sbyte)(left.register.sbyte_12 * right.register.sbyte_12); + product.register.sbyte_13 = (sbyte)(left.register.sbyte_13 * right.register.sbyte_13); + product.register.sbyte_14 = (sbyte)(left.register.sbyte_14 * right.register.sbyte_14); + product.register.sbyte_15 = (sbyte)(left.register.sbyte_15 * right.register.sbyte_15); + } + else if (typeof(T) == typeof(ushort)) + { + product.register.uint16_0 = (ushort)(left.register.uint16_0 * right.register.uint16_0); + product.register.uint16_1 = (ushort)(left.register.uint16_1 * right.register.uint16_1); + product.register.uint16_2 = (ushort)(left.register.uint16_2 * right.register.uint16_2); + product.register.uint16_3 = (ushort)(left.register.uint16_3 * right.register.uint16_3); + product.register.uint16_4 = (ushort)(left.register.uint16_4 * right.register.uint16_4); + product.register.uint16_5 = (ushort)(left.register.uint16_5 * right.register.uint16_5); + product.register.uint16_6 = (ushort)(left.register.uint16_6 * right.register.uint16_6); + product.register.uint16_7 = (ushort)(left.register.uint16_7 * right.register.uint16_7); + } + else if (typeof(T) == typeof(short)) + { + product.register.int16_0 = (short)(left.register.int16_0 * right.register.int16_0); + product.register.int16_1 = (short)(left.register.int16_1 * right.register.int16_1); + product.register.int16_2 = (short)(left.register.int16_2 * right.register.int16_2); + product.register.int16_3 = (short)(left.register.int16_3 * right.register.int16_3); + product.register.int16_4 = (short)(left.register.int16_4 * right.register.int16_4); + product.register.int16_5 = (short)(left.register.int16_5 * right.register.int16_5); + product.register.int16_6 = (short)(left.register.int16_6 * right.register.int16_6); + product.register.int16_7 = (short)(left.register.int16_7 * right.register.int16_7); + } + else if (typeof(T) == typeof(uint)) + { + product.register.uint32_0 = (uint)(left.register.uint32_0 * right.register.uint32_0); + product.register.uint32_1 = (uint)(left.register.uint32_1 * right.register.uint32_1); + product.register.uint32_2 = (uint)(left.register.uint32_2 * right.register.uint32_2); + product.register.uint32_3 = (uint)(left.register.uint32_3 * right.register.uint32_3); + } + else if (typeof(T) == typeof(int)) + { + product.register.int32_0 = (int)(left.register.int32_0 * right.register.int32_0); + product.register.int32_1 = (int)(left.register.int32_1 * right.register.int32_1); + product.register.int32_2 = (int)(left.register.int32_2 * right.register.int32_2); + product.register.int32_3 = (int)(left.register.int32_3 * right.register.int32_3); + } + else if (typeof(T) == typeof(ulong)) + { + product.register.uint64_0 = (ulong)(left.register.uint64_0 * right.register.uint64_0); + product.register.uint64_1 = (ulong)(left.register.uint64_1 * right.register.uint64_1); + } + else if (typeof(T) == typeof(long)) + { + product.register.int64_0 = (long)(left.register.int64_0 * right.register.int64_0); + product.register.int64_1 = (long)(left.register.int64_1 * right.register.int64_1); + } + else if (typeof(T) == typeof(float)) + { + product.register.single_0 = (float)(left.register.single_0 * right.register.single_0); + product.register.single_1 = (float)(left.register.single_1 * right.register.single_1); + product.register.single_2 = (float)(left.register.single_2 * right.register.single_2); + product.register.single_3 = (float)(left.register.single_3 * right.register.single_3); + } + else if (typeof(T) == typeof(double)) + { + product.register.double_0 = (double)(left.register.double_0 * right.register.double_0); + product.register.double_1 = (double)(left.register.double_1 * right.register.double_1); } return product; } @@ -2237,101 +2237,101 @@ public string ToString(string format, IFormatProvider formatProvider) else { Vector product = new Vector(); - if (typeof(T) == typeof(Byte)) - { - product.register.byte_0 = (Byte)(value.register.byte_0 * (Byte)(object)factor); - product.register.byte_1 = (Byte)(value.register.byte_1 * (Byte)(object)factor); - product.register.byte_2 = (Byte)(value.register.byte_2 * (Byte)(object)factor); - product.register.byte_3 = (Byte)(value.register.byte_3 * (Byte)(object)factor); - product.register.byte_4 = (Byte)(value.register.byte_4 * (Byte)(object)factor); - product.register.byte_5 = (Byte)(value.register.byte_5 * (Byte)(object)factor); - product.register.byte_6 = (Byte)(value.register.byte_6 * (Byte)(object)factor); - product.register.byte_7 = (Byte)(value.register.byte_7 * (Byte)(object)factor); - product.register.byte_8 = (Byte)(value.register.byte_8 * (Byte)(object)factor); - product.register.byte_9 = (Byte)(value.register.byte_9 * (Byte)(object)factor); - product.register.byte_10 = (Byte)(value.register.byte_10 * (Byte)(object)factor); - product.register.byte_11 = (Byte)(value.register.byte_11 * (Byte)(object)factor); - product.register.byte_12 = (Byte)(value.register.byte_12 * (Byte)(object)factor); - product.register.byte_13 = (Byte)(value.register.byte_13 * (Byte)(object)factor); - product.register.byte_14 = (Byte)(value.register.byte_14 * (Byte)(object)factor); - product.register.byte_15 = (Byte)(value.register.byte_15 * (Byte)(object)factor); - } - else if (typeof(T) == typeof(SByte)) - { - product.register.sbyte_0 = (SByte)(value.register.sbyte_0 * (SByte)(object)factor); - product.register.sbyte_1 = (SByte)(value.register.sbyte_1 * (SByte)(object)factor); - product.register.sbyte_2 = (SByte)(value.register.sbyte_2 * (SByte)(object)factor); - product.register.sbyte_3 = (SByte)(value.register.sbyte_3 * (SByte)(object)factor); - product.register.sbyte_4 = (SByte)(value.register.sbyte_4 * (SByte)(object)factor); - product.register.sbyte_5 = (SByte)(value.register.sbyte_5 * (SByte)(object)factor); - product.register.sbyte_6 = (SByte)(value.register.sbyte_6 * (SByte)(object)factor); - product.register.sbyte_7 = (SByte)(value.register.sbyte_7 * (SByte)(object)factor); - product.register.sbyte_8 = (SByte)(value.register.sbyte_8 * (SByte)(object)factor); - product.register.sbyte_9 = (SByte)(value.register.sbyte_9 * (SByte)(object)factor); - product.register.sbyte_10 = (SByte)(value.register.sbyte_10 * (SByte)(object)factor); - product.register.sbyte_11 = (SByte)(value.register.sbyte_11 * (SByte)(object)factor); - product.register.sbyte_12 = (SByte)(value.register.sbyte_12 * (SByte)(object)factor); - product.register.sbyte_13 = (SByte)(value.register.sbyte_13 * (SByte)(object)factor); - product.register.sbyte_14 = (SByte)(value.register.sbyte_14 * (SByte)(object)factor); - product.register.sbyte_15 = (SByte)(value.register.sbyte_15 * (SByte)(object)factor); - } - else if (typeof(T) == typeof(UInt16)) - { - product.register.uint16_0 = (UInt16)(value.register.uint16_0 * (UInt16)(object)factor); - product.register.uint16_1 = (UInt16)(value.register.uint16_1 * (UInt16)(object)factor); - product.register.uint16_2 = (UInt16)(value.register.uint16_2 * (UInt16)(object)factor); - product.register.uint16_3 = (UInt16)(value.register.uint16_3 * (UInt16)(object)factor); - product.register.uint16_4 = (UInt16)(value.register.uint16_4 * (UInt16)(object)factor); - product.register.uint16_5 = (UInt16)(value.register.uint16_5 * (UInt16)(object)factor); - product.register.uint16_6 = (UInt16)(value.register.uint16_6 * (UInt16)(object)factor); - product.register.uint16_7 = (UInt16)(value.register.uint16_7 * (UInt16)(object)factor); - } - else if (typeof(T) == typeof(Int16)) - { - product.register.int16_0 = (Int16)(value.register.int16_0 * (Int16)(object)factor); - product.register.int16_1 = (Int16)(value.register.int16_1 * (Int16)(object)factor); - product.register.int16_2 = (Int16)(value.register.int16_2 * (Int16)(object)factor); - product.register.int16_3 = (Int16)(value.register.int16_3 * (Int16)(object)factor); - product.register.int16_4 = (Int16)(value.register.int16_4 * (Int16)(object)factor); - product.register.int16_5 = (Int16)(value.register.int16_5 * (Int16)(object)factor); - product.register.int16_6 = (Int16)(value.register.int16_6 * (Int16)(object)factor); - product.register.int16_7 = (Int16)(value.register.int16_7 * (Int16)(object)factor); - } - else if (typeof(T) == typeof(UInt32)) - { - product.register.uint32_0 = (UInt32)(value.register.uint32_0 * (UInt32)(object)factor); - product.register.uint32_1 = (UInt32)(value.register.uint32_1 * (UInt32)(object)factor); - product.register.uint32_2 = (UInt32)(value.register.uint32_2 * (UInt32)(object)factor); - product.register.uint32_3 = (UInt32)(value.register.uint32_3 * (UInt32)(object)factor); - } - else if (typeof(T) == typeof(Int32)) - { - product.register.int32_0 = (Int32)(value.register.int32_0 * (Int32)(object)factor); - product.register.int32_1 = (Int32)(value.register.int32_1 * (Int32)(object)factor); - product.register.int32_2 = (Int32)(value.register.int32_2 * (Int32)(object)factor); - product.register.int32_3 = (Int32)(value.register.int32_3 * (Int32)(object)factor); - } - else if (typeof(T) == typeof(UInt64)) - { - product.register.uint64_0 = (UInt64)(value.register.uint64_0 * (UInt64)(object)factor); - product.register.uint64_1 = (UInt64)(value.register.uint64_1 * (UInt64)(object)factor); - } - else if (typeof(T) == typeof(Int64)) - { - product.register.int64_0 = (Int64)(value.register.int64_0 * (Int64)(object)factor); - product.register.int64_1 = (Int64)(value.register.int64_1 * (Int64)(object)factor); - } - else if (typeof(T) == typeof(Single)) - { - product.register.single_0 = (Single)(value.register.single_0 * (Single)(object)factor); - product.register.single_1 = (Single)(value.register.single_1 * (Single)(object)factor); - product.register.single_2 = (Single)(value.register.single_2 * (Single)(object)factor); - product.register.single_3 = (Single)(value.register.single_3 * (Single)(object)factor); - } - else if (typeof(T) == typeof(Double)) - { - product.register.double_0 = (Double)(value.register.double_0 * (Double)(object)factor); - product.register.double_1 = (Double)(value.register.double_1 * (Double)(object)factor); + if (typeof(T) == typeof(byte)) + { + product.register.byte_0 = (byte)(value.register.byte_0 * (byte)(object)factor); + product.register.byte_1 = (byte)(value.register.byte_1 * (byte)(object)factor); + product.register.byte_2 = (byte)(value.register.byte_2 * (byte)(object)factor); + product.register.byte_3 = (byte)(value.register.byte_3 * (byte)(object)factor); + product.register.byte_4 = (byte)(value.register.byte_4 * (byte)(object)factor); + product.register.byte_5 = (byte)(value.register.byte_5 * (byte)(object)factor); + product.register.byte_6 = (byte)(value.register.byte_6 * (byte)(object)factor); + product.register.byte_7 = (byte)(value.register.byte_7 * (byte)(object)factor); + product.register.byte_8 = (byte)(value.register.byte_8 * (byte)(object)factor); + product.register.byte_9 = (byte)(value.register.byte_9 * (byte)(object)factor); + product.register.byte_10 = (byte)(value.register.byte_10 * (byte)(object)factor); + product.register.byte_11 = (byte)(value.register.byte_11 * (byte)(object)factor); + product.register.byte_12 = (byte)(value.register.byte_12 * (byte)(object)factor); + product.register.byte_13 = (byte)(value.register.byte_13 * (byte)(object)factor); + product.register.byte_14 = (byte)(value.register.byte_14 * (byte)(object)factor); + product.register.byte_15 = (byte)(value.register.byte_15 * (byte)(object)factor); + } + else if (typeof(T) == typeof(sbyte)) + { + product.register.sbyte_0 = (sbyte)(value.register.sbyte_0 * (sbyte)(object)factor); + product.register.sbyte_1 = (sbyte)(value.register.sbyte_1 * (sbyte)(object)factor); + product.register.sbyte_2 = (sbyte)(value.register.sbyte_2 * (sbyte)(object)factor); + product.register.sbyte_3 = (sbyte)(value.register.sbyte_3 * (sbyte)(object)factor); + product.register.sbyte_4 = (sbyte)(value.register.sbyte_4 * (sbyte)(object)factor); + product.register.sbyte_5 = (sbyte)(value.register.sbyte_5 * (sbyte)(object)factor); + product.register.sbyte_6 = (sbyte)(value.register.sbyte_6 * (sbyte)(object)factor); + product.register.sbyte_7 = (sbyte)(value.register.sbyte_7 * (sbyte)(object)factor); + product.register.sbyte_8 = (sbyte)(value.register.sbyte_8 * (sbyte)(object)factor); + product.register.sbyte_9 = (sbyte)(value.register.sbyte_9 * (sbyte)(object)factor); + product.register.sbyte_10 = (sbyte)(value.register.sbyte_10 * (sbyte)(object)factor); + product.register.sbyte_11 = (sbyte)(value.register.sbyte_11 * (sbyte)(object)factor); + product.register.sbyte_12 = (sbyte)(value.register.sbyte_12 * (sbyte)(object)factor); + product.register.sbyte_13 = (sbyte)(value.register.sbyte_13 * (sbyte)(object)factor); + product.register.sbyte_14 = (sbyte)(value.register.sbyte_14 * (sbyte)(object)factor); + product.register.sbyte_15 = (sbyte)(value.register.sbyte_15 * (sbyte)(object)factor); + } + else if (typeof(T) == typeof(ushort)) + { + product.register.uint16_0 = (ushort)(value.register.uint16_0 * (ushort)(object)factor); + product.register.uint16_1 = (ushort)(value.register.uint16_1 * (ushort)(object)factor); + product.register.uint16_2 = (ushort)(value.register.uint16_2 * (ushort)(object)factor); + product.register.uint16_3 = (ushort)(value.register.uint16_3 * (ushort)(object)factor); + product.register.uint16_4 = (ushort)(value.register.uint16_4 * (ushort)(object)factor); + product.register.uint16_5 = (ushort)(value.register.uint16_5 * (ushort)(object)factor); + product.register.uint16_6 = (ushort)(value.register.uint16_6 * (ushort)(object)factor); + product.register.uint16_7 = (ushort)(value.register.uint16_7 * (ushort)(object)factor); + } + else if (typeof(T) == typeof(short)) + { + product.register.int16_0 = (short)(value.register.int16_0 * (short)(object)factor); + product.register.int16_1 = (short)(value.register.int16_1 * (short)(object)factor); + product.register.int16_2 = (short)(value.register.int16_2 * (short)(object)factor); + product.register.int16_3 = (short)(value.register.int16_3 * (short)(object)factor); + product.register.int16_4 = (short)(value.register.int16_4 * (short)(object)factor); + product.register.int16_5 = (short)(value.register.int16_5 * (short)(object)factor); + product.register.int16_6 = (short)(value.register.int16_6 * (short)(object)factor); + product.register.int16_7 = (short)(value.register.int16_7 * (short)(object)factor); + } + else if (typeof(T) == typeof(uint)) + { + product.register.uint32_0 = (uint)(value.register.uint32_0 * (uint)(object)factor); + product.register.uint32_1 = (uint)(value.register.uint32_1 * (uint)(object)factor); + product.register.uint32_2 = (uint)(value.register.uint32_2 * (uint)(object)factor); + product.register.uint32_3 = (uint)(value.register.uint32_3 * (uint)(object)factor); + } + else if (typeof(T) == typeof(int)) + { + product.register.int32_0 = (int)(value.register.int32_0 * (int)(object)factor); + product.register.int32_1 = (int)(value.register.int32_1 * (int)(object)factor); + product.register.int32_2 = (int)(value.register.int32_2 * (int)(object)factor); + product.register.int32_3 = (int)(value.register.int32_3 * (int)(object)factor); + } + else if (typeof(T) == typeof(ulong)) + { + product.register.uint64_0 = (ulong)(value.register.uint64_0 * (ulong)(object)factor); + product.register.uint64_1 = (ulong)(value.register.uint64_1 * (ulong)(object)factor); + } + else if (typeof(T) == typeof(long)) + { + product.register.int64_0 = (long)(value.register.int64_0 * (long)(object)factor); + product.register.int64_1 = (long)(value.register.int64_1 * (long)(object)factor); + } + else if (typeof(T) == typeof(float)) + { + product.register.single_0 = (float)(value.register.single_0 * (float)(object)factor); + product.register.single_1 = (float)(value.register.single_1 * (float)(object)factor); + product.register.single_2 = (float)(value.register.single_2 * (float)(object)factor); + product.register.single_3 = (float)(value.register.single_3 * (float)(object)factor); + } + else if (typeof(T) == typeof(double)) + { + product.register.double_0 = (double)(value.register.double_0 * (double)(object)factor); + product.register.double_1 = (double)(value.register.double_1 * (double)(object)factor); } return product; } @@ -2356,101 +2356,101 @@ public string ToString(string format, IFormatProvider formatProvider) else { Vector product = new Vector(); - if (typeof(T) == typeof(Byte)) - { - product.register.byte_0 = (Byte)(value.register.byte_0 * (Byte)(object)factor); - product.register.byte_1 = (Byte)(value.register.byte_1 * (Byte)(object)factor); - product.register.byte_2 = (Byte)(value.register.byte_2 * (Byte)(object)factor); - product.register.byte_3 = (Byte)(value.register.byte_3 * (Byte)(object)factor); - product.register.byte_4 = (Byte)(value.register.byte_4 * (Byte)(object)factor); - product.register.byte_5 = (Byte)(value.register.byte_5 * (Byte)(object)factor); - product.register.byte_6 = (Byte)(value.register.byte_6 * (Byte)(object)factor); - product.register.byte_7 = (Byte)(value.register.byte_7 * (Byte)(object)factor); - product.register.byte_8 = (Byte)(value.register.byte_8 * (Byte)(object)factor); - product.register.byte_9 = (Byte)(value.register.byte_9 * (Byte)(object)factor); - product.register.byte_10 = (Byte)(value.register.byte_10 * (Byte)(object)factor); - product.register.byte_11 = (Byte)(value.register.byte_11 * (Byte)(object)factor); - product.register.byte_12 = (Byte)(value.register.byte_12 * (Byte)(object)factor); - product.register.byte_13 = (Byte)(value.register.byte_13 * (Byte)(object)factor); - product.register.byte_14 = (Byte)(value.register.byte_14 * (Byte)(object)factor); - product.register.byte_15 = (Byte)(value.register.byte_15 * (Byte)(object)factor); - } - else if (typeof(T) == typeof(SByte)) - { - product.register.sbyte_0 = (SByte)(value.register.sbyte_0 * (SByte)(object)factor); - product.register.sbyte_1 = (SByte)(value.register.sbyte_1 * (SByte)(object)factor); - product.register.sbyte_2 = (SByte)(value.register.sbyte_2 * (SByte)(object)factor); - product.register.sbyte_3 = (SByte)(value.register.sbyte_3 * (SByte)(object)factor); - product.register.sbyte_4 = (SByte)(value.register.sbyte_4 * (SByte)(object)factor); - product.register.sbyte_5 = (SByte)(value.register.sbyte_5 * (SByte)(object)factor); - product.register.sbyte_6 = (SByte)(value.register.sbyte_6 * (SByte)(object)factor); - product.register.sbyte_7 = (SByte)(value.register.sbyte_7 * (SByte)(object)factor); - product.register.sbyte_8 = (SByte)(value.register.sbyte_8 * (SByte)(object)factor); - product.register.sbyte_9 = (SByte)(value.register.sbyte_9 * (SByte)(object)factor); - product.register.sbyte_10 = (SByte)(value.register.sbyte_10 * (SByte)(object)factor); - product.register.sbyte_11 = (SByte)(value.register.sbyte_11 * (SByte)(object)factor); - product.register.sbyte_12 = (SByte)(value.register.sbyte_12 * (SByte)(object)factor); - product.register.sbyte_13 = (SByte)(value.register.sbyte_13 * (SByte)(object)factor); - product.register.sbyte_14 = (SByte)(value.register.sbyte_14 * (SByte)(object)factor); - product.register.sbyte_15 = (SByte)(value.register.sbyte_15 * (SByte)(object)factor); - } - else if (typeof(T) == typeof(UInt16)) - { - product.register.uint16_0 = (UInt16)(value.register.uint16_0 * (UInt16)(object)factor); - product.register.uint16_1 = (UInt16)(value.register.uint16_1 * (UInt16)(object)factor); - product.register.uint16_2 = (UInt16)(value.register.uint16_2 * (UInt16)(object)factor); - product.register.uint16_3 = (UInt16)(value.register.uint16_3 * (UInt16)(object)factor); - product.register.uint16_4 = (UInt16)(value.register.uint16_4 * (UInt16)(object)factor); - product.register.uint16_5 = (UInt16)(value.register.uint16_5 * (UInt16)(object)factor); - product.register.uint16_6 = (UInt16)(value.register.uint16_6 * (UInt16)(object)factor); - product.register.uint16_7 = (UInt16)(value.register.uint16_7 * (UInt16)(object)factor); - } - else if (typeof(T) == typeof(Int16)) - { - product.register.int16_0 = (Int16)(value.register.int16_0 * (Int16)(object)factor); - product.register.int16_1 = (Int16)(value.register.int16_1 * (Int16)(object)factor); - product.register.int16_2 = (Int16)(value.register.int16_2 * (Int16)(object)factor); - product.register.int16_3 = (Int16)(value.register.int16_3 * (Int16)(object)factor); - product.register.int16_4 = (Int16)(value.register.int16_4 * (Int16)(object)factor); - product.register.int16_5 = (Int16)(value.register.int16_5 * (Int16)(object)factor); - product.register.int16_6 = (Int16)(value.register.int16_6 * (Int16)(object)factor); - product.register.int16_7 = (Int16)(value.register.int16_7 * (Int16)(object)factor); - } - else if (typeof(T) == typeof(UInt32)) - { - product.register.uint32_0 = (UInt32)(value.register.uint32_0 * (UInt32)(object)factor); - product.register.uint32_1 = (UInt32)(value.register.uint32_1 * (UInt32)(object)factor); - product.register.uint32_2 = (UInt32)(value.register.uint32_2 * (UInt32)(object)factor); - product.register.uint32_3 = (UInt32)(value.register.uint32_3 * (UInt32)(object)factor); - } - else if (typeof(T) == typeof(Int32)) - { - product.register.int32_0 = (Int32)(value.register.int32_0 * (Int32)(object)factor); - product.register.int32_1 = (Int32)(value.register.int32_1 * (Int32)(object)factor); - product.register.int32_2 = (Int32)(value.register.int32_2 * (Int32)(object)factor); - product.register.int32_3 = (Int32)(value.register.int32_3 * (Int32)(object)factor); - } - else if (typeof(T) == typeof(UInt64)) - { - product.register.uint64_0 = (UInt64)(value.register.uint64_0 * (UInt64)(object)factor); - product.register.uint64_1 = (UInt64)(value.register.uint64_1 * (UInt64)(object)factor); - } - else if (typeof(T) == typeof(Int64)) - { - product.register.int64_0 = (Int64)(value.register.int64_0 * (Int64)(object)factor); - product.register.int64_1 = (Int64)(value.register.int64_1 * (Int64)(object)factor); - } - else if (typeof(T) == typeof(Single)) - { - product.register.single_0 = (Single)(value.register.single_0 * (Single)(object)factor); - product.register.single_1 = (Single)(value.register.single_1 * (Single)(object)factor); - product.register.single_2 = (Single)(value.register.single_2 * (Single)(object)factor); - product.register.single_3 = (Single)(value.register.single_3 * (Single)(object)factor); - } - else if (typeof(T) == typeof(Double)) - { - product.register.double_0 = (Double)(value.register.double_0 * (Double)(object)factor); - product.register.double_1 = (Double)(value.register.double_1 * (Double)(object)factor); + if (typeof(T) == typeof(byte)) + { + product.register.byte_0 = (byte)(value.register.byte_0 * (byte)(object)factor); + product.register.byte_1 = (byte)(value.register.byte_1 * (byte)(object)factor); + product.register.byte_2 = (byte)(value.register.byte_2 * (byte)(object)factor); + product.register.byte_3 = (byte)(value.register.byte_3 * (byte)(object)factor); + product.register.byte_4 = (byte)(value.register.byte_4 * (byte)(object)factor); + product.register.byte_5 = (byte)(value.register.byte_5 * (byte)(object)factor); + product.register.byte_6 = (byte)(value.register.byte_6 * (byte)(object)factor); + product.register.byte_7 = (byte)(value.register.byte_7 * (byte)(object)factor); + product.register.byte_8 = (byte)(value.register.byte_8 * (byte)(object)factor); + product.register.byte_9 = (byte)(value.register.byte_9 * (byte)(object)factor); + product.register.byte_10 = (byte)(value.register.byte_10 * (byte)(object)factor); + product.register.byte_11 = (byte)(value.register.byte_11 * (byte)(object)factor); + product.register.byte_12 = (byte)(value.register.byte_12 * (byte)(object)factor); + product.register.byte_13 = (byte)(value.register.byte_13 * (byte)(object)factor); + product.register.byte_14 = (byte)(value.register.byte_14 * (byte)(object)factor); + product.register.byte_15 = (byte)(value.register.byte_15 * (byte)(object)factor); + } + else if (typeof(T) == typeof(sbyte)) + { + product.register.sbyte_0 = (sbyte)(value.register.sbyte_0 * (sbyte)(object)factor); + product.register.sbyte_1 = (sbyte)(value.register.sbyte_1 * (sbyte)(object)factor); + product.register.sbyte_2 = (sbyte)(value.register.sbyte_2 * (sbyte)(object)factor); + product.register.sbyte_3 = (sbyte)(value.register.sbyte_3 * (sbyte)(object)factor); + product.register.sbyte_4 = (sbyte)(value.register.sbyte_4 * (sbyte)(object)factor); + product.register.sbyte_5 = (sbyte)(value.register.sbyte_5 * (sbyte)(object)factor); + product.register.sbyte_6 = (sbyte)(value.register.sbyte_6 * (sbyte)(object)factor); + product.register.sbyte_7 = (sbyte)(value.register.sbyte_7 * (sbyte)(object)factor); + product.register.sbyte_8 = (sbyte)(value.register.sbyte_8 * (sbyte)(object)factor); + product.register.sbyte_9 = (sbyte)(value.register.sbyte_9 * (sbyte)(object)factor); + product.register.sbyte_10 = (sbyte)(value.register.sbyte_10 * (sbyte)(object)factor); + product.register.sbyte_11 = (sbyte)(value.register.sbyte_11 * (sbyte)(object)factor); + product.register.sbyte_12 = (sbyte)(value.register.sbyte_12 * (sbyte)(object)factor); + product.register.sbyte_13 = (sbyte)(value.register.sbyte_13 * (sbyte)(object)factor); + product.register.sbyte_14 = (sbyte)(value.register.sbyte_14 * (sbyte)(object)factor); + product.register.sbyte_15 = (sbyte)(value.register.sbyte_15 * (sbyte)(object)factor); + } + else if (typeof(T) == typeof(ushort)) + { + product.register.uint16_0 = (ushort)(value.register.uint16_0 * (ushort)(object)factor); + product.register.uint16_1 = (ushort)(value.register.uint16_1 * (ushort)(object)factor); + product.register.uint16_2 = (ushort)(value.register.uint16_2 * (ushort)(object)factor); + product.register.uint16_3 = (ushort)(value.register.uint16_3 * (ushort)(object)factor); + product.register.uint16_4 = (ushort)(value.register.uint16_4 * (ushort)(object)factor); + product.register.uint16_5 = (ushort)(value.register.uint16_5 * (ushort)(object)factor); + product.register.uint16_6 = (ushort)(value.register.uint16_6 * (ushort)(object)factor); + product.register.uint16_7 = (ushort)(value.register.uint16_7 * (ushort)(object)factor); + } + else if (typeof(T) == typeof(short)) + { + product.register.int16_0 = (short)(value.register.int16_0 * (short)(object)factor); + product.register.int16_1 = (short)(value.register.int16_1 * (short)(object)factor); + product.register.int16_2 = (short)(value.register.int16_2 * (short)(object)factor); + product.register.int16_3 = (short)(value.register.int16_3 * (short)(object)factor); + product.register.int16_4 = (short)(value.register.int16_4 * (short)(object)factor); + product.register.int16_5 = (short)(value.register.int16_5 * (short)(object)factor); + product.register.int16_6 = (short)(value.register.int16_6 * (short)(object)factor); + product.register.int16_7 = (short)(value.register.int16_7 * (short)(object)factor); + } + else if (typeof(T) == typeof(uint)) + { + product.register.uint32_0 = (uint)(value.register.uint32_0 * (uint)(object)factor); + product.register.uint32_1 = (uint)(value.register.uint32_1 * (uint)(object)factor); + product.register.uint32_2 = (uint)(value.register.uint32_2 * (uint)(object)factor); + product.register.uint32_3 = (uint)(value.register.uint32_3 * (uint)(object)factor); + } + else if (typeof(T) == typeof(int)) + { + product.register.int32_0 = (int)(value.register.int32_0 * (int)(object)factor); + product.register.int32_1 = (int)(value.register.int32_1 * (int)(object)factor); + product.register.int32_2 = (int)(value.register.int32_2 * (int)(object)factor); + product.register.int32_3 = (int)(value.register.int32_3 * (int)(object)factor); + } + else if (typeof(T) == typeof(ulong)) + { + product.register.uint64_0 = (ulong)(value.register.uint64_0 * (ulong)(object)factor); + product.register.uint64_1 = (ulong)(value.register.uint64_1 * (ulong)(object)factor); + } + else if (typeof(T) == typeof(long)) + { + product.register.int64_0 = (long)(value.register.int64_0 * (long)(object)factor); + product.register.int64_1 = (long)(value.register.int64_1 * (long)(object)factor); + } + else if (typeof(T) == typeof(float)) + { + product.register.single_0 = (float)(value.register.single_0 * (float)(object)factor); + product.register.single_1 = (float)(value.register.single_1 * (float)(object)factor); + product.register.single_2 = (float)(value.register.single_2 * (float)(object)factor); + product.register.single_3 = (float)(value.register.single_3 * (float)(object)factor); + } + else if (typeof(T) == typeof(double)) + { + product.register.double_0 = (double)(value.register.double_0 * (double)(object)factor); + product.register.double_1 = (double)(value.register.double_1 * (double)(object)factor); } return product; } @@ -2470,93 +2470,93 @@ public string ToString(string format, IFormatProvider formatProvider) { if (Vector.IsHardwareAccelerated) { - if (typeof(T) == typeof(Byte)) + if (typeof(T) == typeof(byte)) { - Byte* dataPtr = stackalloc Byte[Count]; + byte* dataPtr = stackalloc byte[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (Byte)(object)ScalarDivide(left[g], right[g]); + dataPtr[g] = (byte)(object)ScalarDivide(left[g], right[g]); } return new Vector(dataPtr); } - else if (typeof(T) == typeof(SByte)) + else if (typeof(T) == typeof(sbyte)) { - SByte* dataPtr = stackalloc SByte[Count]; + sbyte* dataPtr = stackalloc sbyte[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (SByte)(object)ScalarDivide(left[g], right[g]); + dataPtr[g] = (sbyte)(object)ScalarDivide(left[g], right[g]); } return new Vector(dataPtr); } - else if (typeof(T) == typeof(UInt16)) + else if (typeof(T) == typeof(ushort)) { - UInt16* dataPtr = stackalloc UInt16[Count]; + ushort* dataPtr = stackalloc ushort[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (UInt16)(object)ScalarDivide(left[g], right[g]); + dataPtr[g] = (ushort)(object)ScalarDivide(left[g], right[g]); } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Int16)) + else if (typeof(T) == typeof(short)) { - Int16* dataPtr = stackalloc Int16[Count]; + short* dataPtr = stackalloc short[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (Int16)(object)ScalarDivide(left[g], right[g]); + dataPtr[g] = (short)(object)ScalarDivide(left[g], right[g]); } return new Vector(dataPtr); } - else if (typeof(T) == typeof(UInt32)) + else if (typeof(T) == typeof(uint)) { - UInt32* dataPtr = stackalloc UInt32[Count]; + uint* dataPtr = stackalloc uint[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (UInt32)(object)ScalarDivide(left[g], right[g]); + dataPtr[g] = (uint)(object)ScalarDivide(left[g], right[g]); } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Int32)) + else if (typeof(T) == typeof(int)) { - Int32* dataPtr = stackalloc Int32[Count]; + int* dataPtr = stackalloc int[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (Int32)(object)ScalarDivide(left[g], right[g]); + dataPtr[g] = (int)(object)ScalarDivide(left[g], right[g]); } return new Vector(dataPtr); } - else if (typeof(T) == typeof(UInt64)) + else if (typeof(T) == typeof(ulong)) { - UInt64* dataPtr = stackalloc UInt64[Count]; + ulong* dataPtr = stackalloc ulong[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (UInt64)(object)ScalarDivide(left[g], right[g]); + dataPtr[g] = (ulong)(object)ScalarDivide(left[g], right[g]); } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Int64)) + else if (typeof(T) == typeof(long)) { - Int64* dataPtr = stackalloc Int64[Count]; + long* dataPtr = stackalloc long[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (Int64)(object)ScalarDivide(left[g], right[g]); + dataPtr[g] = (long)(object)ScalarDivide(left[g], right[g]); } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Single)) + else if (typeof(T) == typeof(float)) { - Single* dataPtr = stackalloc Single[Count]; + float* dataPtr = stackalloc float[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (Single)(object)ScalarDivide(left[g], right[g]); + dataPtr[g] = (float)(object)ScalarDivide(left[g], right[g]); } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Double)) + else if (typeof(T) == typeof(double)) { - Double* dataPtr = stackalloc Double[Count]; + double* dataPtr = stackalloc double[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (Double)(object)ScalarDivide(left[g], right[g]); + dataPtr[g] = (double)(object)ScalarDivide(left[g], right[g]); } return new Vector(dataPtr); } @@ -2568,101 +2568,101 @@ public string ToString(string format, IFormatProvider formatProvider) else { Vector quotient = new Vector(); - if (typeof(T) == typeof(Byte)) - { - quotient.register.byte_0 = (Byte)(left.register.byte_0 / right.register.byte_0); - quotient.register.byte_1 = (Byte)(left.register.byte_1 / right.register.byte_1); - quotient.register.byte_2 = (Byte)(left.register.byte_2 / right.register.byte_2); - quotient.register.byte_3 = (Byte)(left.register.byte_3 / right.register.byte_3); - quotient.register.byte_4 = (Byte)(left.register.byte_4 / right.register.byte_4); - quotient.register.byte_5 = (Byte)(left.register.byte_5 / right.register.byte_5); - quotient.register.byte_6 = (Byte)(left.register.byte_6 / right.register.byte_6); - quotient.register.byte_7 = (Byte)(left.register.byte_7 / right.register.byte_7); - quotient.register.byte_8 = (Byte)(left.register.byte_8 / right.register.byte_8); - quotient.register.byte_9 = (Byte)(left.register.byte_9 / right.register.byte_9); - quotient.register.byte_10 = (Byte)(left.register.byte_10 / right.register.byte_10); - quotient.register.byte_11 = (Byte)(left.register.byte_11 / right.register.byte_11); - quotient.register.byte_12 = (Byte)(left.register.byte_12 / right.register.byte_12); - quotient.register.byte_13 = (Byte)(left.register.byte_13 / right.register.byte_13); - quotient.register.byte_14 = (Byte)(left.register.byte_14 / right.register.byte_14); - quotient.register.byte_15 = (Byte)(left.register.byte_15 / right.register.byte_15); - } - else if (typeof(T) == typeof(SByte)) - { - quotient.register.sbyte_0 = (SByte)(left.register.sbyte_0 / right.register.sbyte_0); - quotient.register.sbyte_1 = (SByte)(left.register.sbyte_1 / right.register.sbyte_1); - quotient.register.sbyte_2 = (SByte)(left.register.sbyte_2 / right.register.sbyte_2); - quotient.register.sbyte_3 = (SByte)(left.register.sbyte_3 / right.register.sbyte_3); - quotient.register.sbyte_4 = (SByte)(left.register.sbyte_4 / right.register.sbyte_4); - quotient.register.sbyte_5 = (SByte)(left.register.sbyte_5 / right.register.sbyte_5); - quotient.register.sbyte_6 = (SByte)(left.register.sbyte_6 / right.register.sbyte_6); - quotient.register.sbyte_7 = (SByte)(left.register.sbyte_7 / right.register.sbyte_7); - quotient.register.sbyte_8 = (SByte)(left.register.sbyte_8 / right.register.sbyte_8); - quotient.register.sbyte_9 = (SByte)(left.register.sbyte_9 / right.register.sbyte_9); - quotient.register.sbyte_10 = (SByte)(left.register.sbyte_10 / right.register.sbyte_10); - quotient.register.sbyte_11 = (SByte)(left.register.sbyte_11 / right.register.sbyte_11); - quotient.register.sbyte_12 = (SByte)(left.register.sbyte_12 / right.register.sbyte_12); - quotient.register.sbyte_13 = (SByte)(left.register.sbyte_13 / right.register.sbyte_13); - quotient.register.sbyte_14 = (SByte)(left.register.sbyte_14 / right.register.sbyte_14); - quotient.register.sbyte_15 = (SByte)(left.register.sbyte_15 / right.register.sbyte_15); - } - else if (typeof(T) == typeof(UInt16)) - { - quotient.register.uint16_0 = (UInt16)(left.register.uint16_0 / right.register.uint16_0); - quotient.register.uint16_1 = (UInt16)(left.register.uint16_1 / right.register.uint16_1); - quotient.register.uint16_2 = (UInt16)(left.register.uint16_2 / right.register.uint16_2); - quotient.register.uint16_3 = (UInt16)(left.register.uint16_3 / right.register.uint16_3); - quotient.register.uint16_4 = (UInt16)(left.register.uint16_4 / right.register.uint16_4); - quotient.register.uint16_5 = (UInt16)(left.register.uint16_5 / right.register.uint16_5); - quotient.register.uint16_6 = (UInt16)(left.register.uint16_6 / right.register.uint16_6); - quotient.register.uint16_7 = (UInt16)(left.register.uint16_7 / right.register.uint16_7); - } - else if (typeof(T) == typeof(Int16)) - { - quotient.register.int16_0 = (Int16)(left.register.int16_0 / right.register.int16_0); - quotient.register.int16_1 = (Int16)(left.register.int16_1 / right.register.int16_1); - quotient.register.int16_2 = (Int16)(left.register.int16_2 / right.register.int16_2); - quotient.register.int16_3 = (Int16)(left.register.int16_3 / right.register.int16_3); - quotient.register.int16_4 = (Int16)(left.register.int16_4 / right.register.int16_4); - quotient.register.int16_5 = (Int16)(left.register.int16_5 / right.register.int16_5); - quotient.register.int16_6 = (Int16)(left.register.int16_6 / right.register.int16_6); - quotient.register.int16_7 = (Int16)(left.register.int16_7 / right.register.int16_7); - } - else if (typeof(T) == typeof(UInt32)) - { - quotient.register.uint32_0 = (UInt32)(left.register.uint32_0 / right.register.uint32_0); - quotient.register.uint32_1 = (UInt32)(left.register.uint32_1 / right.register.uint32_1); - quotient.register.uint32_2 = (UInt32)(left.register.uint32_2 / right.register.uint32_2); - quotient.register.uint32_3 = (UInt32)(left.register.uint32_3 / right.register.uint32_3); - } - else if (typeof(T) == typeof(Int32)) - { - quotient.register.int32_0 = (Int32)(left.register.int32_0 / right.register.int32_0); - quotient.register.int32_1 = (Int32)(left.register.int32_1 / right.register.int32_1); - quotient.register.int32_2 = (Int32)(left.register.int32_2 / right.register.int32_2); - quotient.register.int32_3 = (Int32)(left.register.int32_3 / right.register.int32_3); - } - else if (typeof(T) == typeof(UInt64)) - { - quotient.register.uint64_0 = (UInt64)(left.register.uint64_0 / right.register.uint64_0); - quotient.register.uint64_1 = (UInt64)(left.register.uint64_1 / right.register.uint64_1); - } - else if (typeof(T) == typeof(Int64)) - { - quotient.register.int64_0 = (Int64)(left.register.int64_0 / right.register.int64_0); - quotient.register.int64_1 = (Int64)(left.register.int64_1 / right.register.int64_1); - } - else if (typeof(T) == typeof(Single)) - { - quotient.register.single_0 = (Single)(left.register.single_0 / right.register.single_0); - quotient.register.single_1 = (Single)(left.register.single_1 / right.register.single_1); - quotient.register.single_2 = (Single)(left.register.single_2 / right.register.single_2); - quotient.register.single_3 = (Single)(left.register.single_3 / right.register.single_3); - } - else if (typeof(T) == typeof(Double)) - { - quotient.register.double_0 = (Double)(left.register.double_0 / right.register.double_0); - quotient.register.double_1 = (Double)(left.register.double_1 / right.register.double_1); + if (typeof(T) == typeof(byte)) + { + quotient.register.byte_0 = (byte)(left.register.byte_0 / right.register.byte_0); + quotient.register.byte_1 = (byte)(left.register.byte_1 / right.register.byte_1); + quotient.register.byte_2 = (byte)(left.register.byte_2 / right.register.byte_2); + quotient.register.byte_3 = (byte)(left.register.byte_3 / right.register.byte_3); + quotient.register.byte_4 = (byte)(left.register.byte_4 / right.register.byte_4); + quotient.register.byte_5 = (byte)(left.register.byte_5 / right.register.byte_5); + quotient.register.byte_6 = (byte)(left.register.byte_6 / right.register.byte_6); + quotient.register.byte_7 = (byte)(left.register.byte_7 / right.register.byte_7); + quotient.register.byte_8 = (byte)(left.register.byte_8 / right.register.byte_8); + quotient.register.byte_9 = (byte)(left.register.byte_9 / right.register.byte_9); + quotient.register.byte_10 = (byte)(left.register.byte_10 / right.register.byte_10); + quotient.register.byte_11 = (byte)(left.register.byte_11 / right.register.byte_11); + quotient.register.byte_12 = (byte)(left.register.byte_12 / right.register.byte_12); + quotient.register.byte_13 = (byte)(left.register.byte_13 / right.register.byte_13); + quotient.register.byte_14 = (byte)(left.register.byte_14 / right.register.byte_14); + quotient.register.byte_15 = (byte)(left.register.byte_15 / right.register.byte_15); + } + else if (typeof(T) == typeof(sbyte)) + { + quotient.register.sbyte_0 = (sbyte)(left.register.sbyte_0 / right.register.sbyte_0); + quotient.register.sbyte_1 = (sbyte)(left.register.sbyte_1 / right.register.sbyte_1); + quotient.register.sbyte_2 = (sbyte)(left.register.sbyte_2 / right.register.sbyte_2); + quotient.register.sbyte_3 = (sbyte)(left.register.sbyte_3 / right.register.sbyte_3); + quotient.register.sbyte_4 = (sbyte)(left.register.sbyte_4 / right.register.sbyte_4); + quotient.register.sbyte_5 = (sbyte)(left.register.sbyte_5 / right.register.sbyte_5); + quotient.register.sbyte_6 = (sbyte)(left.register.sbyte_6 / right.register.sbyte_6); + quotient.register.sbyte_7 = (sbyte)(left.register.sbyte_7 / right.register.sbyte_7); + quotient.register.sbyte_8 = (sbyte)(left.register.sbyte_8 / right.register.sbyte_8); + quotient.register.sbyte_9 = (sbyte)(left.register.sbyte_9 / right.register.sbyte_9); + quotient.register.sbyte_10 = (sbyte)(left.register.sbyte_10 / right.register.sbyte_10); + quotient.register.sbyte_11 = (sbyte)(left.register.sbyte_11 / right.register.sbyte_11); + quotient.register.sbyte_12 = (sbyte)(left.register.sbyte_12 / right.register.sbyte_12); + quotient.register.sbyte_13 = (sbyte)(left.register.sbyte_13 / right.register.sbyte_13); + quotient.register.sbyte_14 = (sbyte)(left.register.sbyte_14 / right.register.sbyte_14); + quotient.register.sbyte_15 = (sbyte)(left.register.sbyte_15 / right.register.sbyte_15); + } + else if (typeof(T) == typeof(ushort)) + { + quotient.register.uint16_0 = (ushort)(left.register.uint16_0 / right.register.uint16_0); + quotient.register.uint16_1 = (ushort)(left.register.uint16_1 / right.register.uint16_1); + quotient.register.uint16_2 = (ushort)(left.register.uint16_2 / right.register.uint16_2); + quotient.register.uint16_3 = (ushort)(left.register.uint16_3 / right.register.uint16_3); + quotient.register.uint16_4 = (ushort)(left.register.uint16_4 / right.register.uint16_4); + quotient.register.uint16_5 = (ushort)(left.register.uint16_5 / right.register.uint16_5); + quotient.register.uint16_6 = (ushort)(left.register.uint16_6 / right.register.uint16_6); + quotient.register.uint16_7 = (ushort)(left.register.uint16_7 / right.register.uint16_7); + } + else if (typeof(T) == typeof(short)) + { + quotient.register.int16_0 = (short)(left.register.int16_0 / right.register.int16_0); + quotient.register.int16_1 = (short)(left.register.int16_1 / right.register.int16_1); + quotient.register.int16_2 = (short)(left.register.int16_2 / right.register.int16_2); + quotient.register.int16_3 = (short)(left.register.int16_3 / right.register.int16_3); + quotient.register.int16_4 = (short)(left.register.int16_4 / right.register.int16_4); + quotient.register.int16_5 = (short)(left.register.int16_5 / right.register.int16_5); + quotient.register.int16_6 = (short)(left.register.int16_6 / right.register.int16_6); + quotient.register.int16_7 = (short)(left.register.int16_7 / right.register.int16_7); + } + else if (typeof(T) == typeof(uint)) + { + quotient.register.uint32_0 = (uint)(left.register.uint32_0 / right.register.uint32_0); + quotient.register.uint32_1 = (uint)(left.register.uint32_1 / right.register.uint32_1); + quotient.register.uint32_2 = (uint)(left.register.uint32_2 / right.register.uint32_2); + quotient.register.uint32_3 = (uint)(left.register.uint32_3 / right.register.uint32_3); + } + else if (typeof(T) == typeof(int)) + { + quotient.register.int32_0 = (int)(left.register.int32_0 / right.register.int32_0); + quotient.register.int32_1 = (int)(left.register.int32_1 / right.register.int32_1); + quotient.register.int32_2 = (int)(left.register.int32_2 / right.register.int32_2); + quotient.register.int32_3 = (int)(left.register.int32_3 / right.register.int32_3); + } + else if (typeof(T) == typeof(ulong)) + { + quotient.register.uint64_0 = (ulong)(left.register.uint64_0 / right.register.uint64_0); + quotient.register.uint64_1 = (ulong)(left.register.uint64_1 / right.register.uint64_1); + } + else if (typeof(T) == typeof(long)) + { + quotient.register.int64_0 = (long)(left.register.int64_0 / right.register.int64_0); + quotient.register.int64_1 = (long)(left.register.int64_1 / right.register.int64_1); + } + else if (typeof(T) == typeof(float)) + { + quotient.register.single_0 = (float)(left.register.single_0 / right.register.single_0); + quotient.register.single_1 = (float)(left.register.single_1 / right.register.single_1); + quotient.register.single_2 = (float)(left.register.single_2 / right.register.single_2); + quotient.register.single_3 = (float)(left.register.single_3 / right.register.single_3); + } + else if (typeof(T) == typeof(double)) + { + quotient.register.double_0 = (double)(left.register.double_0 / right.register.double_0); + quotient.register.double_1 = (double)(left.register.double_1 / right.register.double_1); } return quotient; } @@ -2695,10 +2695,10 @@ public string ToString(string format, IFormatProvider formatProvider) { if (Vector.IsHardwareAccelerated) { - Int64* resultBase = &result.register.int64_0; - Int64* leftBase = &left.register.int64_0; - Int64* rightBase = &right.register.int64_0; - for (int g = 0; g < Vector.Count; g++) + long* resultBase = &result.register.int64_0; + long* leftBase = &left.register.int64_0; + long* rightBase = &right.register.int64_0; + for (int g = 0; g < Vector.Count; g++) { resultBase[g] = leftBase[g] & rightBase[g]; } @@ -2726,10 +2726,10 @@ public string ToString(string format, IFormatProvider formatProvider) { if (Vector.IsHardwareAccelerated) { - Int64* resultBase = &result.register.int64_0; - Int64* leftBase = &left.register.int64_0; - Int64* rightBase = &right.register.int64_0; - for (int g = 0; g < Vector.Count; g++) + long* resultBase = &result.register.int64_0; + long* leftBase = &left.register.int64_0; + long* rightBase = &right.register.int64_0; + for (int g = 0; g < Vector.Count; g++) { resultBase[g] = leftBase[g] | rightBase[g]; } @@ -2757,10 +2757,10 @@ public string ToString(string format, IFormatProvider formatProvider) { if (Vector.IsHardwareAccelerated) { - Int64* resultBase = &result.register.int64_0; - Int64* leftBase = &left.register.int64_0; - Int64* rightBase = &right.register.int64_0; - for (int g = 0; g < Vector.Count; g++) + long* resultBase = &result.register.int64_0; + long* leftBase = &left.register.int64_0; + long* rightBase = &right.register.int64_0; + for (int g = 0; g < Vector.Count; g++) { resultBase[g] = leftBase[g] ^ rightBase[g]; } @@ -2819,9 +2819,9 @@ public string ToString(string format, IFormatProvider formatProvider) /// The source vector /// The reinterpreted vector. [Intrinsic] - public static explicit operator Vector(Vector value) + public static explicit operator Vector(Vector value) { - return new Vector(ref value.register); + return new Vector(ref value.register); } /// @@ -2831,9 +2831,9 @@ public string ToString(string format, IFormatProvider formatProvider) /// The reinterpreted vector. [CLSCompliant(false)] [Intrinsic] - public static explicit operator Vector(Vector value) + public static explicit operator Vector(Vector value) { - return new Vector(ref value.register); + return new Vector(ref value.register); } /// @@ -2843,9 +2843,9 @@ public string ToString(string format, IFormatProvider formatProvider) /// The reinterpreted vector. [CLSCompliant(false)] [Intrinsic] - public static explicit operator Vector(Vector value) + public static explicit operator Vector(Vector value) { - return new Vector(ref value.register); + return new Vector(ref value.register); } /// @@ -2854,9 +2854,9 @@ public string ToString(string format, IFormatProvider formatProvider) /// The source vector /// The reinterpreted vector. [Intrinsic] - public static explicit operator Vector(Vector value) + public static explicit operator Vector(Vector value) { - return new Vector(ref value.register); + return new Vector(ref value.register); } /// @@ -2866,9 +2866,9 @@ public string ToString(string format, IFormatProvider formatProvider) /// The reinterpreted vector. [CLSCompliant(false)] [Intrinsic] - public static explicit operator Vector(Vector value) + public static explicit operator Vector(Vector value) { - return new Vector(ref value.register); + return new Vector(ref value.register); } /// @@ -2877,9 +2877,9 @@ public string ToString(string format, IFormatProvider formatProvider) /// The source vector /// The reinterpreted vector. [Intrinsic] - public static explicit operator Vector(Vector value) + public static explicit operator Vector(Vector value) { - return new Vector(ref value.register); + return new Vector(ref value.register); } /// @@ -2889,9 +2889,9 @@ public string ToString(string format, IFormatProvider formatProvider) /// The reinterpreted vector. [CLSCompliant(false)] [Intrinsic] - public static explicit operator Vector(Vector value) + public static explicit operator Vector(Vector value) { - return new Vector(ref value.register); + return new Vector(ref value.register); } /// @@ -2900,9 +2900,9 @@ public string ToString(string format, IFormatProvider formatProvider) /// The source vector /// The reinterpreted vector. [Intrinsic] - public static explicit operator Vector(Vector value) + public static explicit operator Vector(Vector value) { - return new Vector(ref value.register); + return new Vector(ref value.register); } /// @@ -2911,9 +2911,9 @@ public string ToString(string format, IFormatProvider formatProvider) /// The source vector /// The reinterpreted vector. [Intrinsic] - public static explicit operator Vector(Vector value) + public static explicit operator Vector(Vector value) { - return new Vector(ref value.register); + return new Vector(ref value.register); } /// @@ -2922,9 +2922,9 @@ public string ToString(string format, IFormatProvider formatProvider) /// The source vector /// The reinterpreted vector. [Intrinsic] - public static explicit operator Vector(Vector value) + public static explicit operator Vector(Vector value) { - return new Vector(ref value.register); + return new Vector(ref value.register); } #endregion Conversions @@ -2936,93 +2936,93 @@ internal static unsafe Vector Equals(Vector left, Vector right) { if (Vector.IsHardwareAccelerated) { - if (typeof(T) == typeof(Byte)) + if (typeof(T) == typeof(byte)) { - Byte* dataPtr = stackalloc Byte[Count]; + byte* dataPtr = stackalloc byte[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarEquals(left[g], right[g]) ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; + dataPtr[g] = ScalarEquals(left[g], right[g]) ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; } return new Vector(dataPtr); } - else if (typeof(T) == typeof(SByte)) + else if (typeof(T) == typeof(sbyte)) { - SByte* dataPtr = stackalloc SByte[Count]; + sbyte* dataPtr = stackalloc sbyte[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarEquals(left[g], right[g]) ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; + dataPtr[g] = ScalarEquals(left[g], right[g]) ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; } return new Vector(dataPtr); } - else if (typeof(T) == typeof(UInt16)) + else if (typeof(T) == typeof(ushort)) { - UInt16* dataPtr = stackalloc UInt16[Count]; + ushort* dataPtr = stackalloc ushort[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarEquals(left[g], right[g]) ? ConstantHelper.GetUInt16WithAllBitsSet() : (UInt16)0; + dataPtr[g] = ScalarEquals(left[g], right[g]) ? ConstantHelper.GetUInt16WithAllBitsSet() : (ushort)0; } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Int16)) + else if (typeof(T) == typeof(short)) { - Int16* dataPtr = stackalloc Int16[Count]; + short* dataPtr = stackalloc short[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarEquals(left[g], right[g]) ? ConstantHelper.GetInt16WithAllBitsSet() : (Int16)0; + dataPtr[g] = ScalarEquals(left[g], right[g]) ? ConstantHelper.GetInt16WithAllBitsSet() : (short)0; } return new Vector(dataPtr); } - else if (typeof(T) == typeof(UInt32)) + else if (typeof(T) == typeof(uint)) { - UInt32* dataPtr = stackalloc UInt32[Count]; + uint* dataPtr = stackalloc uint[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarEquals(left[g], right[g]) ? ConstantHelper.GetUInt32WithAllBitsSet() : (UInt32)0; + dataPtr[g] = ScalarEquals(left[g], right[g]) ? ConstantHelper.GetUInt32WithAllBitsSet() : (uint)0; } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Int32)) + else if (typeof(T) == typeof(int)) { - Int32* dataPtr = stackalloc Int32[Count]; + int* dataPtr = stackalloc int[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarEquals(left[g], right[g]) ? ConstantHelper.GetInt32WithAllBitsSet() : (Int32)0; + dataPtr[g] = ScalarEquals(left[g], right[g]) ? ConstantHelper.GetInt32WithAllBitsSet() : (int)0; } return new Vector(dataPtr); } - else if (typeof(T) == typeof(UInt64)) + else if (typeof(T) == typeof(ulong)) { - UInt64* dataPtr = stackalloc UInt64[Count]; + ulong* dataPtr = stackalloc ulong[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarEquals(left[g], right[g]) ? ConstantHelper.GetUInt64WithAllBitsSet() : (UInt64)0; + dataPtr[g] = ScalarEquals(left[g], right[g]) ? ConstantHelper.GetUInt64WithAllBitsSet() : (ulong)0; } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Int64)) + else if (typeof(T) == typeof(long)) { - Int64* dataPtr = stackalloc Int64[Count]; + long* dataPtr = stackalloc long[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarEquals(left[g], right[g]) ? ConstantHelper.GetInt64WithAllBitsSet() : (Int64)0; + dataPtr[g] = ScalarEquals(left[g], right[g]) ? ConstantHelper.GetInt64WithAllBitsSet() : (long)0; } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Single)) + else if (typeof(T) == typeof(float)) { - Single* dataPtr = stackalloc Single[Count]; + float* dataPtr = stackalloc float[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarEquals(left[g], right[g]) ? ConstantHelper.GetSingleWithAllBitsSet() : (Single)0; + dataPtr[g] = ScalarEquals(left[g], right[g]) ? ConstantHelper.GetSingleWithAllBitsSet() : (float)0; } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Double)) + else if (typeof(T) == typeof(double)) { - Double* dataPtr = stackalloc Double[Count]; + double* dataPtr = stackalloc double[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarEquals(left[g], right[g]) ? ConstantHelper.GetDoubleWithAllBitsSet() : (Double)0; + dataPtr[g] = ScalarEquals(left[g], right[g]) ? ConstantHelper.GetDoubleWithAllBitsSet() : (double)0; } return new Vector(dataPtr); } @@ -3034,110 +3034,110 @@ internal static unsafe Vector Equals(Vector left, Vector right) else { Register register = new Register(); - if (typeof(T) == typeof(Byte)) - { - register.byte_0 = left.register.byte_0 == right.register.byte_0 ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; - register.byte_1 = left.register.byte_1 == right.register.byte_1 ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; - register.byte_2 = left.register.byte_2 == right.register.byte_2 ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; - register.byte_3 = left.register.byte_3 == right.register.byte_3 ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; - register.byte_4 = left.register.byte_4 == right.register.byte_4 ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; - register.byte_5 = left.register.byte_5 == right.register.byte_5 ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; - register.byte_6 = left.register.byte_6 == right.register.byte_6 ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; - register.byte_7 = left.register.byte_7 == right.register.byte_7 ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; - register.byte_8 = left.register.byte_8 == right.register.byte_8 ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; - register.byte_9 = left.register.byte_9 == right.register.byte_9 ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; - register.byte_10 = left.register.byte_10 == right.register.byte_10 ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; - register.byte_11 = left.register.byte_11 == right.register.byte_11 ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; - register.byte_12 = left.register.byte_12 == right.register.byte_12 ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; - register.byte_13 = left.register.byte_13 == right.register.byte_13 ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; - register.byte_14 = left.register.byte_14 == right.register.byte_14 ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; - register.byte_15 = left.register.byte_15 == right.register.byte_15 ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; + if (typeof(T) == typeof(byte)) + { + register.byte_0 = left.register.byte_0 == right.register.byte_0 ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; + register.byte_1 = left.register.byte_1 == right.register.byte_1 ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; + register.byte_2 = left.register.byte_2 == right.register.byte_2 ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; + register.byte_3 = left.register.byte_3 == right.register.byte_3 ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; + register.byte_4 = left.register.byte_4 == right.register.byte_4 ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; + register.byte_5 = left.register.byte_5 == right.register.byte_5 ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; + register.byte_6 = left.register.byte_6 == right.register.byte_6 ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; + register.byte_7 = left.register.byte_7 == right.register.byte_7 ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; + register.byte_8 = left.register.byte_8 == right.register.byte_8 ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; + register.byte_9 = left.register.byte_9 == right.register.byte_9 ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; + register.byte_10 = left.register.byte_10 == right.register.byte_10 ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; + register.byte_11 = left.register.byte_11 == right.register.byte_11 ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; + register.byte_12 = left.register.byte_12 == right.register.byte_12 ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; + register.byte_13 = left.register.byte_13 == right.register.byte_13 ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; + register.byte_14 = left.register.byte_14 == right.register.byte_14 ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; + register.byte_15 = left.register.byte_15 == right.register.byte_15 ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; return new Vector(ref register); } - else if (typeof(T) == typeof(SByte)) - { - register.sbyte_0 = left.register.sbyte_0 == right.register.sbyte_0 ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; - register.sbyte_1 = left.register.sbyte_1 == right.register.sbyte_1 ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; - register.sbyte_2 = left.register.sbyte_2 == right.register.sbyte_2 ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; - register.sbyte_3 = left.register.sbyte_3 == right.register.sbyte_3 ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; - register.sbyte_4 = left.register.sbyte_4 == right.register.sbyte_4 ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; - register.sbyte_5 = left.register.sbyte_5 == right.register.sbyte_5 ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; - register.sbyte_6 = left.register.sbyte_6 == right.register.sbyte_6 ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; - register.sbyte_7 = left.register.sbyte_7 == right.register.sbyte_7 ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; - register.sbyte_8 = left.register.sbyte_8 == right.register.sbyte_8 ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; - register.sbyte_9 = left.register.sbyte_9 == right.register.sbyte_9 ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; - register.sbyte_10 = left.register.sbyte_10 == right.register.sbyte_10 ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; - register.sbyte_11 = left.register.sbyte_11 == right.register.sbyte_11 ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; - register.sbyte_12 = left.register.sbyte_12 == right.register.sbyte_12 ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; - register.sbyte_13 = left.register.sbyte_13 == right.register.sbyte_13 ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; - register.sbyte_14 = left.register.sbyte_14 == right.register.sbyte_14 ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; - register.sbyte_15 = left.register.sbyte_15 == right.register.sbyte_15 ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; + else if (typeof(T) == typeof(sbyte)) + { + register.sbyte_0 = left.register.sbyte_0 == right.register.sbyte_0 ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; + register.sbyte_1 = left.register.sbyte_1 == right.register.sbyte_1 ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; + register.sbyte_2 = left.register.sbyte_2 == right.register.sbyte_2 ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; + register.sbyte_3 = left.register.sbyte_3 == right.register.sbyte_3 ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; + register.sbyte_4 = left.register.sbyte_4 == right.register.sbyte_4 ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; + register.sbyte_5 = left.register.sbyte_5 == right.register.sbyte_5 ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; + register.sbyte_6 = left.register.sbyte_6 == right.register.sbyte_6 ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; + register.sbyte_7 = left.register.sbyte_7 == right.register.sbyte_7 ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; + register.sbyte_8 = left.register.sbyte_8 == right.register.sbyte_8 ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; + register.sbyte_9 = left.register.sbyte_9 == right.register.sbyte_9 ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; + register.sbyte_10 = left.register.sbyte_10 == right.register.sbyte_10 ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; + register.sbyte_11 = left.register.sbyte_11 == right.register.sbyte_11 ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; + register.sbyte_12 = left.register.sbyte_12 == right.register.sbyte_12 ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; + register.sbyte_13 = left.register.sbyte_13 == right.register.sbyte_13 ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; + register.sbyte_14 = left.register.sbyte_14 == right.register.sbyte_14 ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; + register.sbyte_15 = left.register.sbyte_15 == right.register.sbyte_15 ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; return new Vector(ref register); } - else if (typeof(T) == typeof(UInt16)) + else if (typeof(T) == typeof(ushort)) { - register.uint16_0 = left.register.uint16_0 == right.register.uint16_0 ? ConstantHelper.GetUInt16WithAllBitsSet() : (UInt16)0; - register.uint16_1 = left.register.uint16_1 == right.register.uint16_1 ? ConstantHelper.GetUInt16WithAllBitsSet() : (UInt16)0; - register.uint16_2 = left.register.uint16_2 == right.register.uint16_2 ? ConstantHelper.GetUInt16WithAllBitsSet() : (UInt16)0; - register.uint16_3 = left.register.uint16_3 == right.register.uint16_3 ? ConstantHelper.GetUInt16WithAllBitsSet() : (UInt16)0; - register.uint16_4 = left.register.uint16_4 == right.register.uint16_4 ? ConstantHelper.GetUInt16WithAllBitsSet() : (UInt16)0; - register.uint16_5 = left.register.uint16_5 == right.register.uint16_5 ? ConstantHelper.GetUInt16WithAllBitsSet() : (UInt16)0; - register.uint16_6 = left.register.uint16_6 == right.register.uint16_6 ? ConstantHelper.GetUInt16WithAllBitsSet() : (UInt16)0; - register.uint16_7 = left.register.uint16_7 == right.register.uint16_7 ? ConstantHelper.GetUInt16WithAllBitsSet() : (UInt16)0; + register.uint16_0 = left.register.uint16_0 == right.register.uint16_0 ? ConstantHelper.GetUInt16WithAllBitsSet() : (ushort)0; + register.uint16_1 = left.register.uint16_1 == right.register.uint16_1 ? ConstantHelper.GetUInt16WithAllBitsSet() : (ushort)0; + register.uint16_2 = left.register.uint16_2 == right.register.uint16_2 ? ConstantHelper.GetUInt16WithAllBitsSet() : (ushort)0; + register.uint16_3 = left.register.uint16_3 == right.register.uint16_3 ? ConstantHelper.GetUInt16WithAllBitsSet() : (ushort)0; + register.uint16_4 = left.register.uint16_4 == right.register.uint16_4 ? ConstantHelper.GetUInt16WithAllBitsSet() : (ushort)0; + register.uint16_5 = left.register.uint16_5 == right.register.uint16_5 ? ConstantHelper.GetUInt16WithAllBitsSet() : (ushort)0; + register.uint16_6 = left.register.uint16_6 == right.register.uint16_6 ? ConstantHelper.GetUInt16WithAllBitsSet() : (ushort)0; + register.uint16_7 = left.register.uint16_7 == right.register.uint16_7 ? ConstantHelper.GetUInt16WithAllBitsSet() : (ushort)0; return new Vector(ref register); } - else if (typeof(T) == typeof(Int16)) + else if (typeof(T) == typeof(short)) { - register.int16_0 = left.register.int16_0 == right.register.int16_0 ? ConstantHelper.GetInt16WithAllBitsSet() : (Int16)0; - register.int16_1 = left.register.int16_1 == right.register.int16_1 ? ConstantHelper.GetInt16WithAllBitsSet() : (Int16)0; - register.int16_2 = left.register.int16_2 == right.register.int16_2 ? ConstantHelper.GetInt16WithAllBitsSet() : (Int16)0; - register.int16_3 = left.register.int16_3 == right.register.int16_3 ? ConstantHelper.GetInt16WithAllBitsSet() : (Int16)0; - register.int16_4 = left.register.int16_4 == right.register.int16_4 ? ConstantHelper.GetInt16WithAllBitsSet() : (Int16)0; - register.int16_5 = left.register.int16_5 == right.register.int16_5 ? ConstantHelper.GetInt16WithAllBitsSet() : (Int16)0; - register.int16_6 = left.register.int16_6 == right.register.int16_6 ? ConstantHelper.GetInt16WithAllBitsSet() : (Int16)0; - register.int16_7 = left.register.int16_7 == right.register.int16_7 ? ConstantHelper.GetInt16WithAllBitsSet() : (Int16)0; + register.int16_0 = left.register.int16_0 == right.register.int16_0 ? ConstantHelper.GetInt16WithAllBitsSet() : (short)0; + register.int16_1 = left.register.int16_1 == right.register.int16_1 ? ConstantHelper.GetInt16WithAllBitsSet() : (short)0; + register.int16_2 = left.register.int16_2 == right.register.int16_2 ? ConstantHelper.GetInt16WithAllBitsSet() : (short)0; + register.int16_3 = left.register.int16_3 == right.register.int16_3 ? ConstantHelper.GetInt16WithAllBitsSet() : (short)0; + register.int16_4 = left.register.int16_4 == right.register.int16_4 ? ConstantHelper.GetInt16WithAllBitsSet() : (short)0; + register.int16_5 = left.register.int16_5 == right.register.int16_5 ? ConstantHelper.GetInt16WithAllBitsSet() : (short)0; + register.int16_6 = left.register.int16_6 == right.register.int16_6 ? ConstantHelper.GetInt16WithAllBitsSet() : (short)0; + register.int16_7 = left.register.int16_7 == right.register.int16_7 ? ConstantHelper.GetInt16WithAllBitsSet() : (short)0; return new Vector(ref register); } - else if (typeof(T) == typeof(UInt32)) + else if (typeof(T) == typeof(uint)) { - register.uint32_0 = left.register.uint32_0 == right.register.uint32_0 ? ConstantHelper.GetUInt32WithAllBitsSet() : (UInt32)0; - register.uint32_1 = left.register.uint32_1 == right.register.uint32_1 ? ConstantHelper.GetUInt32WithAllBitsSet() : (UInt32)0; - register.uint32_2 = left.register.uint32_2 == right.register.uint32_2 ? ConstantHelper.GetUInt32WithAllBitsSet() : (UInt32)0; - register.uint32_3 = left.register.uint32_3 == right.register.uint32_3 ? ConstantHelper.GetUInt32WithAllBitsSet() : (UInt32)0; + register.uint32_0 = left.register.uint32_0 == right.register.uint32_0 ? ConstantHelper.GetUInt32WithAllBitsSet() : (uint)0; + register.uint32_1 = left.register.uint32_1 == right.register.uint32_1 ? ConstantHelper.GetUInt32WithAllBitsSet() : (uint)0; + register.uint32_2 = left.register.uint32_2 == right.register.uint32_2 ? ConstantHelper.GetUInt32WithAllBitsSet() : (uint)0; + register.uint32_3 = left.register.uint32_3 == right.register.uint32_3 ? ConstantHelper.GetUInt32WithAllBitsSet() : (uint)0; return new Vector(ref register); } - else if (typeof(T) == typeof(Int32)) + else if (typeof(T) == typeof(int)) { - register.int32_0 = left.register.int32_0 == right.register.int32_0 ? ConstantHelper.GetInt32WithAllBitsSet() : (Int32)0; - register.int32_1 = left.register.int32_1 == right.register.int32_1 ? ConstantHelper.GetInt32WithAllBitsSet() : (Int32)0; - register.int32_2 = left.register.int32_2 == right.register.int32_2 ? ConstantHelper.GetInt32WithAllBitsSet() : (Int32)0; - register.int32_3 = left.register.int32_3 == right.register.int32_3 ? ConstantHelper.GetInt32WithAllBitsSet() : (Int32)0; + register.int32_0 = left.register.int32_0 == right.register.int32_0 ? ConstantHelper.GetInt32WithAllBitsSet() : (int)0; + register.int32_1 = left.register.int32_1 == right.register.int32_1 ? ConstantHelper.GetInt32WithAllBitsSet() : (int)0; + register.int32_2 = left.register.int32_2 == right.register.int32_2 ? ConstantHelper.GetInt32WithAllBitsSet() : (int)0; + register.int32_3 = left.register.int32_3 == right.register.int32_3 ? ConstantHelper.GetInt32WithAllBitsSet() : (int)0; return new Vector(ref register); } - else if (typeof(T) == typeof(UInt64)) + else if (typeof(T) == typeof(ulong)) { - register.uint64_0 = left.register.uint64_0 == right.register.uint64_0 ? ConstantHelper.GetUInt64WithAllBitsSet() : (UInt64)0; - register.uint64_1 = left.register.uint64_1 == right.register.uint64_1 ? ConstantHelper.GetUInt64WithAllBitsSet() : (UInt64)0; + register.uint64_0 = left.register.uint64_0 == right.register.uint64_0 ? ConstantHelper.GetUInt64WithAllBitsSet() : (ulong)0; + register.uint64_1 = left.register.uint64_1 == right.register.uint64_1 ? ConstantHelper.GetUInt64WithAllBitsSet() : (ulong)0; return new Vector(ref register); } - else if (typeof(T) == typeof(Int64)) + else if (typeof(T) == typeof(long)) { - register.int64_0 = left.register.int64_0 == right.register.int64_0 ? ConstantHelper.GetInt64WithAllBitsSet() : (Int64)0; - register.int64_1 = left.register.int64_1 == right.register.int64_1 ? ConstantHelper.GetInt64WithAllBitsSet() : (Int64)0; + register.int64_0 = left.register.int64_0 == right.register.int64_0 ? ConstantHelper.GetInt64WithAllBitsSet() : (long)0; + register.int64_1 = left.register.int64_1 == right.register.int64_1 ? ConstantHelper.GetInt64WithAllBitsSet() : (long)0; return new Vector(ref register); } - else if (typeof(T) == typeof(Single)) + else if (typeof(T) == typeof(float)) { - register.single_0 = left.register.single_0 == right.register.single_0 ? ConstantHelper.GetSingleWithAllBitsSet() : (Single)0; - register.single_1 = left.register.single_1 == right.register.single_1 ? ConstantHelper.GetSingleWithAllBitsSet() : (Single)0; - register.single_2 = left.register.single_2 == right.register.single_2 ? ConstantHelper.GetSingleWithAllBitsSet() : (Single)0; - register.single_3 = left.register.single_3 == right.register.single_3 ? ConstantHelper.GetSingleWithAllBitsSet() : (Single)0; + register.single_0 = left.register.single_0 == right.register.single_0 ? ConstantHelper.GetSingleWithAllBitsSet() : (float)0; + register.single_1 = left.register.single_1 == right.register.single_1 ? ConstantHelper.GetSingleWithAllBitsSet() : (float)0; + register.single_2 = left.register.single_2 == right.register.single_2 ? ConstantHelper.GetSingleWithAllBitsSet() : (float)0; + register.single_3 = left.register.single_3 == right.register.single_3 ? ConstantHelper.GetSingleWithAllBitsSet() : (float)0; return new Vector(ref register); } - else if (typeof(T) == typeof(Double)) + else if (typeof(T) == typeof(double)) { - register.double_0 = left.register.double_0 == right.register.double_0 ? ConstantHelper.GetDoubleWithAllBitsSet() : (Double)0; - register.double_1 = left.register.double_1 == right.register.double_1 ? ConstantHelper.GetDoubleWithAllBitsSet() : (Double)0; + register.double_0 = left.register.double_0 == right.register.double_0 ? ConstantHelper.GetDoubleWithAllBitsSet() : (double)0; + register.double_1 = left.register.double_1 == right.register.double_1 ? ConstantHelper.GetDoubleWithAllBitsSet() : (double)0; return new Vector(ref register); } else @@ -3153,93 +3153,93 @@ internal static unsafe Vector LessThan(Vector left, Vector right) { if (Vector.IsHardwareAccelerated) { - if (typeof(T) == typeof(Byte)) + if (typeof(T) == typeof(byte)) { - Byte* dataPtr = stackalloc Byte[Count]; + byte* dataPtr = stackalloc byte[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarLessThan(left[g], right[g]) ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; + dataPtr[g] = ScalarLessThan(left[g], right[g]) ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; } return new Vector(dataPtr); } - else if (typeof(T) == typeof(SByte)) + else if (typeof(T) == typeof(sbyte)) { - SByte* dataPtr = stackalloc SByte[Count]; + sbyte* dataPtr = stackalloc sbyte[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarLessThan(left[g], right[g]) ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; + dataPtr[g] = ScalarLessThan(left[g], right[g]) ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; } return new Vector(dataPtr); } - else if (typeof(T) == typeof(UInt16)) + else if (typeof(T) == typeof(ushort)) { - UInt16* dataPtr = stackalloc UInt16[Count]; + ushort* dataPtr = stackalloc ushort[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarLessThan(left[g], right[g]) ? ConstantHelper.GetUInt16WithAllBitsSet() : (UInt16)0; + dataPtr[g] = ScalarLessThan(left[g], right[g]) ? ConstantHelper.GetUInt16WithAllBitsSet() : (ushort)0; } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Int16)) + else if (typeof(T) == typeof(short)) { - Int16* dataPtr = stackalloc Int16[Count]; + short* dataPtr = stackalloc short[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarLessThan(left[g], right[g]) ? ConstantHelper.GetInt16WithAllBitsSet() : (Int16)0; + dataPtr[g] = ScalarLessThan(left[g], right[g]) ? ConstantHelper.GetInt16WithAllBitsSet() : (short)0; } return new Vector(dataPtr); } - else if (typeof(T) == typeof(UInt32)) + else if (typeof(T) == typeof(uint)) { - UInt32* dataPtr = stackalloc UInt32[Count]; + uint* dataPtr = stackalloc uint[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarLessThan(left[g], right[g]) ? ConstantHelper.GetUInt32WithAllBitsSet() : (UInt32)0; + dataPtr[g] = ScalarLessThan(left[g], right[g]) ? ConstantHelper.GetUInt32WithAllBitsSet() : (uint)0; } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Int32)) + else if (typeof(T) == typeof(int)) { - Int32* dataPtr = stackalloc Int32[Count]; + int* dataPtr = stackalloc int[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarLessThan(left[g], right[g]) ? ConstantHelper.GetInt32WithAllBitsSet() : (Int32)0; + dataPtr[g] = ScalarLessThan(left[g], right[g]) ? ConstantHelper.GetInt32WithAllBitsSet() : (int)0; } return new Vector(dataPtr); } - else if (typeof(T) == typeof(UInt64)) + else if (typeof(T) == typeof(ulong)) { - UInt64* dataPtr = stackalloc UInt64[Count]; + ulong* dataPtr = stackalloc ulong[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarLessThan(left[g], right[g]) ? ConstantHelper.GetUInt64WithAllBitsSet() : (UInt64)0; + dataPtr[g] = ScalarLessThan(left[g], right[g]) ? ConstantHelper.GetUInt64WithAllBitsSet() : (ulong)0; } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Int64)) + else if (typeof(T) == typeof(long)) { - Int64* dataPtr = stackalloc Int64[Count]; + long* dataPtr = stackalloc long[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarLessThan(left[g], right[g]) ? ConstantHelper.GetInt64WithAllBitsSet() : (Int64)0; + dataPtr[g] = ScalarLessThan(left[g], right[g]) ? ConstantHelper.GetInt64WithAllBitsSet() : (long)0; } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Single)) + else if (typeof(T) == typeof(float)) { - Single* dataPtr = stackalloc Single[Count]; + float* dataPtr = stackalloc float[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarLessThan(left[g], right[g]) ? ConstantHelper.GetSingleWithAllBitsSet() : (Single)0; + dataPtr[g] = ScalarLessThan(left[g], right[g]) ? ConstantHelper.GetSingleWithAllBitsSet() : (float)0; } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Double)) + else if (typeof(T) == typeof(double)) { - Double* dataPtr = stackalloc Double[Count]; + double* dataPtr = stackalloc double[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarLessThan(left[g], right[g]) ? ConstantHelper.GetDoubleWithAllBitsSet() : (Double)0; + dataPtr[g] = ScalarLessThan(left[g], right[g]) ? ConstantHelper.GetDoubleWithAllBitsSet() : (double)0; } return new Vector(dataPtr); } @@ -3251,110 +3251,110 @@ internal static unsafe Vector LessThan(Vector left, Vector right) else { Register register = new Register(); - if (typeof(T) == typeof(Byte)) - { - register.byte_0 = left.register.byte_0 < right.register.byte_0 ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; - register.byte_1 = left.register.byte_1 < right.register.byte_1 ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; - register.byte_2 = left.register.byte_2 < right.register.byte_2 ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; - register.byte_3 = left.register.byte_3 < right.register.byte_3 ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; - register.byte_4 = left.register.byte_4 < right.register.byte_4 ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; - register.byte_5 = left.register.byte_5 < right.register.byte_5 ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; - register.byte_6 = left.register.byte_6 < right.register.byte_6 ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; - register.byte_7 = left.register.byte_7 < right.register.byte_7 ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; - register.byte_8 = left.register.byte_8 < right.register.byte_8 ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; - register.byte_9 = left.register.byte_9 < right.register.byte_9 ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; - register.byte_10 = left.register.byte_10 < right.register.byte_10 ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; - register.byte_11 = left.register.byte_11 < right.register.byte_11 ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; - register.byte_12 = left.register.byte_12 < right.register.byte_12 ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; - register.byte_13 = left.register.byte_13 < right.register.byte_13 ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; - register.byte_14 = left.register.byte_14 < right.register.byte_14 ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; - register.byte_15 = left.register.byte_15 < right.register.byte_15 ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; + if (typeof(T) == typeof(byte)) + { + register.byte_0 = left.register.byte_0 < right.register.byte_0 ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; + register.byte_1 = left.register.byte_1 < right.register.byte_1 ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; + register.byte_2 = left.register.byte_2 < right.register.byte_2 ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; + register.byte_3 = left.register.byte_3 < right.register.byte_3 ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; + register.byte_4 = left.register.byte_4 < right.register.byte_4 ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; + register.byte_5 = left.register.byte_5 < right.register.byte_5 ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; + register.byte_6 = left.register.byte_6 < right.register.byte_6 ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; + register.byte_7 = left.register.byte_7 < right.register.byte_7 ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; + register.byte_8 = left.register.byte_8 < right.register.byte_8 ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; + register.byte_9 = left.register.byte_9 < right.register.byte_9 ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; + register.byte_10 = left.register.byte_10 < right.register.byte_10 ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; + register.byte_11 = left.register.byte_11 < right.register.byte_11 ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; + register.byte_12 = left.register.byte_12 < right.register.byte_12 ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; + register.byte_13 = left.register.byte_13 < right.register.byte_13 ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; + register.byte_14 = left.register.byte_14 < right.register.byte_14 ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; + register.byte_15 = left.register.byte_15 < right.register.byte_15 ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; return new Vector(ref register); } - else if (typeof(T) == typeof(SByte)) - { - register.sbyte_0 = left.register.sbyte_0 < right.register.sbyte_0 ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; - register.sbyte_1 = left.register.sbyte_1 < right.register.sbyte_1 ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; - register.sbyte_2 = left.register.sbyte_2 < right.register.sbyte_2 ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; - register.sbyte_3 = left.register.sbyte_3 < right.register.sbyte_3 ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; - register.sbyte_4 = left.register.sbyte_4 < right.register.sbyte_4 ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; - register.sbyte_5 = left.register.sbyte_5 < right.register.sbyte_5 ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; - register.sbyte_6 = left.register.sbyte_6 < right.register.sbyte_6 ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; - register.sbyte_7 = left.register.sbyte_7 < right.register.sbyte_7 ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; - register.sbyte_8 = left.register.sbyte_8 < right.register.sbyte_8 ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; - register.sbyte_9 = left.register.sbyte_9 < right.register.sbyte_9 ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; - register.sbyte_10 = left.register.sbyte_10 < right.register.sbyte_10 ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; - register.sbyte_11 = left.register.sbyte_11 < right.register.sbyte_11 ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; - register.sbyte_12 = left.register.sbyte_12 < right.register.sbyte_12 ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; - register.sbyte_13 = left.register.sbyte_13 < right.register.sbyte_13 ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; - register.sbyte_14 = left.register.sbyte_14 < right.register.sbyte_14 ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; - register.sbyte_15 = left.register.sbyte_15 < right.register.sbyte_15 ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; + else if (typeof(T) == typeof(sbyte)) + { + register.sbyte_0 = left.register.sbyte_0 < right.register.sbyte_0 ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; + register.sbyte_1 = left.register.sbyte_1 < right.register.sbyte_1 ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; + register.sbyte_2 = left.register.sbyte_2 < right.register.sbyte_2 ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; + register.sbyte_3 = left.register.sbyte_3 < right.register.sbyte_3 ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; + register.sbyte_4 = left.register.sbyte_4 < right.register.sbyte_4 ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; + register.sbyte_5 = left.register.sbyte_5 < right.register.sbyte_5 ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; + register.sbyte_6 = left.register.sbyte_6 < right.register.sbyte_6 ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; + register.sbyte_7 = left.register.sbyte_7 < right.register.sbyte_7 ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; + register.sbyte_8 = left.register.sbyte_8 < right.register.sbyte_8 ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; + register.sbyte_9 = left.register.sbyte_9 < right.register.sbyte_9 ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; + register.sbyte_10 = left.register.sbyte_10 < right.register.sbyte_10 ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; + register.sbyte_11 = left.register.sbyte_11 < right.register.sbyte_11 ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; + register.sbyte_12 = left.register.sbyte_12 < right.register.sbyte_12 ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; + register.sbyte_13 = left.register.sbyte_13 < right.register.sbyte_13 ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; + register.sbyte_14 = left.register.sbyte_14 < right.register.sbyte_14 ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; + register.sbyte_15 = left.register.sbyte_15 < right.register.sbyte_15 ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; return new Vector(ref register); } - else if (typeof(T) == typeof(UInt16)) + else if (typeof(T) == typeof(ushort)) { - register.uint16_0 = left.register.uint16_0 < right.register.uint16_0 ? ConstantHelper.GetUInt16WithAllBitsSet() : (UInt16)0; - register.uint16_1 = left.register.uint16_1 < right.register.uint16_1 ? ConstantHelper.GetUInt16WithAllBitsSet() : (UInt16)0; - register.uint16_2 = left.register.uint16_2 < right.register.uint16_2 ? ConstantHelper.GetUInt16WithAllBitsSet() : (UInt16)0; - register.uint16_3 = left.register.uint16_3 < right.register.uint16_3 ? ConstantHelper.GetUInt16WithAllBitsSet() : (UInt16)0; - register.uint16_4 = left.register.uint16_4 < right.register.uint16_4 ? ConstantHelper.GetUInt16WithAllBitsSet() : (UInt16)0; - register.uint16_5 = left.register.uint16_5 < right.register.uint16_5 ? ConstantHelper.GetUInt16WithAllBitsSet() : (UInt16)0; - register.uint16_6 = left.register.uint16_6 < right.register.uint16_6 ? ConstantHelper.GetUInt16WithAllBitsSet() : (UInt16)0; - register.uint16_7 = left.register.uint16_7 < right.register.uint16_7 ? ConstantHelper.GetUInt16WithAllBitsSet() : (UInt16)0; + register.uint16_0 = left.register.uint16_0 < right.register.uint16_0 ? ConstantHelper.GetUInt16WithAllBitsSet() : (ushort)0; + register.uint16_1 = left.register.uint16_1 < right.register.uint16_1 ? ConstantHelper.GetUInt16WithAllBitsSet() : (ushort)0; + register.uint16_2 = left.register.uint16_2 < right.register.uint16_2 ? ConstantHelper.GetUInt16WithAllBitsSet() : (ushort)0; + register.uint16_3 = left.register.uint16_3 < right.register.uint16_3 ? ConstantHelper.GetUInt16WithAllBitsSet() : (ushort)0; + register.uint16_4 = left.register.uint16_4 < right.register.uint16_4 ? ConstantHelper.GetUInt16WithAllBitsSet() : (ushort)0; + register.uint16_5 = left.register.uint16_5 < right.register.uint16_5 ? ConstantHelper.GetUInt16WithAllBitsSet() : (ushort)0; + register.uint16_6 = left.register.uint16_6 < right.register.uint16_6 ? ConstantHelper.GetUInt16WithAllBitsSet() : (ushort)0; + register.uint16_7 = left.register.uint16_7 < right.register.uint16_7 ? ConstantHelper.GetUInt16WithAllBitsSet() : (ushort)0; return new Vector(ref register); } - else if (typeof(T) == typeof(Int16)) + else if (typeof(T) == typeof(short)) { - register.int16_0 = left.register.int16_0 < right.register.int16_0 ? ConstantHelper.GetInt16WithAllBitsSet() : (Int16)0; - register.int16_1 = left.register.int16_1 < right.register.int16_1 ? ConstantHelper.GetInt16WithAllBitsSet() : (Int16)0; - register.int16_2 = left.register.int16_2 < right.register.int16_2 ? ConstantHelper.GetInt16WithAllBitsSet() : (Int16)0; - register.int16_3 = left.register.int16_3 < right.register.int16_3 ? ConstantHelper.GetInt16WithAllBitsSet() : (Int16)0; - register.int16_4 = left.register.int16_4 < right.register.int16_4 ? ConstantHelper.GetInt16WithAllBitsSet() : (Int16)0; - register.int16_5 = left.register.int16_5 < right.register.int16_5 ? ConstantHelper.GetInt16WithAllBitsSet() : (Int16)0; - register.int16_6 = left.register.int16_6 < right.register.int16_6 ? ConstantHelper.GetInt16WithAllBitsSet() : (Int16)0; - register.int16_7 = left.register.int16_7 < right.register.int16_7 ? ConstantHelper.GetInt16WithAllBitsSet() : (Int16)0; + register.int16_0 = left.register.int16_0 < right.register.int16_0 ? ConstantHelper.GetInt16WithAllBitsSet() : (short)0; + register.int16_1 = left.register.int16_1 < right.register.int16_1 ? ConstantHelper.GetInt16WithAllBitsSet() : (short)0; + register.int16_2 = left.register.int16_2 < right.register.int16_2 ? ConstantHelper.GetInt16WithAllBitsSet() : (short)0; + register.int16_3 = left.register.int16_3 < right.register.int16_3 ? ConstantHelper.GetInt16WithAllBitsSet() : (short)0; + register.int16_4 = left.register.int16_4 < right.register.int16_4 ? ConstantHelper.GetInt16WithAllBitsSet() : (short)0; + register.int16_5 = left.register.int16_5 < right.register.int16_5 ? ConstantHelper.GetInt16WithAllBitsSet() : (short)0; + register.int16_6 = left.register.int16_6 < right.register.int16_6 ? ConstantHelper.GetInt16WithAllBitsSet() : (short)0; + register.int16_7 = left.register.int16_7 < right.register.int16_7 ? ConstantHelper.GetInt16WithAllBitsSet() : (short)0; return new Vector(ref register); } - else if (typeof(T) == typeof(UInt32)) + else if (typeof(T) == typeof(uint)) { - register.uint32_0 = left.register.uint32_0 < right.register.uint32_0 ? ConstantHelper.GetUInt32WithAllBitsSet() : (UInt32)0; - register.uint32_1 = left.register.uint32_1 < right.register.uint32_1 ? ConstantHelper.GetUInt32WithAllBitsSet() : (UInt32)0; - register.uint32_2 = left.register.uint32_2 < right.register.uint32_2 ? ConstantHelper.GetUInt32WithAllBitsSet() : (UInt32)0; - register.uint32_3 = left.register.uint32_3 < right.register.uint32_3 ? ConstantHelper.GetUInt32WithAllBitsSet() : (UInt32)0; + register.uint32_0 = left.register.uint32_0 < right.register.uint32_0 ? ConstantHelper.GetUInt32WithAllBitsSet() : (uint)0; + register.uint32_1 = left.register.uint32_1 < right.register.uint32_1 ? ConstantHelper.GetUInt32WithAllBitsSet() : (uint)0; + register.uint32_2 = left.register.uint32_2 < right.register.uint32_2 ? ConstantHelper.GetUInt32WithAllBitsSet() : (uint)0; + register.uint32_3 = left.register.uint32_3 < right.register.uint32_3 ? ConstantHelper.GetUInt32WithAllBitsSet() : (uint)0; return new Vector(ref register); } - else if (typeof(T) == typeof(Int32)) + else if (typeof(T) == typeof(int)) { - register.int32_0 = left.register.int32_0 < right.register.int32_0 ? ConstantHelper.GetInt32WithAllBitsSet() : (Int32)0; - register.int32_1 = left.register.int32_1 < right.register.int32_1 ? ConstantHelper.GetInt32WithAllBitsSet() : (Int32)0; - register.int32_2 = left.register.int32_2 < right.register.int32_2 ? ConstantHelper.GetInt32WithAllBitsSet() : (Int32)0; - register.int32_3 = left.register.int32_3 < right.register.int32_3 ? ConstantHelper.GetInt32WithAllBitsSet() : (Int32)0; + register.int32_0 = left.register.int32_0 < right.register.int32_0 ? ConstantHelper.GetInt32WithAllBitsSet() : (int)0; + register.int32_1 = left.register.int32_1 < right.register.int32_1 ? ConstantHelper.GetInt32WithAllBitsSet() : (int)0; + register.int32_2 = left.register.int32_2 < right.register.int32_2 ? ConstantHelper.GetInt32WithAllBitsSet() : (int)0; + register.int32_3 = left.register.int32_3 < right.register.int32_3 ? ConstantHelper.GetInt32WithAllBitsSet() : (int)0; return new Vector(ref register); } - else if (typeof(T) == typeof(UInt64)) + else if (typeof(T) == typeof(ulong)) { - register.uint64_0 = left.register.uint64_0 < right.register.uint64_0 ? ConstantHelper.GetUInt64WithAllBitsSet() : (UInt64)0; - register.uint64_1 = left.register.uint64_1 < right.register.uint64_1 ? ConstantHelper.GetUInt64WithAllBitsSet() : (UInt64)0; + register.uint64_0 = left.register.uint64_0 < right.register.uint64_0 ? ConstantHelper.GetUInt64WithAllBitsSet() : (ulong)0; + register.uint64_1 = left.register.uint64_1 < right.register.uint64_1 ? ConstantHelper.GetUInt64WithAllBitsSet() : (ulong)0; return new Vector(ref register); } - else if (typeof(T) == typeof(Int64)) + else if (typeof(T) == typeof(long)) { - register.int64_0 = left.register.int64_0 < right.register.int64_0 ? ConstantHelper.GetInt64WithAllBitsSet() : (Int64)0; - register.int64_1 = left.register.int64_1 < right.register.int64_1 ? ConstantHelper.GetInt64WithAllBitsSet() : (Int64)0; + register.int64_0 = left.register.int64_0 < right.register.int64_0 ? ConstantHelper.GetInt64WithAllBitsSet() : (long)0; + register.int64_1 = left.register.int64_1 < right.register.int64_1 ? ConstantHelper.GetInt64WithAllBitsSet() : (long)0; return new Vector(ref register); } - else if (typeof(T) == typeof(Single)) + else if (typeof(T) == typeof(float)) { - register.single_0 = left.register.single_0 < right.register.single_0 ? ConstantHelper.GetSingleWithAllBitsSet() : (Single)0; - register.single_1 = left.register.single_1 < right.register.single_1 ? ConstantHelper.GetSingleWithAllBitsSet() : (Single)0; - register.single_2 = left.register.single_2 < right.register.single_2 ? ConstantHelper.GetSingleWithAllBitsSet() : (Single)0; - register.single_3 = left.register.single_3 < right.register.single_3 ? ConstantHelper.GetSingleWithAllBitsSet() : (Single)0; + register.single_0 = left.register.single_0 < right.register.single_0 ? ConstantHelper.GetSingleWithAllBitsSet() : (float)0; + register.single_1 = left.register.single_1 < right.register.single_1 ? ConstantHelper.GetSingleWithAllBitsSet() : (float)0; + register.single_2 = left.register.single_2 < right.register.single_2 ? ConstantHelper.GetSingleWithAllBitsSet() : (float)0; + register.single_3 = left.register.single_3 < right.register.single_3 ? ConstantHelper.GetSingleWithAllBitsSet() : (float)0; return new Vector(ref register); } - else if (typeof(T) == typeof(Double)) + else if (typeof(T) == typeof(double)) { - register.double_0 = left.register.double_0 < right.register.double_0 ? ConstantHelper.GetDoubleWithAllBitsSet() : (Double)0; - register.double_1 = left.register.double_1 < right.register.double_1 ? ConstantHelper.GetDoubleWithAllBitsSet() : (Double)0; + register.double_0 = left.register.double_0 < right.register.double_0 ? ConstantHelper.GetDoubleWithAllBitsSet() : (double)0; + register.double_1 = left.register.double_1 < right.register.double_1 ? ConstantHelper.GetDoubleWithAllBitsSet() : (double)0; return new Vector(ref register); } else @@ -3370,93 +3370,93 @@ internal static unsafe Vector GreaterThan(Vector left, Vector right) { if (Vector.IsHardwareAccelerated) { - if (typeof(T) == typeof(Byte)) + if (typeof(T) == typeof(byte)) { - Byte* dataPtr = stackalloc Byte[Count]; + byte* dataPtr = stackalloc byte[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarGreaterThan(left[g], right[g]) ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; + dataPtr[g] = ScalarGreaterThan(left[g], right[g]) ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; } return new Vector(dataPtr); } - else if (typeof(T) == typeof(SByte)) + else if (typeof(T) == typeof(sbyte)) { - SByte* dataPtr = stackalloc SByte[Count]; + sbyte* dataPtr = stackalloc sbyte[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarGreaterThan(left[g], right[g]) ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; + dataPtr[g] = ScalarGreaterThan(left[g], right[g]) ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; } return new Vector(dataPtr); } - else if (typeof(T) == typeof(UInt16)) + else if (typeof(T) == typeof(ushort)) { - UInt16* dataPtr = stackalloc UInt16[Count]; + ushort* dataPtr = stackalloc ushort[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarGreaterThan(left[g], right[g]) ? ConstantHelper.GetUInt16WithAllBitsSet() : (UInt16)0; + dataPtr[g] = ScalarGreaterThan(left[g], right[g]) ? ConstantHelper.GetUInt16WithAllBitsSet() : (ushort)0; } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Int16)) + else if (typeof(T) == typeof(short)) { - Int16* dataPtr = stackalloc Int16[Count]; + short* dataPtr = stackalloc short[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarGreaterThan(left[g], right[g]) ? ConstantHelper.GetInt16WithAllBitsSet() : (Int16)0; + dataPtr[g] = ScalarGreaterThan(left[g], right[g]) ? ConstantHelper.GetInt16WithAllBitsSet() : (short)0; } return new Vector(dataPtr); } - else if (typeof(T) == typeof(UInt32)) + else if (typeof(T) == typeof(uint)) { - UInt32* dataPtr = stackalloc UInt32[Count]; + uint* dataPtr = stackalloc uint[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarGreaterThan(left[g], right[g]) ? ConstantHelper.GetUInt32WithAllBitsSet() : (UInt32)0; + dataPtr[g] = ScalarGreaterThan(left[g], right[g]) ? ConstantHelper.GetUInt32WithAllBitsSet() : (uint)0; } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Int32)) + else if (typeof(T) == typeof(int)) { - Int32* dataPtr = stackalloc Int32[Count]; + int* dataPtr = stackalloc int[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarGreaterThan(left[g], right[g]) ? ConstantHelper.GetInt32WithAllBitsSet() : (Int32)0; + dataPtr[g] = ScalarGreaterThan(left[g], right[g]) ? ConstantHelper.GetInt32WithAllBitsSet() : (int)0; } return new Vector(dataPtr); } - else if (typeof(T) == typeof(UInt64)) + else if (typeof(T) == typeof(ulong)) { - UInt64* dataPtr = stackalloc UInt64[Count]; + ulong* dataPtr = stackalloc ulong[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarGreaterThan(left[g], right[g]) ? ConstantHelper.GetUInt64WithAllBitsSet() : (UInt64)0; + dataPtr[g] = ScalarGreaterThan(left[g], right[g]) ? ConstantHelper.GetUInt64WithAllBitsSet() : (ulong)0; } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Int64)) + else if (typeof(T) == typeof(long)) { - Int64* dataPtr = stackalloc Int64[Count]; + long* dataPtr = stackalloc long[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarGreaterThan(left[g], right[g]) ? ConstantHelper.GetInt64WithAllBitsSet() : (Int64)0; + dataPtr[g] = ScalarGreaterThan(left[g], right[g]) ? ConstantHelper.GetInt64WithAllBitsSet() : (long)0; } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Single)) + else if (typeof(T) == typeof(float)) { - Single* dataPtr = stackalloc Single[Count]; + float* dataPtr = stackalloc float[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarGreaterThan(left[g], right[g]) ? ConstantHelper.GetSingleWithAllBitsSet() : (Single)0; + dataPtr[g] = ScalarGreaterThan(left[g], right[g]) ? ConstantHelper.GetSingleWithAllBitsSet() : (float)0; } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Double)) + else if (typeof(T) == typeof(double)) { - Double* dataPtr = stackalloc Double[Count]; + double* dataPtr = stackalloc double[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarGreaterThan(left[g], right[g]) ? ConstantHelper.GetDoubleWithAllBitsSet() : (Double)0; + dataPtr[g] = ScalarGreaterThan(left[g], right[g]) ? ConstantHelper.GetDoubleWithAllBitsSet() : (double)0; } return new Vector(dataPtr); } @@ -3468,110 +3468,110 @@ internal static unsafe Vector GreaterThan(Vector left, Vector right) else { Register register = new Register(); - if (typeof(T) == typeof(Byte)) - { - register.byte_0 = left.register.byte_0 > right.register.byte_0 ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; - register.byte_1 = left.register.byte_1 > right.register.byte_1 ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; - register.byte_2 = left.register.byte_2 > right.register.byte_2 ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; - register.byte_3 = left.register.byte_3 > right.register.byte_3 ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; - register.byte_4 = left.register.byte_4 > right.register.byte_4 ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; - register.byte_5 = left.register.byte_5 > right.register.byte_5 ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; - register.byte_6 = left.register.byte_6 > right.register.byte_6 ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; - register.byte_7 = left.register.byte_7 > right.register.byte_7 ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; - register.byte_8 = left.register.byte_8 > right.register.byte_8 ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; - register.byte_9 = left.register.byte_9 > right.register.byte_9 ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; - register.byte_10 = left.register.byte_10 > right.register.byte_10 ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; - register.byte_11 = left.register.byte_11 > right.register.byte_11 ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; - register.byte_12 = left.register.byte_12 > right.register.byte_12 ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; - register.byte_13 = left.register.byte_13 > right.register.byte_13 ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; - register.byte_14 = left.register.byte_14 > right.register.byte_14 ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; - register.byte_15 = left.register.byte_15 > right.register.byte_15 ? ConstantHelper.GetByteWithAllBitsSet() : (Byte)0; + if (typeof(T) == typeof(byte)) + { + register.byte_0 = left.register.byte_0 > right.register.byte_0 ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; + register.byte_1 = left.register.byte_1 > right.register.byte_1 ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; + register.byte_2 = left.register.byte_2 > right.register.byte_2 ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; + register.byte_3 = left.register.byte_3 > right.register.byte_3 ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; + register.byte_4 = left.register.byte_4 > right.register.byte_4 ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; + register.byte_5 = left.register.byte_5 > right.register.byte_5 ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; + register.byte_6 = left.register.byte_6 > right.register.byte_6 ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; + register.byte_7 = left.register.byte_7 > right.register.byte_7 ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; + register.byte_8 = left.register.byte_8 > right.register.byte_8 ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; + register.byte_9 = left.register.byte_9 > right.register.byte_9 ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; + register.byte_10 = left.register.byte_10 > right.register.byte_10 ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; + register.byte_11 = left.register.byte_11 > right.register.byte_11 ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; + register.byte_12 = left.register.byte_12 > right.register.byte_12 ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; + register.byte_13 = left.register.byte_13 > right.register.byte_13 ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; + register.byte_14 = left.register.byte_14 > right.register.byte_14 ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; + register.byte_15 = left.register.byte_15 > right.register.byte_15 ? ConstantHelper.GetByteWithAllBitsSet() : (byte)0; return new Vector(ref register); } - else if (typeof(T) == typeof(SByte)) - { - register.sbyte_0 = left.register.sbyte_0 > right.register.sbyte_0 ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; - register.sbyte_1 = left.register.sbyte_1 > right.register.sbyte_1 ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; - register.sbyte_2 = left.register.sbyte_2 > right.register.sbyte_2 ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; - register.sbyte_3 = left.register.sbyte_3 > right.register.sbyte_3 ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; - register.sbyte_4 = left.register.sbyte_4 > right.register.sbyte_4 ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; - register.sbyte_5 = left.register.sbyte_5 > right.register.sbyte_5 ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; - register.sbyte_6 = left.register.sbyte_6 > right.register.sbyte_6 ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; - register.sbyte_7 = left.register.sbyte_7 > right.register.sbyte_7 ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; - register.sbyte_8 = left.register.sbyte_8 > right.register.sbyte_8 ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; - register.sbyte_9 = left.register.sbyte_9 > right.register.sbyte_9 ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; - register.sbyte_10 = left.register.sbyte_10 > right.register.sbyte_10 ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; - register.sbyte_11 = left.register.sbyte_11 > right.register.sbyte_11 ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; - register.sbyte_12 = left.register.sbyte_12 > right.register.sbyte_12 ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; - register.sbyte_13 = left.register.sbyte_13 > right.register.sbyte_13 ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; - register.sbyte_14 = left.register.sbyte_14 > right.register.sbyte_14 ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; - register.sbyte_15 = left.register.sbyte_15 > right.register.sbyte_15 ? ConstantHelper.GetSByteWithAllBitsSet() : (SByte)0; + else if (typeof(T) == typeof(sbyte)) + { + register.sbyte_0 = left.register.sbyte_0 > right.register.sbyte_0 ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; + register.sbyte_1 = left.register.sbyte_1 > right.register.sbyte_1 ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; + register.sbyte_2 = left.register.sbyte_2 > right.register.sbyte_2 ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; + register.sbyte_3 = left.register.sbyte_3 > right.register.sbyte_3 ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; + register.sbyte_4 = left.register.sbyte_4 > right.register.sbyte_4 ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; + register.sbyte_5 = left.register.sbyte_5 > right.register.sbyte_5 ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; + register.sbyte_6 = left.register.sbyte_6 > right.register.sbyte_6 ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; + register.sbyte_7 = left.register.sbyte_7 > right.register.sbyte_7 ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; + register.sbyte_8 = left.register.sbyte_8 > right.register.sbyte_8 ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; + register.sbyte_9 = left.register.sbyte_9 > right.register.sbyte_9 ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; + register.sbyte_10 = left.register.sbyte_10 > right.register.sbyte_10 ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; + register.sbyte_11 = left.register.sbyte_11 > right.register.sbyte_11 ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; + register.sbyte_12 = left.register.sbyte_12 > right.register.sbyte_12 ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; + register.sbyte_13 = left.register.sbyte_13 > right.register.sbyte_13 ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; + register.sbyte_14 = left.register.sbyte_14 > right.register.sbyte_14 ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; + register.sbyte_15 = left.register.sbyte_15 > right.register.sbyte_15 ? ConstantHelper.GetSByteWithAllBitsSet() : (sbyte)0; return new Vector(ref register); } - else if (typeof(T) == typeof(UInt16)) + else if (typeof(T) == typeof(ushort)) { - register.uint16_0 = left.register.uint16_0 > right.register.uint16_0 ? ConstantHelper.GetUInt16WithAllBitsSet() : (UInt16)0; - register.uint16_1 = left.register.uint16_1 > right.register.uint16_1 ? ConstantHelper.GetUInt16WithAllBitsSet() : (UInt16)0; - register.uint16_2 = left.register.uint16_2 > right.register.uint16_2 ? ConstantHelper.GetUInt16WithAllBitsSet() : (UInt16)0; - register.uint16_3 = left.register.uint16_3 > right.register.uint16_3 ? ConstantHelper.GetUInt16WithAllBitsSet() : (UInt16)0; - register.uint16_4 = left.register.uint16_4 > right.register.uint16_4 ? ConstantHelper.GetUInt16WithAllBitsSet() : (UInt16)0; - register.uint16_5 = left.register.uint16_5 > right.register.uint16_5 ? ConstantHelper.GetUInt16WithAllBitsSet() : (UInt16)0; - register.uint16_6 = left.register.uint16_6 > right.register.uint16_6 ? ConstantHelper.GetUInt16WithAllBitsSet() : (UInt16)0; - register.uint16_7 = left.register.uint16_7 > right.register.uint16_7 ? ConstantHelper.GetUInt16WithAllBitsSet() : (UInt16)0; + register.uint16_0 = left.register.uint16_0 > right.register.uint16_0 ? ConstantHelper.GetUInt16WithAllBitsSet() : (ushort)0; + register.uint16_1 = left.register.uint16_1 > right.register.uint16_1 ? ConstantHelper.GetUInt16WithAllBitsSet() : (ushort)0; + register.uint16_2 = left.register.uint16_2 > right.register.uint16_2 ? ConstantHelper.GetUInt16WithAllBitsSet() : (ushort)0; + register.uint16_3 = left.register.uint16_3 > right.register.uint16_3 ? ConstantHelper.GetUInt16WithAllBitsSet() : (ushort)0; + register.uint16_4 = left.register.uint16_4 > right.register.uint16_4 ? ConstantHelper.GetUInt16WithAllBitsSet() : (ushort)0; + register.uint16_5 = left.register.uint16_5 > right.register.uint16_5 ? ConstantHelper.GetUInt16WithAllBitsSet() : (ushort)0; + register.uint16_6 = left.register.uint16_6 > right.register.uint16_6 ? ConstantHelper.GetUInt16WithAllBitsSet() : (ushort)0; + register.uint16_7 = left.register.uint16_7 > right.register.uint16_7 ? ConstantHelper.GetUInt16WithAllBitsSet() : (ushort)0; return new Vector(ref register); } - else if (typeof(T) == typeof(Int16)) + else if (typeof(T) == typeof(short)) { - register.int16_0 = left.register.int16_0 > right.register.int16_0 ? ConstantHelper.GetInt16WithAllBitsSet() : (Int16)0; - register.int16_1 = left.register.int16_1 > right.register.int16_1 ? ConstantHelper.GetInt16WithAllBitsSet() : (Int16)0; - register.int16_2 = left.register.int16_2 > right.register.int16_2 ? ConstantHelper.GetInt16WithAllBitsSet() : (Int16)0; - register.int16_3 = left.register.int16_3 > right.register.int16_3 ? ConstantHelper.GetInt16WithAllBitsSet() : (Int16)0; - register.int16_4 = left.register.int16_4 > right.register.int16_4 ? ConstantHelper.GetInt16WithAllBitsSet() : (Int16)0; - register.int16_5 = left.register.int16_5 > right.register.int16_5 ? ConstantHelper.GetInt16WithAllBitsSet() : (Int16)0; - register.int16_6 = left.register.int16_6 > right.register.int16_6 ? ConstantHelper.GetInt16WithAllBitsSet() : (Int16)0; - register.int16_7 = left.register.int16_7 > right.register.int16_7 ? ConstantHelper.GetInt16WithAllBitsSet() : (Int16)0; + register.int16_0 = left.register.int16_0 > right.register.int16_0 ? ConstantHelper.GetInt16WithAllBitsSet() : (short)0; + register.int16_1 = left.register.int16_1 > right.register.int16_1 ? ConstantHelper.GetInt16WithAllBitsSet() : (short)0; + register.int16_2 = left.register.int16_2 > right.register.int16_2 ? ConstantHelper.GetInt16WithAllBitsSet() : (short)0; + register.int16_3 = left.register.int16_3 > right.register.int16_3 ? ConstantHelper.GetInt16WithAllBitsSet() : (short)0; + register.int16_4 = left.register.int16_4 > right.register.int16_4 ? ConstantHelper.GetInt16WithAllBitsSet() : (short)0; + register.int16_5 = left.register.int16_5 > right.register.int16_5 ? ConstantHelper.GetInt16WithAllBitsSet() : (short)0; + register.int16_6 = left.register.int16_6 > right.register.int16_6 ? ConstantHelper.GetInt16WithAllBitsSet() : (short)0; + register.int16_7 = left.register.int16_7 > right.register.int16_7 ? ConstantHelper.GetInt16WithAllBitsSet() : (short)0; return new Vector(ref register); } - else if (typeof(T) == typeof(UInt32)) + else if (typeof(T) == typeof(uint)) { - register.uint32_0 = left.register.uint32_0 > right.register.uint32_0 ? ConstantHelper.GetUInt32WithAllBitsSet() : (UInt32)0; - register.uint32_1 = left.register.uint32_1 > right.register.uint32_1 ? ConstantHelper.GetUInt32WithAllBitsSet() : (UInt32)0; - register.uint32_2 = left.register.uint32_2 > right.register.uint32_2 ? ConstantHelper.GetUInt32WithAllBitsSet() : (UInt32)0; - register.uint32_3 = left.register.uint32_3 > right.register.uint32_3 ? ConstantHelper.GetUInt32WithAllBitsSet() : (UInt32)0; + register.uint32_0 = left.register.uint32_0 > right.register.uint32_0 ? ConstantHelper.GetUInt32WithAllBitsSet() : (uint)0; + register.uint32_1 = left.register.uint32_1 > right.register.uint32_1 ? ConstantHelper.GetUInt32WithAllBitsSet() : (uint)0; + register.uint32_2 = left.register.uint32_2 > right.register.uint32_2 ? ConstantHelper.GetUInt32WithAllBitsSet() : (uint)0; + register.uint32_3 = left.register.uint32_3 > right.register.uint32_3 ? ConstantHelper.GetUInt32WithAllBitsSet() : (uint)0; return new Vector(ref register); } - else if (typeof(T) == typeof(Int32)) + else if (typeof(T) == typeof(int)) { - register.int32_0 = left.register.int32_0 > right.register.int32_0 ? ConstantHelper.GetInt32WithAllBitsSet() : (Int32)0; - register.int32_1 = left.register.int32_1 > right.register.int32_1 ? ConstantHelper.GetInt32WithAllBitsSet() : (Int32)0; - register.int32_2 = left.register.int32_2 > right.register.int32_2 ? ConstantHelper.GetInt32WithAllBitsSet() : (Int32)0; - register.int32_3 = left.register.int32_3 > right.register.int32_3 ? ConstantHelper.GetInt32WithAllBitsSet() : (Int32)0; + register.int32_0 = left.register.int32_0 > right.register.int32_0 ? ConstantHelper.GetInt32WithAllBitsSet() : (int)0; + register.int32_1 = left.register.int32_1 > right.register.int32_1 ? ConstantHelper.GetInt32WithAllBitsSet() : (int)0; + register.int32_2 = left.register.int32_2 > right.register.int32_2 ? ConstantHelper.GetInt32WithAllBitsSet() : (int)0; + register.int32_3 = left.register.int32_3 > right.register.int32_3 ? ConstantHelper.GetInt32WithAllBitsSet() : (int)0; return new Vector(ref register); } - else if (typeof(T) == typeof(UInt64)) + else if (typeof(T) == typeof(ulong)) { - register.uint64_0 = left.register.uint64_0 > right.register.uint64_0 ? ConstantHelper.GetUInt64WithAllBitsSet() : (UInt64)0; - register.uint64_1 = left.register.uint64_1 > right.register.uint64_1 ? ConstantHelper.GetUInt64WithAllBitsSet() : (UInt64)0; + register.uint64_0 = left.register.uint64_0 > right.register.uint64_0 ? ConstantHelper.GetUInt64WithAllBitsSet() : (ulong)0; + register.uint64_1 = left.register.uint64_1 > right.register.uint64_1 ? ConstantHelper.GetUInt64WithAllBitsSet() : (ulong)0; return new Vector(ref register); } - else if (typeof(T) == typeof(Int64)) + else if (typeof(T) == typeof(long)) { - register.int64_0 = left.register.int64_0 > right.register.int64_0 ? ConstantHelper.GetInt64WithAllBitsSet() : (Int64)0; - register.int64_1 = left.register.int64_1 > right.register.int64_1 ? ConstantHelper.GetInt64WithAllBitsSet() : (Int64)0; + register.int64_0 = left.register.int64_0 > right.register.int64_0 ? ConstantHelper.GetInt64WithAllBitsSet() : (long)0; + register.int64_1 = left.register.int64_1 > right.register.int64_1 ? ConstantHelper.GetInt64WithAllBitsSet() : (long)0; return new Vector(ref register); } - else if (typeof(T) == typeof(Single)) + else if (typeof(T) == typeof(float)) { - register.single_0 = left.register.single_0 > right.register.single_0 ? ConstantHelper.GetSingleWithAllBitsSet() : (Single)0; - register.single_1 = left.register.single_1 > right.register.single_1 ? ConstantHelper.GetSingleWithAllBitsSet() : (Single)0; - register.single_2 = left.register.single_2 > right.register.single_2 ? ConstantHelper.GetSingleWithAllBitsSet() : (Single)0; - register.single_3 = left.register.single_3 > right.register.single_3 ? ConstantHelper.GetSingleWithAllBitsSet() : (Single)0; + register.single_0 = left.register.single_0 > right.register.single_0 ? ConstantHelper.GetSingleWithAllBitsSet() : (float)0; + register.single_1 = left.register.single_1 > right.register.single_1 ? ConstantHelper.GetSingleWithAllBitsSet() : (float)0; + register.single_2 = left.register.single_2 > right.register.single_2 ? ConstantHelper.GetSingleWithAllBitsSet() : (float)0; + register.single_3 = left.register.single_3 > right.register.single_3 ? ConstantHelper.GetSingleWithAllBitsSet() : (float)0; return new Vector(ref register); } - else if (typeof(T) == typeof(Double)) + else if (typeof(T) == typeof(double)) { - register.double_0 = left.register.double_0 > right.register.double_0 ? ConstantHelper.GetDoubleWithAllBitsSet() : (Double)0; - register.double_1 = left.register.double_1 > right.register.double_1 ? ConstantHelper.GetDoubleWithAllBitsSet() : (Double)0; + register.double_0 = left.register.double_0 > right.register.double_0 ? ConstantHelper.GetDoubleWithAllBitsSet() : (double)0; + register.double_1 = left.register.double_1 > right.register.double_1 ? ConstantHelper.GetDoubleWithAllBitsSet() : (double)0; return new Vector(ref register); } else @@ -3604,75 +3604,75 @@ internal static Vector ConditionalSelect(Vector condition, Vector left, [Intrinsic] internal static unsafe Vector Abs(Vector value) { - if (typeof(T) == typeof(Byte)) + if (typeof(T) == typeof(byte)) { return value; } - else if (typeof(T) == typeof(UInt16)) + else if (typeof(T) == typeof(ushort)) { return value; } - else if (typeof(T) == typeof(UInt32)) + else if (typeof(T) == typeof(uint)) { return value; } - else if (typeof(T) == typeof(UInt64)) + else if (typeof(T) == typeof(ulong)) { return value; } if (Vector.IsHardwareAccelerated) { - if (typeof(T) == typeof(SByte)) + if (typeof(T) == typeof(sbyte)) { - SByte* dataPtr = stackalloc SByte[Count]; + sbyte* dataPtr = stackalloc sbyte[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (SByte)(object)(Math.Abs((SByte)(object)value[g])); + dataPtr[g] = (sbyte)(object)(Math.Abs((sbyte)(object)value[g])); } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Int16)) + else if (typeof(T) == typeof(short)) { - Int16* dataPtr = stackalloc Int16[Count]; + short* dataPtr = stackalloc short[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (Int16)(object)(Math.Abs((Int16)(object)value[g])); + dataPtr[g] = (short)(object)(Math.Abs((short)(object)value[g])); } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Int32)) + else if (typeof(T) == typeof(int)) { - Int32* dataPtr = stackalloc Int32[Count]; + int* dataPtr = stackalloc int[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (Int32)(object)(Math.Abs((Int32)(object)value[g])); + dataPtr[g] = (int)(object)(Math.Abs((int)(object)value[g])); } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Int64)) + else if (typeof(T) == typeof(long)) { - Int64* dataPtr = stackalloc Int64[Count]; + long* dataPtr = stackalloc long[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (Int64)(object)(Math.Abs((Int64)(object)value[g])); + dataPtr[g] = (long)(object)(Math.Abs((long)(object)value[g])); } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Single)) + else if (typeof(T) == typeof(float)) { - Single* dataPtr = stackalloc Single[Count]; + float* dataPtr = stackalloc float[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (Single)(object)(Math.Abs((Single)(object)value[g])); + dataPtr[g] = (float)(object)(Math.Abs((float)(object)value[g])); } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Double)) + else if (typeof(T) == typeof(double)) { - Double* dataPtr = stackalloc Double[Count]; + double* dataPtr = stackalloc double[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = (Double)(object)(Math.Abs((Double)(object)value[g])); + dataPtr[g] = (double)(object)(Math.Abs((double)(object)value[g])); } return new Vector(dataPtr); } @@ -3683,64 +3683,64 @@ internal static unsafe Vector Abs(Vector value) } else { - if (typeof(T) == typeof(SByte)) - { - value.register.sbyte_0 = (SByte)(Math.Abs(value.register.sbyte_0)); - value.register.sbyte_1 = (SByte)(Math.Abs(value.register.sbyte_1)); - value.register.sbyte_2 = (SByte)(Math.Abs(value.register.sbyte_2)); - value.register.sbyte_3 = (SByte)(Math.Abs(value.register.sbyte_3)); - value.register.sbyte_4 = (SByte)(Math.Abs(value.register.sbyte_4)); - value.register.sbyte_5 = (SByte)(Math.Abs(value.register.sbyte_5)); - value.register.sbyte_6 = (SByte)(Math.Abs(value.register.sbyte_6)); - value.register.sbyte_7 = (SByte)(Math.Abs(value.register.sbyte_7)); - value.register.sbyte_8 = (SByte)(Math.Abs(value.register.sbyte_8)); - value.register.sbyte_9 = (SByte)(Math.Abs(value.register.sbyte_9)); - value.register.sbyte_10 = (SByte)(Math.Abs(value.register.sbyte_10)); - value.register.sbyte_11 = (SByte)(Math.Abs(value.register.sbyte_11)); - value.register.sbyte_12 = (SByte)(Math.Abs(value.register.sbyte_12)); - value.register.sbyte_13 = (SByte)(Math.Abs(value.register.sbyte_13)); - value.register.sbyte_14 = (SByte)(Math.Abs(value.register.sbyte_14)); - value.register.sbyte_15 = (SByte)(Math.Abs(value.register.sbyte_15)); + if (typeof(T) == typeof(sbyte)) + { + value.register.sbyte_0 = (sbyte)(Math.Abs(value.register.sbyte_0)); + value.register.sbyte_1 = (sbyte)(Math.Abs(value.register.sbyte_1)); + value.register.sbyte_2 = (sbyte)(Math.Abs(value.register.sbyte_2)); + value.register.sbyte_3 = (sbyte)(Math.Abs(value.register.sbyte_3)); + value.register.sbyte_4 = (sbyte)(Math.Abs(value.register.sbyte_4)); + value.register.sbyte_5 = (sbyte)(Math.Abs(value.register.sbyte_5)); + value.register.sbyte_6 = (sbyte)(Math.Abs(value.register.sbyte_6)); + value.register.sbyte_7 = (sbyte)(Math.Abs(value.register.sbyte_7)); + value.register.sbyte_8 = (sbyte)(Math.Abs(value.register.sbyte_8)); + value.register.sbyte_9 = (sbyte)(Math.Abs(value.register.sbyte_9)); + value.register.sbyte_10 = (sbyte)(Math.Abs(value.register.sbyte_10)); + value.register.sbyte_11 = (sbyte)(Math.Abs(value.register.sbyte_11)); + value.register.sbyte_12 = (sbyte)(Math.Abs(value.register.sbyte_12)); + value.register.sbyte_13 = (sbyte)(Math.Abs(value.register.sbyte_13)); + value.register.sbyte_14 = (sbyte)(Math.Abs(value.register.sbyte_14)); + value.register.sbyte_15 = (sbyte)(Math.Abs(value.register.sbyte_15)); return value; } - else if (typeof(T) == typeof(Int16)) + else if (typeof(T) == typeof(short)) { - value.register.int16_0 = (Int16)(Math.Abs(value.register.int16_0)); - value.register.int16_1 = (Int16)(Math.Abs(value.register.int16_1)); - value.register.int16_2 = (Int16)(Math.Abs(value.register.int16_2)); - value.register.int16_3 = (Int16)(Math.Abs(value.register.int16_3)); - value.register.int16_4 = (Int16)(Math.Abs(value.register.int16_4)); - value.register.int16_5 = (Int16)(Math.Abs(value.register.int16_5)); - value.register.int16_6 = (Int16)(Math.Abs(value.register.int16_6)); - value.register.int16_7 = (Int16)(Math.Abs(value.register.int16_7)); + value.register.int16_0 = (short)(Math.Abs(value.register.int16_0)); + value.register.int16_1 = (short)(Math.Abs(value.register.int16_1)); + value.register.int16_2 = (short)(Math.Abs(value.register.int16_2)); + value.register.int16_3 = (short)(Math.Abs(value.register.int16_3)); + value.register.int16_4 = (short)(Math.Abs(value.register.int16_4)); + value.register.int16_5 = (short)(Math.Abs(value.register.int16_5)); + value.register.int16_6 = (short)(Math.Abs(value.register.int16_6)); + value.register.int16_7 = (short)(Math.Abs(value.register.int16_7)); return value; } - else if (typeof(T) == typeof(Int32)) + else if (typeof(T) == typeof(int)) { - value.register.int32_0 = (Int32)(Math.Abs(value.register.int32_0)); - value.register.int32_1 = (Int32)(Math.Abs(value.register.int32_1)); - value.register.int32_2 = (Int32)(Math.Abs(value.register.int32_2)); - value.register.int32_3 = (Int32)(Math.Abs(value.register.int32_3)); + value.register.int32_0 = (int)(Math.Abs(value.register.int32_0)); + value.register.int32_1 = (int)(Math.Abs(value.register.int32_1)); + value.register.int32_2 = (int)(Math.Abs(value.register.int32_2)); + value.register.int32_3 = (int)(Math.Abs(value.register.int32_3)); return value; } - else if (typeof(T) == typeof(Int64)) + else if (typeof(T) == typeof(long)) { - value.register.int64_0 = (Int64)(Math.Abs(value.register.int64_0)); - value.register.int64_1 = (Int64)(Math.Abs(value.register.int64_1)); + value.register.int64_0 = (long)(Math.Abs(value.register.int64_0)); + value.register.int64_1 = (long)(Math.Abs(value.register.int64_1)); return value; } - else if (typeof(T) == typeof(Single)) + else if (typeof(T) == typeof(float)) { - value.register.single_0 = (Single)(Math.Abs(value.register.single_0)); - value.register.single_1 = (Single)(Math.Abs(value.register.single_1)); - value.register.single_2 = (Single)(Math.Abs(value.register.single_2)); - value.register.single_3 = (Single)(Math.Abs(value.register.single_3)); + value.register.single_0 = (float)(Math.Abs(value.register.single_0)); + value.register.single_1 = (float)(Math.Abs(value.register.single_1)); + value.register.single_2 = (float)(Math.Abs(value.register.single_2)); + value.register.single_3 = (float)(Math.Abs(value.register.single_3)); return value; } - else if (typeof(T) == typeof(Double)) + else if (typeof(T) == typeof(double)) { - value.register.double_0 = (Double)(Math.Abs(value.register.double_0)); - value.register.double_1 = (Double)(Math.Abs(value.register.double_1)); + value.register.double_0 = (double)(Math.Abs(value.register.double_0)); + value.register.double_1 = (double)(Math.Abs(value.register.double_1)); return value; } else @@ -3755,93 +3755,93 @@ internal static unsafe Vector Min(Vector left, Vector right) { if (Vector.IsHardwareAccelerated) { - if (typeof(T) == typeof(Byte)) + if (typeof(T) == typeof(byte)) { - Byte* dataPtr = stackalloc Byte[Count]; + byte* dataPtr = stackalloc byte[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarLessThan(left[g], right[g]) ? (Byte)(object)left[g] : (Byte)(object)right[g]; + dataPtr[g] = ScalarLessThan(left[g], right[g]) ? (byte)(object)left[g] : (byte)(object)right[g]; } return new Vector(dataPtr); } - else if (typeof(T) == typeof(SByte)) + else if (typeof(T) == typeof(sbyte)) { - SByte* dataPtr = stackalloc SByte[Count]; + sbyte* dataPtr = stackalloc sbyte[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarLessThan(left[g], right[g]) ? (SByte)(object)left[g] : (SByte)(object)right[g]; + dataPtr[g] = ScalarLessThan(left[g], right[g]) ? (sbyte)(object)left[g] : (sbyte)(object)right[g]; } return new Vector(dataPtr); } - else if (typeof(T) == typeof(UInt16)) + else if (typeof(T) == typeof(ushort)) { - UInt16* dataPtr = stackalloc UInt16[Count]; + ushort* dataPtr = stackalloc ushort[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarLessThan(left[g], right[g]) ? (UInt16)(object)left[g] : (UInt16)(object)right[g]; + dataPtr[g] = ScalarLessThan(left[g], right[g]) ? (ushort)(object)left[g] : (ushort)(object)right[g]; } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Int16)) + else if (typeof(T) == typeof(short)) { - Int16* dataPtr = stackalloc Int16[Count]; + short* dataPtr = stackalloc short[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarLessThan(left[g], right[g]) ? (Int16)(object)left[g] : (Int16)(object)right[g]; + dataPtr[g] = ScalarLessThan(left[g], right[g]) ? (short)(object)left[g] : (short)(object)right[g]; } return new Vector(dataPtr); } - else if (typeof(T) == typeof(UInt32)) + else if (typeof(T) == typeof(uint)) { - UInt32* dataPtr = stackalloc UInt32[Count]; + uint* dataPtr = stackalloc uint[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarLessThan(left[g], right[g]) ? (UInt32)(object)left[g] : (UInt32)(object)right[g]; + dataPtr[g] = ScalarLessThan(left[g], right[g]) ? (uint)(object)left[g] : (uint)(object)right[g]; } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Int32)) + else if (typeof(T) == typeof(int)) { - Int32* dataPtr = stackalloc Int32[Count]; + int* dataPtr = stackalloc int[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarLessThan(left[g], right[g]) ? (Int32)(object)left[g] : (Int32)(object)right[g]; + dataPtr[g] = ScalarLessThan(left[g], right[g]) ? (int)(object)left[g] : (int)(object)right[g]; } return new Vector(dataPtr); } - else if (typeof(T) == typeof(UInt64)) + else if (typeof(T) == typeof(ulong)) { - UInt64* dataPtr = stackalloc UInt64[Count]; + ulong* dataPtr = stackalloc ulong[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarLessThan(left[g], right[g]) ? (UInt64)(object)left[g] : (UInt64)(object)right[g]; + dataPtr[g] = ScalarLessThan(left[g], right[g]) ? (ulong)(object)left[g] : (ulong)(object)right[g]; } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Int64)) + else if (typeof(T) == typeof(long)) { - Int64* dataPtr = stackalloc Int64[Count]; + long* dataPtr = stackalloc long[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarLessThan(left[g], right[g]) ? (Int64)(object)left[g] : (Int64)(object)right[g]; + dataPtr[g] = ScalarLessThan(left[g], right[g]) ? (long)(object)left[g] : (long)(object)right[g]; } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Single)) + else if (typeof(T) == typeof(float)) { - Single* dataPtr = stackalloc Single[Count]; + float* dataPtr = stackalloc float[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarLessThan(left[g], right[g]) ? (Single)(object)left[g] : (Single)(object)right[g]; + dataPtr[g] = ScalarLessThan(left[g], right[g]) ? (float)(object)left[g] : (float)(object)right[g]; } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Double)) + else if (typeof(T) == typeof(double)) { - Double* dataPtr = stackalloc Double[Count]; + double* dataPtr = stackalloc double[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarLessThan(left[g], right[g]) ? (Double)(object)left[g] : (Double)(object)right[g]; + dataPtr[g] = ScalarLessThan(left[g], right[g]) ? (double)(object)left[g] : (double)(object)right[g]; } return new Vector(dataPtr); } @@ -3853,7 +3853,7 @@ internal static unsafe Vector Min(Vector left, Vector right) else { Vector vec = new Vector(); - if (typeof(T) == typeof(Byte)) + if (typeof(T) == typeof(byte)) { vec.register.byte_0 = left.register.byte_0 < right.register.byte_0 ? left.register.byte_0 : right.register.byte_0; vec.register.byte_1 = left.register.byte_1 < right.register.byte_1 ? left.register.byte_1 : right.register.byte_1; @@ -3873,7 +3873,7 @@ internal static unsafe Vector Min(Vector left, Vector right) vec.register.byte_15 = left.register.byte_15 < right.register.byte_15 ? left.register.byte_15 : right.register.byte_15; return vec; } - else if (typeof(T) == typeof(SByte)) + else if (typeof(T) == typeof(sbyte)) { vec.register.sbyte_0 = left.register.sbyte_0 < right.register.sbyte_0 ? left.register.sbyte_0 : right.register.sbyte_0; vec.register.sbyte_1 = left.register.sbyte_1 < right.register.sbyte_1 ? left.register.sbyte_1 : right.register.sbyte_1; @@ -3893,7 +3893,7 @@ internal static unsafe Vector Min(Vector left, Vector right) vec.register.sbyte_15 = left.register.sbyte_15 < right.register.sbyte_15 ? left.register.sbyte_15 : right.register.sbyte_15; return vec; } - else if (typeof(T) == typeof(UInt16)) + else if (typeof(T) == typeof(ushort)) { vec.register.uint16_0 = left.register.uint16_0 < right.register.uint16_0 ? left.register.uint16_0 : right.register.uint16_0; vec.register.uint16_1 = left.register.uint16_1 < right.register.uint16_1 ? left.register.uint16_1 : right.register.uint16_1; @@ -3905,7 +3905,7 @@ internal static unsafe Vector Min(Vector left, Vector right) vec.register.uint16_7 = left.register.uint16_7 < right.register.uint16_7 ? left.register.uint16_7 : right.register.uint16_7; return vec; } - else if (typeof(T) == typeof(Int16)) + else if (typeof(T) == typeof(short)) { vec.register.int16_0 = left.register.int16_0 < right.register.int16_0 ? left.register.int16_0 : right.register.int16_0; vec.register.int16_1 = left.register.int16_1 < right.register.int16_1 ? left.register.int16_1 : right.register.int16_1; @@ -3917,7 +3917,7 @@ internal static unsafe Vector Min(Vector left, Vector right) vec.register.int16_7 = left.register.int16_7 < right.register.int16_7 ? left.register.int16_7 : right.register.int16_7; return vec; } - else if (typeof(T) == typeof(UInt32)) + else if (typeof(T) == typeof(uint)) { vec.register.uint32_0 = left.register.uint32_0 < right.register.uint32_0 ? left.register.uint32_0 : right.register.uint32_0; vec.register.uint32_1 = left.register.uint32_1 < right.register.uint32_1 ? left.register.uint32_1 : right.register.uint32_1; @@ -3925,7 +3925,7 @@ internal static unsafe Vector Min(Vector left, Vector right) vec.register.uint32_3 = left.register.uint32_3 < right.register.uint32_3 ? left.register.uint32_3 : right.register.uint32_3; return vec; } - else if (typeof(T) == typeof(Int32)) + else if (typeof(T) == typeof(int)) { vec.register.int32_0 = left.register.int32_0 < right.register.int32_0 ? left.register.int32_0 : right.register.int32_0; vec.register.int32_1 = left.register.int32_1 < right.register.int32_1 ? left.register.int32_1 : right.register.int32_1; @@ -3933,19 +3933,19 @@ internal static unsafe Vector Min(Vector left, Vector right) vec.register.int32_3 = left.register.int32_3 < right.register.int32_3 ? left.register.int32_3 : right.register.int32_3; return vec; } - else if (typeof(T) == typeof(UInt64)) + else if (typeof(T) == typeof(ulong)) { vec.register.uint64_0 = left.register.uint64_0 < right.register.uint64_0 ? left.register.uint64_0 : right.register.uint64_0; vec.register.uint64_1 = left.register.uint64_1 < right.register.uint64_1 ? left.register.uint64_1 : right.register.uint64_1; return vec; } - else if (typeof(T) == typeof(Int64)) + else if (typeof(T) == typeof(long)) { vec.register.int64_0 = left.register.int64_0 < right.register.int64_0 ? left.register.int64_0 : right.register.int64_0; vec.register.int64_1 = left.register.int64_1 < right.register.int64_1 ? left.register.int64_1 : right.register.int64_1; return vec; } - else if (typeof(T) == typeof(Single)) + else if (typeof(T) == typeof(float)) { vec.register.single_0 = left.register.single_0 < right.register.single_0 ? left.register.single_0 : right.register.single_0; vec.register.single_1 = left.register.single_1 < right.register.single_1 ? left.register.single_1 : right.register.single_1; @@ -3953,7 +3953,7 @@ internal static unsafe Vector Min(Vector left, Vector right) vec.register.single_3 = left.register.single_3 < right.register.single_3 ? left.register.single_3 : right.register.single_3; return vec; } - else if (typeof(T) == typeof(Double)) + else if (typeof(T) == typeof(double)) { vec.register.double_0 = left.register.double_0 < right.register.double_0 ? left.register.double_0 : right.register.double_0; vec.register.double_1 = left.register.double_1 < right.register.double_1 ? left.register.double_1 : right.register.double_1; @@ -3971,93 +3971,93 @@ internal static unsafe Vector Max(Vector left, Vector right) { if (Vector.IsHardwareAccelerated) { - if (typeof(T) == typeof(Byte)) + if (typeof(T) == typeof(byte)) { - Byte* dataPtr = stackalloc Byte[Count]; + byte* dataPtr = stackalloc byte[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarGreaterThan(left[g], right[g]) ? (Byte)(object)left[g] : (Byte)(object)right[g]; + dataPtr[g] = ScalarGreaterThan(left[g], right[g]) ? (byte)(object)left[g] : (byte)(object)right[g]; } return new Vector(dataPtr); } - else if (typeof(T) == typeof(SByte)) + else if (typeof(T) == typeof(sbyte)) { - SByte* dataPtr = stackalloc SByte[Count]; + sbyte* dataPtr = stackalloc sbyte[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarGreaterThan(left[g], right[g]) ? (SByte)(object)left[g] : (SByte)(object)right[g]; + dataPtr[g] = ScalarGreaterThan(left[g], right[g]) ? (sbyte)(object)left[g] : (sbyte)(object)right[g]; } return new Vector(dataPtr); } - else if (typeof(T) == typeof(UInt16)) + else if (typeof(T) == typeof(ushort)) { - UInt16* dataPtr = stackalloc UInt16[Count]; + ushort* dataPtr = stackalloc ushort[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarGreaterThan(left[g], right[g]) ? (UInt16)(object)left[g] : (UInt16)(object)right[g]; + dataPtr[g] = ScalarGreaterThan(left[g], right[g]) ? (ushort)(object)left[g] : (ushort)(object)right[g]; } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Int16)) + else if (typeof(T) == typeof(short)) { - Int16* dataPtr = stackalloc Int16[Count]; + short* dataPtr = stackalloc short[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarGreaterThan(left[g], right[g]) ? (Int16)(object)left[g] : (Int16)(object)right[g]; + dataPtr[g] = ScalarGreaterThan(left[g], right[g]) ? (short)(object)left[g] : (short)(object)right[g]; } return new Vector(dataPtr); } - else if (typeof(T) == typeof(UInt32)) + else if (typeof(T) == typeof(uint)) { - UInt32* dataPtr = stackalloc UInt32[Count]; + uint* dataPtr = stackalloc uint[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarGreaterThan(left[g], right[g]) ? (UInt32)(object)left[g] : (UInt32)(object)right[g]; + dataPtr[g] = ScalarGreaterThan(left[g], right[g]) ? (uint)(object)left[g] : (uint)(object)right[g]; } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Int32)) + else if (typeof(T) == typeof(int)) { - Int32* dataPtr = stackalloc Int32[Count]; + int* dataPtr = stackalloc int[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarGreaterThan(left[g], right[g]) ? (Int32)(object)left[g] : (Int32)(object)right[g]; + dataPtr[g] = ScalarGreaterThan(left[g], right[g]) ? (int)(object)left[g] : (int)(object)right[g]; } return new Vector(dataPtr); } - else if (typeof(T) == typeof(UInt64)) + else if (typeof(T) == typeof(ulong)) { - UInt64* dataPtr = stackalloc UInt64[Count]; + ulong* dataPtr = stackalloc ulong[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarGreaterThan(left[g], right[g]) ? (UInt64)(object)left[g] : (UInt64)(object)right[g]; + dataPtr[g] = ScalarGreaterThan(left[g], right[g]) ? (ulong)(object)left[g] : (ulong)(object)right[g]; } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Int64)) + else if (typeof(T) == typeof(long)) { - Int64* dataPtr = stackalloc Int64[Count]; + long* dataPtr = stackalloc long[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarGreaterThan(left[g], right[g]) ? (Int64)(object)left[g] : (Int64)(object)right[g]; + dataPtr[g] = ScalarGreaterThan(left[g], right[g]) ? (long)(object)left[g] : (long)(object)right[g]; } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Single)) + else if (typeof(T) == typeof(float)) { - Single* dataPtr = stackalloc Single[Count]; + float* dataPtr = stackalloc float[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarGreaterThan(left[g], right[g]) ? (Single)(object)left[g] : (Single)(object)right[g]; + dataPtr[g] = ScalarGreaterThan(left[g], right[g]) ? (float)(object)left[g] : (float)(object)right[g]; } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Double)) + else if (typeof(T) == typeof(double)) { - Double* dataPtr = stackalloc Double[Count]; + double* dataPtr = stackalloc double[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = ScalarGreaterThan(left[g], right[g]) ? (Double)(object)left[g] : (Double)(object)right[g]; + dataPtr[g] = ScalarGreaterThan(left[g], right[g]) ? (double)(object)left[g] : (double)(object)right[g]; } return new Vector(dataPtr); } @@ -4069,7 +4069,7 @@ internal static unsafe Vector Max(Vector left, Vector right) else { Vector vec = new Vector(); - if (typeof(T) == typeof(Byte)) + if (typeof(T) == typeof(byte)) { vec.register.byte_0 = left.register.byte_0 > right.register.byte_0 ? left.register.byte_0 : right.register.byte_0; vec.register.byte_1 = left.register.byte_1 > right.register.byte_1 ? left.register.byte_1 : right.register.byte_1; @@ -4089,7 +4089,7 @@ internal static unsafe Vector Max(Vector left, Vector right) vec.register.byte_15 = left.register.byte_15 > right.register.byte_15 ? left.register.byte_15 : right.register.byte_15; return vec; } - else if (typeof(T) == typeof(SByte)) + else if (typeof(T) == typeof(sbyte)) { vec.register.sbyte_0 = left.register.sbyte_0 > right.register.sbyte_0 ? left.register.sbyte_0 : right.register.sbyte_0; vec.register.sbyte_1 = left.register.sbyte_1 > right.register.sbyte_1 ? left.register.sbyte_1 : right.register.sbyte_1; @@ -4109,7 +4109,7 @@ internal static unsafe Vector Max(Vector left, Vector right) vec.register.sbyte_15 = left.register.sbyte_15 > right.register.sbyte_15 ? left.register.sbyte_15 : right.register.sbyte_15; return vec; } - else if (typeof(T) == typeof(UInt16)) + else if (typeof(T) == typeof(ushort)) { vec.register.uint16_0 = left.register.uint16_0 > right.register.uint16_0 ? left.register.uint16_0 : right.register.uint16_0; vec.register.uint16_1 = left.register.uint16_1 > right.register.uint16_1 ? left.register.uint16_1 : right.register.uint16_1; @@ -4121,7 +4121,7 @@ internal static unsafe Vector Max(Vector left, Vector right) vec.register.uint16_7 = left.register.uint16_7 > right.register.uint16_7 ? left.register.uint16_7 : right.register.uint16_7; return vec; } - else if (typeof(T) == typeof(Int16)) + else if (typeof(T) == typeof(short)) { vec.register.int16_0 = left.register.int16_0 > right.register.int16_0 ? left.register.int16_0 : right.register.int16_0; vec.register.int16_1 = left.register.int16_1 > right.register.int16_1 ? left.register.int16_1 : right.register.int16_1; @@ -4133,7 +4133,7 @@ internal static unsafe Vector Max(Vector left, Vector right) vec.register.int16_7 = left.register.int16_7 > right.register.int16_7 ? left.register.int16_7 : right.register.int16_7; return vec; } - else if (typeof(T) == typeof(UInt32)) + else if (typeof(T) == typeof(uint)) { vec.register.uint32_0 = left.register.uint32_0 > right.register.uint32_0 ? left.register.uint32_0 : right.register.uint32_0; vec.register.uint32_1 = left.register.uint32_1 > right.register.uint32_1 ? left.register.uint32_1 : right.register.uint32_1; @@ -4141,7 +4141,7 @@ internal static unsafe Vector Max(Vector left, Vector right) vec.register.uint32_3 = left.register.uint32_3 > right.register.uint32_3 ? left.register.uint32_3 : right.register.uint32_3; return vec; } - else if (typeof(T) == typeof(Int32)) + else if (typeof(T) == typeof(int)) { vec.register.int32_0 = left.register.int32_0 > right.register.int32_0 ? left.register.int32_0 : right.register.int32_0; vec.register.int32_1 = left.register.int32_1 > right.register.int32_1 ? left.register.int32_1 : right.register.int32_1; @@ -4149,19 +4149,19 @@ internal static unsafe Vector Max(Vector left, Vector right) vec.register.int32_3 = left.register.int32_3 > right.register.int32_3 ? left.register.int32_3 : right.register.int32_3; return vec; } - else if (typeof(T) == typeof(UInt64)) + else if (typeof(T) == typeof(ulong)) { vec.register.uint64_0 = left.register.uint64_0 > right.register.uint64_0 ? left.register.uint64_0 : right.register.uint64_0; vec.register.uint64_1 = left.register.uint64_1 > right.register.uint64_1 ? left.register.uint64_1 : right.register.uint64_1; return vec; } - else if (typeof(T) == typeof(Int64)) + else if (typeof(T) == typeof(long)) { vec.register.int64_0 = left.register.int64_0 > right.register.int64_0 ? left.register.int64_0 : right.register.int64_0; vec.register.int64_1 = left.register.int64_1 > right.register.int64_1 ? left.register.int64_1 : right.register.int64_1; return vec; } - else if (typeof(T) == typeof(Single)) + else if (typeof(T) == typeof(float)) { vec.register.single_0 = left.register.single_0 > right.register.single_0 ? left.register.single_0 : right.register.single_0; vec.register.single_1 = left.register.single_1 > right.register.single_1 ? left.register.single_1 : right.register.single_1; @@ -4169,7 +4169,7 @@ internal static unsafe Vector Max(Vector left, Vector right) vec.register.single_3 = left.register.single_3 > right.register.single_3 ? left.register.single_3 : right.register.single_3; return vec; } - else if (typeof(T) == typeof(Double)) + else if (typeof(T) == typeof(double)) { vec.register.double_0 = left.register.double_0 > right.register.double_0 ? left.register.double_0 : right.register.double_0; vec.register.double_1 = left.register.double_1 > right.register.double_1 ? left.register.double_1 : right.register.double_1; @@ -4196,120 +4196,120 @@ internal static T DotProduct(Vector left, Vector right) } else { - if (typeof(T) == typeof(Byte)) - { - Byte product = 0; - product += (Byte)(left.register.byte_0 * right.register.byte_0); - product += (Byte)(left.register.byte_1 * right.register.byte_1); - product += (Byte)(left.register.byte_2 * right.register.byte_2); - product += (Byte)(left.register.byte_3 * right.register.byte_3); - product += (Byte)(left.register.byte_4 * right.register.byte_4); - product += (Byte)(left.register.byte_5 * right.register.byte_5); - product += (Byte)(left.register.byte_6 * right.register.byte_6); - product += (Byte)(left.register.byte_7 * right.register.byte_7); - product += (Byte)(left.register.byte_8 * right.register.byte_8); - product += (Byte)(left.register.byte_9 * right.register.byte_9); - product += (Byte)(left.register.byte_10 * right.register.byte_10); - product += (Byte)(left.register.byte_11 * right.register.byte_11); - product += (Byte)(left.register.byte_12 * right.register.byte_12); - product += (Byte)(left.register.byte_13 * right.register.byte_13); - product += (Byte)(left.register.byte_14 * right.register.byte_14); - product += (Byte)(left.register.byte_15 * right.register.byte_15); + if (typeof(T) == typeof(byte)) + { + byte product = 0; + product += (byte)(left.register.byte_0 * right.register.byte_0); + product += (byte)(left.register.byte_1 * right.register.byte_1); + product += (byte)(left.register.byte_2 * right.register.byte_2); + product += (byte)(left.register.byte_3 * right.register.byte_3); + product += (byte)(left.register.byte_4 * right.register.byte_4); + product += (byte)(left.register.byte_5 * right.register.byte_5); + product += (byte)(left.register.byte_6 * right.register.byte_6); + product += (byte)(left.register.byte_7 * right.register.byte_7); + product += (byte)(left.register.byte_8 * right.register.byte_8); + product += (byte)(left.register.byte_9 * right.register.byte_9); + product += (byte)(left.register.byte_10 * right.register.byte_10); + product += (byte)(left.register.byte_11 * right.register.byte_11); + product += (byte)(left.register.byte_12 * right.register.byte_12); + product += (byte)(left.register.byte_13 * right.register.byte_13); + product += (byte)(left.register.byte_14 * right.register.byte_14); + product += (byte)(left.register.byte_15 * right.register.byte_15); return (T)(object)product; } - else if (typeof(T) == typeof(SByte)) - { - SByte product = 0; - product += (SByte)(left.register.sbyte_0 * right.register.sbyte_0); - product += (SByte)(left.register.sbyte_1 * right.register.sbyte_1); - product += (SByte)(left.register.sbyte_2 * right.register.sbyte_2); - product += (SByte)(left.register.sbyte_3 * right.register.sbyte_3); - product += (SByte)(left.register.sbyte_4 * right.register.sbyte_4); - product += (SByte)(left.register.sbyte_5 * right.register.sbyte_5); - product += (SByte)(left.register.sbyte_6 * right.register.sbyte_6); - product += (SByte)(left.register.sbyte_7 * right.register.sbyte_7); - product += (SByte)(left.register.sbyte_8 * right.register.sbyte_8); - product += (SByte)(left.register.sbyte_9 * right.register.sbyte_9); - product += (SByte)(left.register.sbyte_10 * right.register.sbyte_10); - product += (SByte)(left.register.sbyte_11 * right.register.sbyte_11); - product += (SByte)(left.register.sbyte_12 * right.register.sbyte_12); - product += (SByte)(left.register.sbyte_13 * right.register.sbyte_13); - product += (SByte)(left.register.sbyte_14 * right.register.sbyte_14); - product += (SByte)(left.register.sbyte_15 * right.register.sbyte_15); + else if (typeof(T) == typeof(sbyte)) + { + sbyte product = 0; + product += (sbyte)(left.register.sbyte_0 * right.register.sbyte_0); + product += (sbyte)(left.register.sbyte_1 * right.register.sbyte_1); + product += (sbyte)(left.register.sbyte_2 * right.register.sbyte_2); + product += (sbyte)(left.register.sbyte_3 * right.register.sbyte_3); + product += (sbyte)(left.register.sbyte_4 * right.register.sbyte_4); + product += (sbyte)(left.register.sbyte_5 * right.register.sbyte_5); + product += (sbyte)(left.register.sbyte_6 * right.register.sbyte_6); + product += (sbyte)(left.register.sbyte_7 * right.register.sbyte_7); + product += (sbyte)(left.register.sbyte_8 * right.register.sbyte_8); + product += (sbyte)(left.register.sbyte_9 * right.register.sbyte_9); + product += (sbyte)(left.register.sbyte_10 * right.register.sbyte_10); + product += (sbyte)(left.register.sbyte_11 * right.register.sbyte_11); + product += (sbyte)(left.register.sbyte_12 * right.register.sbyte_12); + product += (sbyte)(left.register.sbyte_13 * right.register.sbyte_13); + product += (sbyte)(left.register.sbyte_14 * right.register.sbyte_14); + product += (sbyte)(left.register.sbyte_15 * right.register.sbyte_15); return (T)(object)product; } - else if (typeof(T) == typeof(UInt16)) - { - UInt16 product = 0; - product += (UInt16)(left.register.uint16_0 * right.register.uint16_0); - product += (UInt16)(left.register.uint16_1 * right.register.uint16_1); - product += (UInt16)(left.register.uint16_2 * right.register.uint16_2); - product += (UInt16)(left.register.uint16_3 * right.register.uint16_3); - product += (UInt16)(left.register.uint16_4 * right.register.uint16_4); - product += (UInt16)(left.register.uint16_5 * right.register.uint16_5); - product += (UInt16)(left.register.uint16_6 * right.register.uint16_6); - product += (UInt16)(left.register.uint16_7 * right.register.uint16_7); + else if (typeof(T) == typeof(ushort)) + { + ushort product = 0; + product += (ushort)(left.register.uint16_0 * right.register.uint16_0); + product += (ushort)(left.register.uint16_1 * right.register.uint16_1); + product += (ushort)(left.register.uint16_2 * right.register.uint16_2); + product += (ushort)(left.register.uint16_3 * right.register.uint16_3); + product += (ushort)(left.register.uint16_4 * right.register.uint16_4); + product += (ushort)(left.register.uint16_5 * right.register.uint16_5); + product += (ushort)(left.register.uint16_6 * right.register.uint16_6); + product += (ushort)(left.register.uint16_7 * right.register.uint16_7); return (T)(object)product; } - else if (typeof(T) == typeof(Int16)) - { - Int16 product = 0; - product += (Int16)(left.register.int16_0 * right.register.int16_0); - product += (Int16)(left.register.int16_1 * right.register.int16_1); - product += (Int16)(left.register.int16_2 * right.register.int16_2); - product += (Int16)(left.register.int16_3 * right.register.int16_3); - product += (Int16)(left.register.int16_4 * right.register.int16_4); - product += (Int16)(left.register.int16_5 * right.register.int16_5); - product += (Int16)(left.register.int16_6 * right.register.int16_6); - product += (Int16)(left.register.int16_7 * right.register.int16_7); + else if (typeof(T) == typeof(short)) + { + short product = 0; + product += (short)(left.register.int16_0 * right.register.int16_0); + product += (short)(left.register.int16_1 * right.register.int16_1); + product += (short)(left.register.int16_2 * right.register.int16_2); + product += (short)(left.register.int16_3 * right.register.int16_3); + product += (short)(left.register.int16_4 * right.register.int16_4); + product += (short)(left.register.int16_5 * right.register.int16_5); + product += (short)(left.register.int16_6 * right.register.int16_6); + product += (short)(left.register.int16_7 * right.register.int16_7); return (T)(object)product; } - else if (typeof(T) == typeof(UInt32)) + else if (typeof(T) == typeof(uint)) { - UInt32 product = 0; - product += (UInt32)(left.register.uint32_0 * right.register.uint32_0); - product += (UInt32)(left.register.uint32_1 * right.register.uint32_1); - product += (UInt32)(left.register.uint32_2 * right.register.uint32_2); - product += (UInt32)(left.register.uint32_3 * right.register.uint32_3); + uint product = 0; + product += (uint)(left.register.uint32_0 * right.register.uint32_0); + product += (uint)(left.register.uint32_1 * right.register.uint32_1); + product += (uint)(left.register.uint32_2 * right.register.uint32_2); + product += (uint)(left.register.uint32_3 * right.register.uint32_3); return (T)(object)product; } - else if (typeof(T) == typeof(Int32)) + else if (typeof(T) == typeof(int)) { - Int32 product = 0; - product += (Int32)(left.register.int32_0 * right.register.int32_0); - product += (Int32)(left.register.int32_1 * right.register.int32_1); - product += (Int32)(left.register.int32_2 * right.register.int32_2); - product += (Int32)(left.register.int32_3 * right.register.int32_3); + int product = 0; + product += (int)(left.register.int32_0 * right.register.int32_0); + product += (int)(left.register.int32_1 * right.register.int32_1); + product += (int)(left.register.int32_2 * right.register.int32_2); + product += (int)(left.register.int32_3 * right.register.int32_3); return (T)(object)product; } - else if (typeof(T) == typeof(UInt64)) + else if (typeof(T) == typeof(ulong)) { - UInt64 product = 0; - product += (UInt64)(left.register.uint64_0 * right.register.uint64_0); - product += (UInt64)(left.register.uint64_1 * right.register.uint64_1); + ulong product = 0; + product += (ulong)(left.register.uint64_0 * right.register.uint64_0); + product += (ulong)(left.register.uint64_1 * right.register.uint64_1); return (T)(object)product; } - else if (typeof(T) == typeof(Int64)) + else if (typeof(T) == typeof(long)) { - Int64 product = 0; - product += (Int64)(left.register.int64_0 * right.register.int64_0); - product += (Int64)(left.register.int64_1 * right.register.int64_1); + long product = 0; + product += (long)(left.register.int64_0 * right.register.int64_0); + product += (long)(left.register.int64_1 * right.register.int64_1); return (T)(object)product; } - else if (typeof(T) == typeof(Single)) + else if (typeof(T) == typeof(float)) { - Single product = 0; - product += (Single)(left.register.single_0 * right.register.single_0); - product += (Single)(left.register.single_1 * right.register.single_1); - product += (Single)(left.register.single_2 * right.register.single_2); - product += (Single)(left.register.single_3 * right.register.single_3); + float product = 0; + product += (float)(left.register.single_0 * right.register.single_0); + product += (float)(left.register.single_1 * right.register.single_1); + product += (float)(left.register.single_2 * right.register.single_2); + product += (float)(left.register.single_3 * right.register.single_3); return (T)(object)product; } - else if (typeof(T) == typeof(Double)) + else if (typeof(T) == typeof(double)) { - Double product = 0; - product += (Double)(left.register.double_0 * right.register.double_0); - product += (Double)(left.register.double_1 * right.register.double_1); + double product = 0; + product += (double)(left.register.double_0 * right.register.double_0); + product += (double)(left.register.double_1 * right.register.double_1); return (T)(object)product; } else @@ -4324,93 +4324,93 @@ internal static unsafe Vector SquareRoot(Vector value) { if (Vector.IsHardwareAccelerated) { - if (typeof(T) == typeof(Byte)) + if (typeof(T) == typeof(byte)) { - Byte* dataPtr = stackalloc Byte[Count]; + byte* dataPtr = stackalloc byte[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = unchecked((Byte)Math.Sqrt((Byte)(object)value[g])); + dataPtr[g] = unchecked((byte)Math.Sqrt((byte)(object)value[g])); } return new Vector(dataPtr); } - else if (typeof(T) == typeof(SByte)) + else if (typeof(T) == typeof(sbyte)) { - SByte* dataPtr = stackalloc SByte[Count]; + sbyte* dataPtr = stackalloc sbyte[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = unchecked((SByte)Math.Sqrt((SByte)(object)value[g])); + dataPtr[g] = unchecked((sbyte)Math.Sqrt((sbyte)(object)value[g])); } return new Vector(dataPtr); } - else if (typeof(T) == typeof(UInt16)) + else if (typeof(T) == typeof(ushort)) { - UInt16* dataPtr = stackalloc UInt16[Count]; + ushort* dataPtr = stackalloc ushort[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = unchecked((UInt16)Math.Sqrt((UInt16)(object)value[g])); + dataPtr[g] = unchecked((ushort)Math.Sqrt((ushort)(object)value[g])); } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Int16)) + else if (typeof(T) == typeof(short)) { - Int16* dataPtr = stackalloc Int16[Count]; + short* dataPtr = stackalloc short[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = unchecked((Int16)Math.Sqrt((Int16)(object)value[g])); + dataPtr[g] = unchecked((short)Math.Sqrt((short)(object)value[g])); } return new Vector(dataPtr); } - else if (typeof(T) == typeof(UInt32)) + else if (typeof(T) == typeof(uint)) { - UInt32* dataPtr = stackalloc UInt32[Count]; + uint* dataPtr = stackalloc uint[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = unchecked((UInt32)Math.Sqrt((UInt32)(object)value[g])); + dataPtr[g] = unchecked((uint)Math.Sqrt((uint)(object)value[g])); } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Int32)) + else if (typeof(T) == typeof(int)) { - Int32* dataPtr = stackalloc Int32[Count]; + int* dataPtr = stackalloc int[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = unchecked((Int32)Math.Sqrt((Int32)(object)value[g])); + dataPtr[g] = unchecked((int)Math.Sqrt((int)(object)value[g])); } return new Vector(dataPtr); } - else if (typeof(T) == typeof(UInt64)) + else if (typeof(T) == typeof(ulong)) { - UInt64* dataPtr = stackalloc UInt64[Count]; + ulong* dataPtr = stackalloc ulong[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = unchecked((UInt64)Math.Sqrt((UInt64)(object)value[g])); + dataPtr[g] = unchecked((ulong)Math.Sqrt((ulong)(object)value[g])); } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Int64)) + else if (typeof(T) == typeof(long)) { - Int64* dataPtr = stackalloc Int64[Count]; + long* dataPtr = stackalloc long[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = unchecked((Int64)Math.Sqrt((Int64)(object)value[g])); + dataPtr[g] = unchecked((long)Math.Sqrt((long)(object)value[g])); } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Single)) + else if (typeof(T) == typeof(float)) { - Single* dataPtr = stackalloc Single[Count]; + float* dataPtr = stackalloc float[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = unchecked((Single)Math.Sqrt((Single)(object)value[g])); + dataPtr[g] = unchecked((float)Math.Sqrt((float)(object)value[g])); } return new Vector(dataPtr); } - else if (typeof(T) == typeof(Double)) + else if (typeof(T) == typeof(double)) { - Double* dataPtr = stackalloc Double[Count]; + double* dataPtr = stackalloc double[Count]; for (int g = 0; g < Count; g++) { - dataPtr[g] = unchecked((Double)Math.Sqrt((Double)(object)value[g])); + dataPtr[g] = unchecked((double)Math.Sqrt((double)(object)value[g])); } return new Vector(dataPtr); } @@ -4421,110 +4421,110 @@ internal static unsafe Vector SquareRoot(Vector value) } else { - if (typeof(T) == typeof(Byte)) - { - value.register.byte_0 = (Byte)Math.Sqrt(value.register.byte_0); - value.register.byte_1 = (Byte)Math.Sqrt(value.register.byte_1); - value.register.byte_2 = (Byte)Math.Sqrt(value.register.byte_2); - value.register.byte_3 = (Byte)Math.Sqrt(value.register.byte_3); - value.register.byte_4 = (Byte)Math.Sqrt(value.register.byte_4); - value.register.byte_5 = (Byte)Math.Sqrt(value.register.byte_5); - value.register.byte_6 = (Byte)Math.Sqrt(value.register.byte_6); - value.register.byte_7 = (Byte)Math.Sqrt(value.register.byte_7); - value.register.byte_8 = (Byte)Math.Sqrt(value.register.byte_8); - value.register.byte_9 = (Byte)Math.Sqrt(value.register.byte_9); - value.register.byte_10 = (Byte)Math.Sqrt(value.register.byte_10); - value.register.byte_11 = (Byte)Math.Sqrt(value.register.byte_11); - value.register.byte_12 = (Byte)Math.Sqrt(value.register.byte_12); - value.register.byte_13 = (Byte)Math.Sqrt(value.register.byte_13); - value.register.byte_14 = (Byte)Math.Sqrt(value.register.byte_14); - value.register.byte_15 = (Byte)Math.Sqrt(value.register.byte_15); + if (typeof(T) == typeof(byte)) + { + value.register.byte_0 = (byte)Math.Sqrt(value.register.byte_0); + value.register.byte_1 = (byte)Math.Sqrt(value.register.byte_1); + value.register.byte_2 = (byte)Math.Sqrt(value.register.byte_2); + value.register.byte_3 = (byte)Math.Sqrt(value.register.byte_3); + value.register.byte_4 = (byte)Math.Sqrt(value.register.byte_4); + value.register.byte_5 = (byte)Math.Sqrt(value.register.byte_5); + value.register.byte_6 = (byte)Math.Sqrt(value.register.byte_6); + value.register.byte_7 = (byte)Math.Sqrt(value.register.byte_7); + value.register.byte_8 = (byte)Math.Sqrt(value.register.byte_8); + value.register.byte_9 = (byte)Math.Sqrt(value.register.byte_9); + value.register.byte_10 = (byte)Math.Sqrt(value.register.byte_10); + value.register.byte_11 = (byte)Math.Sqrt(value.register.byte_11); + value.register.byte_12 = (byte)Math.Sqrt(value.register.byte_12); + value.register.byte_13 = (byte)Math.Sqrt(value.register.byte_13); + value.register.byte_14 = (byte)Math.Sqrt(value.register.byte_14); + value.register.byte_15 = (byte)Math.Sqrt(value.register.byte_15); return value; } - else if (typeof(T) == typeof(SByte)) - { - value.register.sbyte_0 = (SByte)Math.Sqrt(value.register.sbyte_0); - value.register.sbyte_1 = (SByte)Math.Sqrt(value.register.sbyte_1); - value.register.sbyte_2 = (SByte)Math.Sqrt(value.register.sbyte_2); - value.register.sbyte_3 = (SByte)Math.Sqrt(value.register.sbyte_3); - value.register.sbyte_4 = (SByte)Math.Sqrt(value.register.sbyte_4); - value.register.sbyte_5 = (SByte)Math.Sqrt(value.register.sbyte_5); - value.register.sbyte_6 = (SByte)Math.Sqrt(value.register.sbyte_6); - value.register.sbyte_7 = (SByte)Math.Sqrt(value.register.sbyte_7); - value.register.sbyte_8 = (SByte)Math.Sqrt(value.register.sbyte_8); - value.register.sbyte_9 = (SByte)Math.Sqrt(value.register.sbyte_9); - value.register.sbyte_10 = (SByte)Math.Sqrt(value.register.sbyte_10); - value.register.sbyte_11 = (SByte)Math.Sqrt(value.register.sbyte_11); - value.register.sbyte_12 = (SByte)Math.Sqrt(value.register.sbyte_12); - value.register.sbyte_13 = (SByte)Math.Sqrt(value.register.sbyte_13); - value.register.sbyte_14 = (SByte)Math.Sqrt(value.register.sbyte_14); - value.register.sbyte_15 = (SByte)Math.Sqrt(value.register.sbyte_15); + else if (typeof(T) == typeof(sbyte)) + { + value.register.sbyte_0 = (sbyte)Math.Sqrt(value.register.sbyte_0); + value.register.sbyte_1 = (sbyte)Math.Sqrt(value.register.sbyte_1); + value.register.sbyte_2 = (sbyte)Math.Sqrt(value.register.sbyte_2); + value.register.sbyte_3 = (sbyte)Math.Sqrt(value.register.sbyte_3); + value.register.sbyte_4 = (sbyte)Math.Sqrt(value.register.sbyte_4); + value.register.sbyte_5 = (sbyte)Math.Sqrt(value.register.sbyte_5); + value.register.sbyte_6 = (sbyte)Math.Sqrt(value.register.sbyte_6); + value.register.sbyte_7 = (sbyte)Math.Sqrt(value.register.sbyte_7); + value.register.sbyte_8 = (sbyte)Math.Sqrt(value.register.sbyte_8); + value.register.sbyte_9 = (sbyte)Math.Sqrt(value.register.sbyte_9); + value.register.sbyte_10 = (sbyte)Math.Sqrt(value.register.sbyte_10); + value.register.sbyte_11 = (sbyte)Math.Sqrt(value.register.sbyte_11); + value.register.sbyte_12 = (sbyte)Math.Sqrt(value.register.sbyte_12); + value.register.sbyte_13 = (sbyte)Math.Sqrt(value.register.sbyte_13); + value.register.sbyte_14 = (sbyte)Math.Sqrt(value.register.sbyte_14); + value.register.sbyte_15 = (sbyte)Math.Sqrt(value.register.sbyte_15); return value; } - else if (typeof(T) == typeof(UInt16)) + else if (typeof(T) == typeof(ushort)) { - value.register.uint16_0 = (UInt16)Math.Sqrt(value.register.uint16_0); - value.register.uint16_1 = (UInt16)Math.Sqrt(value.register.uint16_1); - value.register.uint16_2 = (UInt16)Math.Sqrt(value.register.uint16_2); - value.register.uint16_3 = (UInt16)Math.Sqrt(value.register.uint16_3); - value.register.uint16_4 = (UInt16)Math.Sqrt(value.register.uint16_4); - value.register.uint16_5 = (UInt16)Math.Sqrt(value.register.uint16_5); - value.register.uint16_6 = (UInt16)Math.Sqrt(value.register.uint16_6); - value.register.uint16_7 = (UInt16)Math.Sqrt(value.register.uint16_7); + value.register.uint16_0 = (ushort)Math.Sqrt(value.register.uint16_0); + value.register.uint16_1 = (ushort)Math.Sqrt(value.register.uint16_1); + value.register.uint16_2 = (ushort)Math.Sqrt(value.register.uint16_2); + value.register.uint16_3 = (ushort)Math.Sqrt(value.register.uint16_3); + value.register.uint16_4 = (ushort)Math.Sqrt(value.register.uint16_4); + value.register.uint16_5 = (ushort)Math.Sqrt(value.register.uint16_5); + value.register.uint16_6 = (ushort)Math.Sqrt(value.register.uint16_6); + value.register.uint16_7 = (ushort)Math.Sqrt(value.register.uint16_7); return value; } - else if (typeof(T) == typeof(Int16)) + else if (typeof(T) == typeof(short)) { - value.register.int16_0 = (Int16)Math.Sqrt(value.register.int16_0); - value.register.int16_1 = (Int16)Math.Sqrt(value.register.int16_1); - value.register.int16_2 = (Int16)Math.Sqrt(value.register.int16_2); - value.register.int16_3 = (Int16)Math.Sqrt(value.register.int16_3); - value.register.int16_4 = (Int16)Math.Sqrt(value.register.int16_4); - value.register.int16_5 = (Int16)Math.Sqrt(value.register.int16_5); - value.register.int16_6 = (Int16)Math.Sqrt(value.register.int16_6); - value.register.int16_7 = (Int16)Math.Sqrt(value.register.int16_7); + value.register.int16_0 = (short)Math.Sqrt(value.register.int16_0); + value.register.int16_1 = (short)Math.Sqrt(value.register.int16_1); + value.register.int16_2 = (short)Math.Sqrt(value.register.int16_2); + value.register.int16_3 = (short)Math.Sqrt(value.register.int16_3); + value.register.int16_4 = (short)Math.Sqrt(value.register.int16_4); + value.register.int16_5 = (short)Math.Sqrt(value.register.int16_5); + value.register.int16_6 = (short)Math.Sqrt(value.register.int16_6); + value.register.int16_7 = (short)Math.Sqrt(value.register.int16_7); return value; } - else if (typeof(T) == typeof(UInt32)) + else if (typeof(T) == typeof(uint)) { - value.register.uint32_0 = (UInt32)Math.Sqrt(value.register.uint32_0); - value.register.uint32_1 = (UInt32)Math.Sqrt(value.register.uint32_1); - value.register.uint32_2 = (UInt32)Math.Sqrt(value.register.uint32_2); - value.register.uint32_3 = (UInt32)Math.Sqrt(value.register.uint32_3); + value.register.uint32_0 = (uint)Math.Sqrt(value.register.uint32_0); + value.register.uint32_1 = (uint)Math.Sqrt(value.register.uint32_1); + value.register.uint32_2 = (uint)Math.Sqrt(value.register.uint32_2); + value.register.uint32_3 = (uint)Math.Sqrt(value.register.uint32_3); return value; } - else if (typeof(T) == typeof(Int32)) + else if (typeof(T) == typeof(int)) { - value.register.int32_0 = (Int32)Math.Sqrt(value.register.int32_0); - value.register.int32_1 = (Int32)Math.Sqrt(value.register.int32_1); - value.register.int32_2 = (Int32)Math.Sqrt(value.register.int32_2); - value.register.int32_3 = (Int32)Math.Sqrt(value.register.int32_3); + value.register.int32_0 = (int)Math.Sqrt(value.register.int32_0); + value.register.int32_1 = (int)Math.Sqrt(value.register.int32_1); + value.register.int32_2 = (int)Math.Sqrt(value.register.int32_2); + value.register.int32_3 = (int)Math.Sqrt(value.register.int32_3); return value; } - else if (typeof(T) == typeof(UInt64)) + else if (typeof(T) == typeof(ulong)) { - value.register.uint64_0 = (UInt64)Math.Sqrt(value.register.uint64_0); - value.register.uint64_1 = (UInt64)Math.Sqrt(value.register.uint64_1); + value.register.uint64_0 = (ulong)Math.Sqrt(value.register.uint64_0); + value.register.uint64_1 = (ulong)Math.Sqrt(value.register.uint64_1); return value; } - else if (typeof(T) == typeof(Int64)) + else if (typeof(T) == typeof(long)) { - value.register.int64_0 = (Int64)Math.Sqrt(value.register.int64_0); - value.register.int64_1 = (Int64)Math.Sqrt(value.register.int64_1); + value.register.int64_0 = (long)Math.Sqrt(value.register.int64_0); + value.register.int64_1 = (long)Math.Sqrt(value.register.int64_1); return value; } - else if (typeof(T) == typeof(Single)) + else if (typeof(T) == typeof(float)) { - value.register.single_0 = (Single)Math.Sqrt(value.register.single_0); - value.register.single_1 = (Single)Math.Sqrt(value.register.single_1); - value.register.single_2 = (Single)Math.Sqrt(value.register.single_2); - value.register.single_3 = (Single)Math.Sqrt(value.register.single_3); + value.register.single_0 = (float)Math.Sqrt(value.register.single_0); + value.register.single_1 = (float)Math.Sqrt(value.register.single_1); + value.register.single_2 = (float)Math.Sqrt(value.register.single_2); + value.register.single_3 = (float)Math.Sqrt(value.register.single_3); return value; } - else if (typeof(T) == typeof(Double)) + else if (typeof(T) == typeof(double)) { - value.register.double_0 = (Double)Math.Sqrt(value.register.double_0); - value.register.double_1 = (Double)Math.Sqrt(value.register.double_1); + value.register.double_0 = (double)Math.Sqrt(value.register.double_0); + value.register.double_1 = (double)Math.Sqrt(value.register.double_1); return value; } else @@ -4539,45 +4539,45 @@ internal static unsafe Vector SquareRoot(Vector value) [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] private static bool ScalarEquals(T left, T right) { - if (typeof(T) == typeof(Byte)) + if (typeof(T) == typeof(byte)) { - return (Byte)(object)left == (Byte)(object)right; + return (byte)(object)left == (byte)(object)right; } - else if (typeof(T) == typeof(SByte)) + else if (typeof(T) == typeof(sbyte)) { - return (SByte)(object)left == (SByte)(object)right; + return (sbyte)(object)left == (sbyte)(object)right; } - else if (typeof(T) == typeof(UInt16)) + else if (typeof(T) == typeof(ushort)) { - return (UInt16)(object)left == (UInt16)(object)right; + return (ushort)(object)left == (ushort)(object)right; } - else if (typeof(T) == typeof(Int16)) + else if (typeof(T) == typeof(short)) { - return (Int16)(object)left == (Int16)(object)right; + return (short)(object)left == (short)(object)right; } - else if (typeof(T) == typeof(UInt32)) + else if (typeof(T) == typeof(uint)) { - return (UInt32)(object)left == (UInt32)(object)right; + return (uint)(object)left == (uint)(object)right; } - else if (typeof(T) == typeof(Int32)) + else if (typeof(T) == typeof(int)) { - return (Int32)(object)left == (Int32)(object)right; + return (int)(object)left == (int)(object)right; } - else if (typeof(T) == typeof(UInt64)) + else if (typeof(T) == typeof(ulong)) { - return (UInt64)(object)left == (UInt64)(object)right; + return (ulong)(object)left == (ulong)(object)right; } - else if (typeof(T) == typeof(Int64)) + else if (typeof(T) == typeof(long)) { - return (Int64)(object)left == (Int64)(object)right; + return (long)(object)left == (long)(object)right; } - else if (typeof(T) == typeof(Single)) + else if (typeof(T) == typeof(float)) { - return (Single)(object)left == (Single)(object)right; + return (float)(object)left == (float)(object)right; } - else if (typeof(T) == typeof(Double)) + else if (typeof(T) == typeof(double)) { - return (Double)(object)left == (Double)(object)right; + return (double)(object)left == (double)(object)right; } else { @@ -4588,45 +4588,45 @@ private static bool ScalarEquals(T left, T right) [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] private static bool ScalarLessThan(T left, T right) { - if (typeof(T) == typeof(Byte)) + if (typeof(T) == typeof(byte)) { - return (Byte)(object)left < (Byte)(object)right; + return (byte)(object)left < (byte)(object)right; } - else if (typeof(T) == typeof(SByte)) + else if (typeof(T) == typeof(sbyte)) { - return (SByte)(object)left < (SByte)(object)right; + return (sbyte)(object)left < (sbyte)(object)right; } - else if (typeof(T) == typeof(UInt16)) + else if (typeof(T) == typeof(ushort)) { - return (UInt16)(object)left < (UInt16)(object)right; + return (ushort)(object)left < (ushort)(object)right; } - else if (typeof(T) == typeof(Int16)) + else if (typeof(T) == typeof(short)) { - return (Int16)(object)left < (Int16)(object)right; + return (short)(object)left < (short)(object)right; } - else if (typeof(T) == typeof(UInt32)) + else if (typeof(T) == typeof(uint)) { - return (UInt32)(object)left < (UInt32)(object)right; + return (uint)(object)left < (uint)(object)right; } - else if (typeof(T) == typeof(Int32)) + else if (typeof(T) == typeof(int)) { - return (Int32)(object)left < (Int32)(object)right; + return (int)(object)left < (int)(object)right; } - else if (typeof(T) == typeof(UInt64)) + else if (typeof(T) == typeof(ulong)) { - return (UInt64)(object)left < (UInt64)(object)right; + return (ulong)(object)left < (ulong)(object)right; } - else if (typeof(T) == typeof(Int64)) + else if (typeof(T) == typeof(long)) { - return (Int64)(object)left < (Int64)(object)right; + return (long)(object)left < (long)(object)right; } - else if (typeof(T) == typeof(Single)) + else if (typeof(T) == typeof(float)) { - return (Single)(object)left < (Single)(object)right; + return (float)(object)left < (float)(object)right; } - else if (typeof(T) == typeof(Double)) + else if (typeof(T) == typeof(double)) { - return (Double)(object)left < (Double)(object)right; + return (double)(object)left < (double)(object)right; } else { @@ -4637,45 +4637,45 @@ private static bool ScalarLessThan(T left, T right) [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] private static bool ScalarGreaterThan(T left, T right) { - if (typeof(T) == typeof(Byte)) + if (typeof(T) == typeof(byte)) { - return (Byte)(object)left > (Byte)(object)right; + return (byte)(object)left > (byte)(object)right; } - else if (typeof(T) == typeof(SByte)) + else if (typeof(T) == typeof(sbyte)) { - return (SByte)(object)left > (SByte)(object)right; + return (sbyte)(object)left > (sbyte)(object)right; } - else if (typeof(T) == typeof(UInt16)) + else if (typeof(T) == typeof(ushort)) { - return (UInt16)(object)left > (UInt16)(object)right; + return (ushort)(object)left > (ushort)(object)right; } - else if (typeof(T) == typeof(Int16)) + else if (typeof(T) == typeof(short)) { - return (Int16)(object)left > (Int16)(object)right; + return (short)(object)left > (short)(object)right; } - else if (typeof(T) == typeof(UInt32)) + else if (typeof(T) == typeof(uint)) { - return (UInt32)(object)left > (UInt32)(object)right; + return (uint)(object)left > (uint)(object)right; } - else if (typeof(T) == typeof(Int32)) + else if (typeof(T) == typeof(int)) { - return (Int32)(object)left > (Int32)(object)right; + return (int)(object)left > (int)(object)right; } - else if (typeof(T) == typeof(UInt64)) + else if (typeof(T) == typeof(ulong)) { - return (UInt64)(object)left > (UInt64)(object)right; + return (ulong)(object)left > (ulong)(object)right; } - else if (typeof(T) == typeof(Int64)) + else if (typeof(T) == typeof(long)) { - return (Int64)(object)left > (Int64)(object)right; + return (long)(object)left > (long)(object)right; } - else if (typeof(T) == typeof(Single)) + else if (typeof(T) == typeof(float)) { - return (Single)(object)left > (Single)(object)right; + return (float)(object)left > (float)(object)right; } - else if (typeof(T) == typeof(Double)) + else if (typeof(T) == typeof(double)) { - return (Double)(object)left > (Double)(object)right; + return (double)(object)left > (double)(object)right; } else { @@ -4686,45 +4686,45 @@ private static bool ScalarGreaterThan(T left, T right) [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] private static T ScalarAdd(T left, T right) { - if (typeof(T) == typeof(Byte)) + if (typeof(T) == typeof(byte)) { - return (T)(object)unchecked((Byte)((Byte)(object)left + (Byte)(object)right)); + return (T)(object)unchecked((byte)((byte)(object)left + (byte)(object)right)); } - else if (typeof(T) == typeof(SByte)) + else if (typeof(T) == typeof(sbyte)) { - return (T)(object)unchecked((SByte)((SByte)(object)left + (SByte)(object)right)); + return (T)(object)unchecked((sbyte)((sbyte)(object)left + (sbyte)(object)right)); } - else if (typeof(T) == typeof(UInt16)) + else if (typeof(T) == typeof(ushort)) { - return (T)(object)unchecked((UInt16)((UInt16)(object)left + (UInt16)(object)right)); + return (T)(object)unchecked((ushort)((ushort)(object)left + (ushort)(object)right)); } - else if (typeof(T) == typeof(Int16)) + else if (typeof(T) == typeof(short)) { - return (T)(object)unchecked((Int16)((Int16)(object)left + (Int16)(object)right)); + return (T)(object)unchecked((short)((short)(object)left + (short)(object)right)); } - else if (typeof(T) == typeof(UInt32)) + else if (typeof(T) == typeof(uint)) { - return (T)(object)unchecked((UInt32)((UInt32)(object)left + (UInt32)(object)right)); + return (T)(object)unchecked((uint)((uint)(object)left + (uint)(object)right)); } - else if (typeof(T) == typeof(Int32)) + else if (typeof(T) == typeof(int)) { - return (T)(object)unchecked((Int32)((Int32)(object)left + (Int32)(object)right)); + return (T)(object)unchecked((int)((int)(object)left + (int)(object)right)); } - else if (typeof(T) == typeof(UInt64)) + else if (typeof(T) == typeof(ulong)) { - return (T)(object)unchecked((UInt64)((UInt64)(object)left + (UInt64)(object)right)); + return (T)(object)unchecked((ulong)((ulong)(object)left + (ulong)(object)right)); } - else if (typeof(T) == typeof(Int64)) + else if (typeof(T) == typeof(long)) { - return (T)(object)unchecked((Int64)((Int64)(object)left + (Int64)(object)right)); + return (T)(object)unchecked((long)((long)(object)left + (long)(object)right)); } - else if (typeof(T) == typeof(Single)) + else if (typeof(T) == typeof(float)) { - return (T)(object)unchecked((Single)((Single)(object)left + (Single)(object)right)); + return (T)(object)unchecked((float)((float)(object)left + (float)(object)right)); } - else if (typeof(T) == typeof(Double)) + else if (typeof(T) == typeof(double)) { - return (T)(object)unchecked((Double)((Double)(object)left + (Double)(object)right)); + return (T)(object)unchecked((double)((double)(object)left + (double)(object)right)); } else { @@ -4735,45 +4735,45 @@ private static T ScalarAdd(T left, T right) [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] private static T ScalarSubtract(T left, T right) { - if (typeof(T) == typeof(Byte)) + if (typeof(T) == typeof(byte)) { - return (T)(object)(Byte)((Byte)(object)left - (Byte)(object)right); + return (T)(object)(byte)((byte)(object)left - (byte)(object)right); } - else if (typeof(T) == typeof(SByte)) + else if (typeof(T) == typeof(sbyte)) { - return (T)(object)(SByte)((SByte)(object)left - (SByte)(object)right); + return (T)(object)(sbyte)((sbyte)(object)left - (sbyte)(object)right); } - else if (typeof(T) == typeof(UInt16)) + else if (typeof(T) == typeof(ushort)) { - return (T)(object)(UInt16)((UInt16)(object)left - (UInt16)(object)right); + return (T)(object)(ushort)((ushort)(object)left - (ushort)(object)right); } - else if (typeof(T) == typeof(Int16)) + else if (typeof(T) == typeof(short)) { - return (T)(object)(Int16)((Int16)(object)left - (Int16)(object)right); + return (T)(object)(short)((short)(object)left - (short)(object)right); } - else if (typeof(T) == typeof(UInt32)) + else if (typeof(T) == typeof(uint)) { - return (T)(object)(UInt32)((UInt32)(object)left - (UInt32)(object)right); + return (T)(object)(uint)((uint)(object)left - (uint)(object)right); } - else if (typeof(T) == typeof(Int32)) + else if (typeof(T) == typeof(int)) { - return (T)(object)(Int32)((Int32)(object)left - (Int32)(object)right); + return (T)(object)(int)((int)(object)left - (int)(object)right); } - else if (typeof(T) == typeof(UInt64)) + else if (typeof(T) == typeof(ulong)) { - return (T)(object)(UInt64)((UInt64)(object)left - (UInt64)(object)right); + return (T)(object)(ulong)((ulong)(object)left - (ulong)(object)right); } - else if (typeof(T) == typeof(Int64)) + else if (typeof(T) == typeof(long)) { - return (T)(object)(Int64)((Int64)(object)left - (Int64)(object)right); + return (T)(object)(long)((long)(object)left - (long)(object)right); } - else if (typeof(T) == typeof(Single)) + else if (typeof(T) == typeof(float)) { - return (T)(object)(Single)((Single)(object)left - (Single)(object)right); + return (T)(object)(float)((float)(object)left - (float)(object)right); } - else if (typeof(T) == typeof(Double)) + else if (typeof(T) == typeof(double)) { - return (T)(object)(Double)((Double)(object)left - (Double)(object)right); + return (T)(object)(double)((double)(object)left - (double)(object)right); } else { @@ -4784,45 +4784,45 @@ private static T ScalarSubtract(T left, T right) [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] private static T ScalarMultiply(T left, T right) { - if (typeof(T) == typeof(Byte)) + if (typeof(T) == typeof(byte)) { - return (T)(object)unchecked((Byte)((Byte)(object)left * (Byte)(object)right)); + return (T)(object)unchecked((byte)((byte)(object)left * (byte)(object)right)); } - else if (typeof(T) == typeof(SByte)) + else if (typeof(T) == typeof(sbyte)) { - return (T)(object)unchecked((SByte)((SByte)(object)left * (SByte)(object)right)); + return (T)(object)unchecked((sbyte)((sbyte)(object)left * (sbyte)(object)right)); } - else if (typeof(T) == typeof(UInt16)) + else if (typeof(T) == typeof(ushort)) { - return (T)(object)unchecked((UInt16)((UInt16)(object)left * (UInt16)(object)right)); + return (T)(object)unchecked((ushort)((ushort)(object)left * (ushort)(object)right)); } - else if (typeof(T) == typeof(Int16)) + else if (typeof(T) == typeof(short)) { - return (T)(object)unchecked((Int16)((Int16)(object)left * (Int16)(object)right)); + return (T)(object)unchecked((short)((short)(object)left * (short)(object)right)); } - else if (typeof(T) == typeof(UInt32)) + else if (typeof(T) == typeof(uint)) { - return (T)(object)unchecked((UInt32)((UInt32)(object)left * (UInt32)(object)right)); + return (T)(object)unchecked((uint)((uint)(object)left * (uint)(object)right)); } - else if (typeof(T) == typeof(Int32)) + else if (typeof(T) == typeof(int)) { - return (T)(object)unchecked((Int32)((Int32)(object)left * (Int32)(object)right)); + return (T)(object)unchecked((int)((int)(object)left * (int)(object)right)); } - else if (typeof(T) == typeof(UInt64)) + else if (typeof(T) == typeof(ulong)) { - return (T)(object)unchecked((UInt64)((UInt64)(object)left * (UInt64)(object)right)); + return (T)(object)unchecked((ulong)((ulong)(object)left * (ulong)(object)right)); } - else if (typeof(T) == typeof(Int64)) + else if (typeof(T) == typeof(long)) { - return (T)(object)unchecked((Int64)((Int64)(object)left * (Int64)(object)right)); + return (T)(object)unchecked((long)((long)(object)left * (long)(object)right)); } - else if (typeof(T) == typeof(Single)) + else if (typeof(T) == typeof(float)) { - return (T)(object)unchecked((Single)((Single)(object)left * (Single)(object)right)); + return (T)(object)unchecked((float)((float)(object)left * (float)(object)right)); } - else if (typeof(T) == typeof(Double)) + else if (typeof(T) == typeof(double)) { - return (T)(object)unchecked((Double)((Double)(object)left * (Double)(object)right)); + return (T)(object)unchecked((double)((double)(object)left * (double)(object)right)); } else { @@ -4833,45 +4833,45 @@ private static T ScalarMultiply(T left, T right) [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] private static T ScalarDivide(T left, T right) { - if (typeof(T) == typeof(Byte)) + if (typeof(T) == typeof(byte)) { - return (T)(object)(Byte)((Byte)(object)left / (Byte)(object)right); + return (T)(object)(byte)((byte)(object)left / (byte)(object)right); } - else if (typeof(T) == typeof(SByte)) + else if (typeof(T) == typeof(sbyte)) { - return (T)(object)(SByte)((SByte)(object)left / (SByte)(object)right); + return (T)(object)(sbyte)((sbyte)(object)left / (sbyte)(object)right); } - else if (typeof(T) == typeof(UInt16)) + else if (typeof(T) == typeof(ushort)) { - return (T)(object)(UInt16)((UInt16)(object)left / (UInt16)(object)right); + return (T)(object)(ushort)((ushort)(object)left / (ushort)(object)right); } - else if (typeof(T) == typeof(Int16)) + else if (typeof(T) == typeof(short)) { - return (T)(object)(Int16)((Int16)(object)left / (Int16)(object)right); + return (T)(object)(short)((short)(object)left / (short)(object)right); } - else if (typeof(T) == typeof(UInt32)) + else if (typeof(T) == typeof(uint)) { - return (T)(object)(UInt32)((UInt32)(object)left / (UInt32)(object)right); + return (T)(object)(uint)((uint)(object)left / (uint)(object)right); } - else if (typeof(T) == typeof(Int32)) + else if (typeof(T) == typeof(int)) { - return (T)(object)(Int32)((Int32)(object)left / (Int32)(object)right); + return (T)(object)(int)((int)(object)left / (int)(object)right); } - else if (typeof(T) == typeof(UInt64)) + else if (typeof(T) == typeof(ulong)) { - return (T)(object)(UInt64)((UInt64)(object)left / (UInt64)(object)right); + return (T)(object)(ulong)((ulong)(object)left / (ulong)(object)right); } - else if (typeof(T) == typeof(Int64)) + else if (typeof(T) == typeof(long)) { - return (T)(object)(Int64)((Int64)(object)left / (Int64)(object)right); + return (T)(object)(long)((long)(object)left / (long)(object)right); } - else if (typeof(T) == typeof(Single)) + else if (typeof(T) == typeof(float)) { - return (T)(object)(Single)((Single)(object)left / (Single)(object)right); + return (T)(object)(float)((float)(object)left / (float)(object)right); } - else if (typeof(T) == typeof(Double)) + else if (typeof(T) == typeof(double)) { - return (T)(object)(Double)((Double)(object)left / (Double)(object)right); + return (T)(object)(double)((double)(object)left / (double)(object)right); } else { @@ -4882,54 +4882,54 @@ private static T ScalarDivide(T left, T right) [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] private static T GetOneValue() { - if (typeof(T) == typeof(Byte)) + if (typeof(T) == typeof(byte)) { - Byte value = 1; + byte value = 1; return (T)(object)value; } - else if (typeof(T) == typeof(SByte)) + else if (typeof(T) == typeof(sbyte)) { - SByte value = 1; + sbyte value = 1; return (T)(object)value; } - else if (typeof(T) == typeof(UInt16)) + else if (typeof(T) == typeof(ushort)) { - UInt16 value = 1; + ushort value = 1; return (T)(object)value; } - else if (typeof(T) == typeof(Int16)) + else if (typeof(T) == typeof(short)) { - Int16 value = 1; + short value = 1; return (T)(object)value; } - else if (typeof(T) == typeof(UInt32)) + else if (typeof(T) == typeof(uint)) { - UInt32 value = 1; + uint value = 1; return (T)(object)value; } - else if (typeof(T) == typeof(Int32)) + else if (typeof(T) == typeof(int)) { - Int32 value = 1; + int value = 1; return (T)(object)value; } - else if (typeof(T) == typeof(UInt64)) + else if (typeof(T) == typeof(ulong)) { - UInt64 value = 1; + ulong value = 1; return (T)(object)value; } - else if (typeof(T) == typeof(Int64)) + else if (typeof(T) == typeof(long)) { - Int64 value = 1; + long value = 1; return (T)(object)value; } - else if (typeof(T) == typeof(Single)) + else if (typeof(T) == typeof(float)) { - Single value = 1; + float value = 1; return (T)(object)value; } - else if (typeof(T) == typeof(Double)) + else if (typeof(T) == typeof(double)) { - Double value = 1; + double value = 1; return (T)(object)value; } else @@ -4941,43 +4941,43 @@ private static T GetOneValue() [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] private static T GetAllBitsSetValue() { - if (typeof(T) == typeof(Byte)) + if (typeof(T) == typeof(byte)) { return (T)(object)ConstantHelper.GetByteWithAllBitsSet(); } - else if (typeof(T) == typeof(SByte)) + else if (typeof(T) == typeof(sbyte)) { return (T)(object)ConstantHelper.GetSByteWithAllBitsSet(); } - else if (typeof(T) == typeof(UInt16)) + else if (typeof(T) == typeof(ushort)) { return (T)(object)ConstantHelper.GetUInt16WithAllBitsSet(); } - else if (typeof(T) == typeof(Int16)) + else if (typeof(T) == typeof(short)) { return (T)(object)ConstantHelper.GetInt16WithAllBitsSet(); } - else if (typeof(T) == typeof(UInt32)) + else if (typeof(T) == typeof(uint)) { return (T)(object)ConstantHelper.GetUInt32WithAllBitsSet(); } - else if (typeof(T) == typeof(Int32)) + else if (typeof(T) == typeof(int)) { return (T)(object)ConstantHelper.GetInt32WithAllBitsSet(); } - else if (typeof(T) == typeof(UInt64)) + else if (typeof(T) == typeof(ulong)) { return (T)(object)ConstantHelper.GetUInt64WithAllBitsSet(); } - else if (typeof(T) == typeof(Int64)) + else if (typeof(T) == typeof(long)) { return (T)(object)ConstantHelper.GetInt64WithAllBitsSet(); } - else if (typeof(T) == typeof(Single)) + else if (typeof(T) == typeof(float)) { return (T)(object)ConstantHelper.GetSingleWithAllBitsSet(); } - else if (typeof(T) == typeof(Double)) + else if (typeof(T) == typeof(double)) { return (T)(object)ConstantHelper.GetDoubleWithAllBitsSet(); } @@ -5001,22 +5001,22 @@ public static partial class Vector /// [CLSCompliant(false)] [Intrinsic] - public static unsafe void Widen(Vector source, out Vector low, out Vector high) + public static unsafe void Widen(Vector source, out Vector low, out Vector high) { - int elements = Vector.Count; - UInt16* lowPtr = stackalloc UInt16[elements / 2]; + int elements = Vector.Count; + ushort* lowPtr = stackalloc ushort[elements / 2]; for (int i = 0; i < elements / 2; i++) { - lowPtr[i] = (UInt16)source[i]; + lowPtr[i] = (ushort)source[i]; } - UInt16* highPtr = stackalloc UInt16[elements / 2]; + ushort* highPtr = stackalloc ushort[elements / 2]; for (int i = 0; i < elements / 2; i++) { - highPtr[i] = (UInt16)source[i + (elements / 2)]; + highPtr[i] = (ushort)source[i + (elements / 2)]; } - low = new Vector(lowPtr); - high = new Vector(highPtr); + low = new Vector(lowPtr); + high = new Vector(highPtr); } /// @@ -5027,22 +5027,22 @@ public static unsafe void Widen(Vector source, out Vector low, out /// [CLSCompliant(false)] [Intrinsic] - public static unsafe void Widen(Vector source, out Vector low, out Vector high) + public static unsafe void Widen(Vector source, out Vector low, out Vector high) { - int elements = Vector.Count; - UInt32* lowPtr = stackalloc UInt32[elements / 2]; + int elements = Vector.Count; + uint* lowPtr = stackalloc uint[elements / 2]; for (int i = 0; i < elements / 2; i++) { - lowPtr[i] = (UInt32)source[i]; + lowPtr[i] = (uint)source[i]; } - UInt32* highPtr = stackalloc UInt32[elements / 2]; + uint* highPtr = stackalloc uint[elements / 2]; for (int i = 0; i < elements / 2; i++) { - highPtr[i] = (UInt32)source[i + (elements / 2)]; + highPtr[i] = (uint)source[i + (elements / 2)]; } - low = new Vector(lowPtr); - high = new Vector(highPtr); + low = new Vector(lowPtr); + high = new Vector(highPtr); } /// @@ -5053,22 +5053,22 @@ public static unsafe void Widen(Vector source, out Vector low, o /// [CLSCompliant(false)] [Intrinsic] - public static unsafe void Widen(Vector source, out Vector low, out Vector high) + public static unsafe void Widen(Vector source, out Vector low, out Vector high) { - int elements = Vector.Count; - UInt64* lowPtr = stackalloc UInt64[elements / 2]; + int elements = Vector.Count; + ulong* lowPtr = stackalloc ulong[elements / 2]; for (int i = 0; i < elements / 2; i++) { - lowPtr[i] = (UInt64)source[i]; + lowPtr[i] = (ulong)source[i]; } - UInt64* highPtr = stackalloc UInt64[elements / 2]; + ulong* highPtr = stackalloc ulong[elements / 2]; for (int i = 0; i < elements / 2; i++) { - highPtr[i] = (UInt64)source[i + (elements / 2)]; + highPtr[i] = (ulong)source[i + (elements / 2)]; } - low = new Vector(lowPtr); - high = new Vector(highPtr); + low = new Vector(lowPtr); + high = new Vector(highPtr); } /// @@ -5079,22 +5079,22 @@ public static unsafe void Widen(Vector source, out Vector low, o /// [CLSCompliant(false)] [Intrinsic] - public static unsafe void Widen(Vector source, out Vector low, out Vector high) + public static unsafe void Widen(Vector source, out Vector low, out Vector high) { - int elements = Vector.Count; - Int16* lowPtr = stackalloc Int16[elements / 2]; + int elements = Vector.Count; + short* lowPtr = stackalloc short[elements / 2]; for (int i = 0; i < elements / 2; i++) { - lowPtr[i] = (Int16)source[i]; + lowPtr[i] = (short)source[i]; } - Int16* highPtr = stackalloc Int16[elements / 2]; + short* highPtr = stackalloc short[elements / 2]; for (int i = 0; i < elements / 2; i++) { - highPtr[i] = (Int16)source[i + (elements / 2)]; + highPtr[i] = (short)source[i + (elements / 2)]; } - low = new Vector(lowPtr); - high = new Vector(highPtr); + low = new Vector(lowPtr); + high = new Vector(highPtr); } /// @@ -5104,22 +5104,22 @@ public static unsafe void Widen(Vector source, out Vector low, out /// The second output vector, whose elements will contain the widened elements from higher indices in the source vector. /// [Intrinsic] - public static unsafe void Widen(Vector source, out Vector low, out Vector high) + public static unsafe void Widen(Vector source, out Vector low, out Vector high) { - int elements = Vector.Count; - Int32* lowPtr = stackalloc Int32[elements / 2]; + int elements = Vector.Count; + int* lowPtr = stackalloc int[elements / 2]; for (int i = 0; i < elements / 2; i++) { - lowPtr[i] = (Int32)source[i]; + lowPtr[i] = (int)source[i]; } - Int32* highPtr = stackalloc Int32[elements / 2]; + int* highPtr = stackalloc int[elements / 2]; for (int i = 0; i < elements / 2; i++) { - highPtr[i] = (Int32)source[i + (elements / 2)]; + highPtr[i] = (int)source[i + (elements / 2)]; } - low = new Vector(lowPtr); - high = new Vector(highPtr); + low = new Vector(lowPtr); + high = new Vector(highPtr); } /// @@ -5129,22 +5129,22 @@ public static unsafe void Widen(Vector source, out Vector low, out /// The second output vector, whose elements will contain the widened elements from higher indices in the source vector. /// [Intrinsic] - public static unsafe void Widen(Vector source, out Vector low, out Vector high) + public static unsafe void Widen(Vector source, out Vector low, out Vector high) { - int elements = Vector.Count; - Int64* lowPtr = stackalloc Int64[elements / 2]; + int elements = Vector.Count; + long* lowPtr = stackalloc long[elements / 2]; for (int i = 0; i < elements / 2; i++) { - lowPtr[i] = (Int64)source[i]; + lowPtr[i] = (long)source[i]; } - Int64* highPtr = stackalloc Int64[elements / 2]; + long* highPtr = stackalloc long[elements / 2]; for (int i = 0; i < elements / 2; i++) { - highPtr[i] = (Int64)source[i + (elements / 2)]; + highPtr[i] = (long)source[i + (elements / 2)]; } - low = new Vector(lowPtr); - high = new Vector(highPtr); + low = new Vector(lowPtr); + high = new Vector(highPtr); } /// @@ -5154,22 +5154,22 @@ public static unsafe void Widen(Vector source, out Vector low, out /// The second output vector, whose elements will contain the widened elements from higher indices in the source vector. /// [Intrinsic] - public static unsafe void Widen(Vector source, out Vector low, out Vector high) + public static unsafe void Widen(Vector source, out Vector low, out Vector high) { - int elements = Vector.Count; - Double* lowPtr = stackalloc Double[elements / 2]; + int elements = Vector.Count; + double* lowPtr = stackalloc double[elements / 2]; for (int i = 0; i < elements / 2; i++) { - lowPtr[i] = (Double)source[i]; + lowPtr[i] = (double)source[i]; } - Double* highPtr = stackalloc Double[elements / 2]; + double* highPtr = stackalloc double[elements / 2]; for (int i = 0; i < elements / 2; i++) { - highPtr[i] = (Double)source[i + (elements / 2)]; + highPtr[i] = (double)source[i + (elements / 2)]; } - low = new Vector(lowPtr); - high = new Vector(highPtr); + low = new Vector(lowPtr); + high = new Vector(highPtr); } /// @@ -5180,22 +5180,22 @@ public static unsafe void Widen(Vector source, out Vector low, o /// [CLSCompliant(false)] [Intrinsic] - public static unsafe Vector Narrow(Vector low, Vector high) + public static unsafe Vector Narrow(Vector low, Vector high) { unchecked { - int elements = Vector.Count; - Byte* retPtr = stackalloc Byte[elements]; + int elements = Vector.Count; + byte* retPtr = stackalloc byte[elements]; for (int i = 0; i < elements / 2; i++) { - retPtr[i] = (Byte)low[i]; + retPtr[i] = (byte)low[i]; } for (int i = 0; i < elements / 2; i++) { - retPtr[i + (elements / 2)] = (Byte)high[i]; + retPtr[i + (elements / 2)] = (byte)high[i]; } - return new Vector(retPtr); + return new Vector(retPtr); } } @@ -5207,22 +5207,22 @@ public static unsafe Vector Narrow(Vector low, Vector high /// [CLSCompliant(false)] [Intrinsic] - public static unsafe Vector Narrow(Vector low, Vector high) + public static unsafe Vector Narrow(Vector low, Vector high) { unchecked { - int elements = Vector.Count; - UInt16* retPtr = stackalloc UInt16[elements]; + int elements = Vector.Count; + ushort* retPtr = stackalloc ushort[elements]; for (int i = 0; i < elements / 2; i++) { - retPtr[i] = (UInt16)low[i]; + retPtr[i] = (ushort)low[i]; } for (int i = 0; i < elements / 2; i++) { - retPtr[i + (elements / 2)] = (UInt16)high[i]; + retPtr[i + (elements / 2)] = (ushort)high[i]; } - return new Vector(retPtr); + return new Vector(retPtr); } } @@ -5234,22 +5234,22 @@ public static unsafe Vector Narrow(Vector low, Vector hi /// [CLSCompliant(false)] [Intrinsic] - public static unsafe Vector Narrow(Vector low, Vector high) + public static unsafe Vector Narrow(Vector low, Vector high) { unchecked { - int elements = Vector.Count; - UInt32* retPtr = stackalloc UInt32[elements]; + int elements = Vector.Count; + uint* retPtr = stackalloc uint[elements]; for (int i = 0; i < elements / 2; i++) { - retPtr[i] = (UInt32)low[i]; + retPtr[i] = (uint)low[i]; } for (int i = 0; i < elements / 2; i++) { - retPtr[i + (elements / 2)] = (UInt32)high[i]; + retPtr[i + (elements / 2)] = (uint)high[i]; } - return new Vector(retPtr); + return new Vector(retPtr); } } @@ -5261,22 +5261,22 @@ public static unsafe Vector Narrow(Vector low, Vector hi /// [CLSCompliant(false)] [Intrinsic] - public static unsafe Vector Narrow(Vector low, Vector high) + public static unsafe Vector Narrow(Vector low, Vector high) { unchecked { - int elements = Vector.Count; - SByte* retPtr = stackalloc SByte[elements]; + int elements = Vector.Count; + sbyte* retPtr = stackalloc sbyte[elements]; for (int i = 0; i < elements / 2; i++) { - retPtr[i] = (SByte)low[i]; + retPtr[i] = (sbyte)low[i]; } for (int i = 0; i < elements / 2; i++) { - retPtr[i + (elements / 2)] = (SByte)high[i]; + retPtr[i + (elements / 2)] = (sbyte)high[i]; } - return new Vector(retPtr); + return new Vector(retPtr); } } @@ -5287,22 +5287,22 @@ public static unsafe Vector Narrow(Vector low, Vector high) /// A Vector{Int16} containing elements narrowed from the source vectors. /// [Intrinsic] - public static unsafe Vector Narrow(Vector low, Vector high) + public static unsafe Vector Narrow(Vector low, Vector high) { unchecked { - int elements = Vector.Count; - Int16* retPtr = stackalloc Int16[elements]; + int elements = Vector.Count; + short* retPtr = stackalloc short[elements]; for (int i = 0; i < elements / 2; i++) { - retPtr[i] = (Int16)low[i]; + retPtr[i] = (short)low[i]; } for (int i = 0; i < elements / 2; i++) { - retPtr[i + (elements / 2)] = (Int16)high[i]; + retPtr[i + (elements / 2)] = (short)high[i]; } - return new Vector(retPtr); + return new Vector(retPtr); } } @@ -5313,22 +5313,22 @@ public static unsafe Vector Narrow(Vector low, Vector high) /// A Vector{Int32} containing elements narrowed from the source vectors. /// [Intrinsic] - public static unsafe Vector Narrow(Vector low, Vector high) + public static unsafe Vector Narrow(Vector low, Vector high) { unchecked { - int elements = Vector.Count; - Int32* retPtr = stackalloc Int32[elements]; + int elements = Vector.Count; + int* retPtr = stackalloc int[elements]; for (int i = 0; i < elements / 2; i++) { - retPtr[i] = (Int32)low[i]; + retPtr[i] = (int)low[i]; } for (int i = 0; i < elements / 2; i++) { - retPtr[i + (elements / 2)] = (Int32)high[i]; + retPtr[i + (elements / 2)] = (int)high[i]; } - return new Vector(retPtr); + return new Vector(retPtr); } } @@ -5339,22 +5339,22 @@ public static unsafe Vector Narrow(Vector low, Vector high) /// A Vector{Single} containing elements narrowed from the source vectors. /// [Intrinsic] - public static unsafe Vector Narrow(Vector low, Vector high) + public static unsafe Vector Narrow(Vector low, Vector high) { unchecked { - int elements = Vector.Count; - Single* retPtr = stackalloc Single[elements]; + int elements = Vector.Count; + float* retPtr = stackalloc float[elements]; for (int i = 0; i < elements / 2; i++) { - retPtr[i] = (Single)low[i]; + retPtr[i] = (float)low[i]; } for (int i = 0; i < elements / 2; i++) { - retPtr[i + (elements / 2)] = (Single)high[i]; + retPtr[i + (elements / 2)] = (float)high[i]; } - return new Vector(retPtr); + return new Vector(retPtr); } } @@ -5367,18 +5367,18 @@ public static unsafe Vector Narrow(Vector low, Vector hi /// The source vector. /// The converted vector. [Intrinsic] - public static unsafe Vector ConvertToSingle(Vector value) + public static unsafe Vector ConvertToSingle(Vector value) { unchecked { - int elements = Vector.Count; - Single* retPtr = stackalloc Single[elements]; + int elements = Vector.Count; + float* retPtr = stackalloc float[elements]; for (int i = 0; i < elements; i++) { - retPtr[i] = (Single)value[i]; + retPtr[i] = (float)value[i]; } - return new Vector(retPtr); + return new Vector(retPtr); } } @@ -5389,18 +5389,18 @@ public static unsafe Vector ConvertToSingle(Vector value) /// The converted vector. [CLSCompliant(false)] [Intrinsic] - public static unsafe Vector ConvertToSingle(Vector value) + public static unsafe Vector ConvertToSingle(Vector value) { unchecked { - int elements = Vector.Count; - Single* retPtr = stackalloc Single[elements]; + int elements = Vector.Count; + float* retPtr = stackalloc float[elements]; for (int i = 0; i < elements; i++) { - retPtr[i] = (Single)value[i]; + retPtr[i] = (float)value[i]; } - return new Vector(retPtr); + return new Vector(retPtr); } } @@ -5410,18 +5410,18 @@ public static unsafe Vector ConvertToSingle(Vector value) /// The source vector. /// The converted vector. [Intrinsic] - public static unsafe Vector ConvertToDouble(Vector value) + public static unsafe Vector ConvertToDouble(Vector value) { unchecked { - int elements = Vector.Count; - Double* retPtr = stackalloc Double[elements]; + int elements = Vector.Count; + double* retPtr = stackalloc double[elements]; for (int i = 0; i < elements; i++) { - retPtr[i] = (Double)value[i]; + retPtr[i] = (double)value[i]; } - return new Vector(retPtr); + return new Vector(retPtr); } } @@ -5432,18 +5432,18 @@ public static unsafe Vector ConvertToDouble(Vector value) /// The converted vector. [CLSCompliant(false)] [Intrinsic] - public static unsafe Vector ConvertToDouble(Vector value) + public static unsafe Vector ConvertToDouble(Vector value) { unchecked { - int elements = Vector.Count; - Double* retPtr = stackalloc Double[elements]; + int elements = Vector.Count; + double* retPtr = stackalloc double[elements]; for (int i = 0; i < elements; i++) { - retPtr[i] = (Double)value[i]; + retPtr[i] = (double)value[i]; } - return new Vector(retPtr); + return new Vector(retPtr); } } @@ -5453,18 +5453,18 @@ public static unsafe Vector ConvertToDouble(Vector value) /// The source vector. /// The converted vector. [Intrinsic] - public static unsafe Vector ConvertToInt32(Vector value) + public static unsafe Vector ConvertToInt32(Vector value) { unchecked { - int elements = Vector.Count; - Int32* retPtr = stackalloc Int32[elements]; + int elements = Vector.Count; + int* retPtr = stackalloc int[elements]; for (int i = 0; i < elements; i++) { - retPtr[i] = (Int32)value[i]; + retPtr[i] = (int)value[i]; } - return new Vector(retPtr); + return new Vector(retPtr); } } @@ -5475,18 +5475,18 @@ public static unsafe Vector ConvertToInt32(Vector value) /// The converted vector. [CLSCompliant(false)] [Intrinsic] - public static unsafe Vector ConvertToUInt32(Vector value) + public static unsafe Vector ConvertToUInt32(Vector value) { unchecked { - int elements = Vector.Count; - UInt32* retPtr = stackalloc UInt32[elements]; + int elements = Vector.Count; + uint* retPtr = stackalloc uint[elements]; for (int i = 0; i < elements; i++) { - retPtr[i] = (UInt32)value[i]; + retPtr[i] = (uint)value[i]; } - return new Vector(retPtr); + return new Vector(retPtr); } } @@ -5496,18 +5496,18 @@ public static unsafe Vector ConvertToUInt32(Vector value) /// The source vector. /// The converted vector. [Intrinsic] - public static unsafe Vector ConvertToInt64(Vector value) + public static unsafe Vector ConvertToInt64(Vector value) { unchecked { - int elements = Vector.Count; - Int64* retPtr = stackalloc Int64[elements]; + int elements = Vector.Count; + long* retPtr = stackalloc long[elements]; for (int i = 0; i < elements; i++) { - retPtr[i] = (Int64)value[i]; + retPtr[i] = (long)value[i]; } - return new Vector(retPtr); + return new Vector(retPtr); } } @@ -5518,18 +5518,18 @@ public static unsafe Vector ConvertToInt64(Vector value) /// The converted vector. [CLSCompliant(false)] [Intrinsic] - public static unsafe Vector ConvertToUInt64(Vector value) + public static unsafe Vector ConvertToUInt64(Vector value) { unchecked { - int elements = Vector.Count; - UInt64* retPtr = stackalloc UInt64[elements]; + int elements = Vector.Count; + ulong* retPtr = stackalloc ulong[elements]; for (int i = 0; i < elements; i++) { - retPtr[i] = (UInt64)value[i]; + retPtr[i] = (ulong)value[i]; } - return new Vector(retPtr); + return new Vector(retPtr); } } diff --git a/src/System.Private.CoreLib/shared/System/Numerics/Vector_Operations.cs b/src/System.Private.CoreLib/shared/System/Numerics/Vector_Operations.cs index b69b058be94..d3ed2509d87 100644 --- a/src/System.Private.CoreLib/shared/System/Numerics/Vector_Operations.cs +++ b/src/System.Private.CoreLib/shared/System/Numerics/Vector_Operations.cs @@ -22,9 +22,9 @@ public static partial class Vector /// The second source vector. /// The new vector with elements selected based on the mask. [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static Vector ConditionalSelect(Vector condition, Vector left, Vector right) + public static Vector ConditionalSelect(Vector condition, Vector left, Vector right) { - return (Vector)Vector.ConditionalSelect((Vector)condition, left, right); + return (Vector)Vector.ConditionalSelect((Vector)condition, left, right); } /// @@ -75,9 +75,9 @@ public static Vector ConditionalSelect(Vector condition, VectorThe second vector to compare. /// The resultant vector. [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static Vector Equals(Vector left, Vector right) + public static Vector Equals(Vector left, Vector right) { - return (Vector)Vector.Equals(left, right); + return (Vector)Vector.Equals(left, right); } /// @@ -163,9 +163,9 @@ public static Vector Equals(Vector left, Vector right) /// The second vector to compare. /// The resultant integral vector. [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static Vector LessThan(Vector left, Vector right) + public static Vector LessThan(Vector left, Vector right) { - return (Vector)Vector.LessThan(left, right); + return (Vector)Vector.LessThan(left, right); } /// @@ -256,9 +256,9 @@ public static Vector LessThan(Vector left, Vector right) /// The second vector to compare. /// The resultant integral vector. [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static Vector LessThanOrEqual(Vector left, Vector right) + public static Vector LessThanOrEqual(Vector left, Vector right) { - return (Vector)Vector.LessThanOrEqual(left, right); + return (Vector)Vector.LessThanOrEqual(left, right); } /// @@ -349,9 +349,9 @@ public static Vector LessThanOrEqual(Vector left, Vector r /// The second vector to compare. /// The resultant integral vector. [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static Vector GreaterThan(Vector left, Vector right) + public static Vector GreaterThan(Vector left, Vector right) { - return (Vector)Vector.GreaterThan(left, right); + return (Vector)Vector.GreaterThan(left, right); } /// @@ -443,9 +443,9 @@ public static Vector GreaterThan(Vector left, Vector right) /// The second vector to compare. /// The resultant integral vector. [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static Vector GreaterThanOrEqual(Vector left, Vector right) + public static Vector GreaterThanOrEqual(Vector left, Vector right) { - return (Vector)Vector.GreaterThanOrEqual(left, right); + return (Vector)Vector.GreaterThanOrEqual(left, right); } /// @@ -752,9 +752,9 @@ public static bool IsHardwareAccelerated /// The source vector /// The reinterpreted vector. [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static Vector AsVectorByte(Vector value) where T : struct + public static Vector AsVectorByte(Vector value) where T : struct { - return (Vector)value; + return (Vector)value; } /// @@ -764,9 +764,9 @@ public static bool IsHardwareAccelerated /// The reinterpreted vector. [CLSCompliant(false)] [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static Vector AsVectorSByte(Vector value) where T : struct + public static Vector AsVectorSByte(Vector value) where T : struct { - return (Vector)value; + return (Vector)value; } /// @@ -776,9 +776,9 @@ public static bool IsHardwareAccelerated /// The reinterpreted vector. [CLSCompliant(false)] [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static Vector AsVectorUInt16(Vector value) where T : struct + public static Vector AsVectorUInt16(Vector value) where T : struct { - return (Vector)value; + return (Vector)value; } /// @@ -787,9 +787,9 @@ public static bool IsHardwareAccelerated /// The source vector /// The reinterpreted vector. [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static Vector AsVectorInt16(Vector value) where T : struct + public static Vector AsVectorInt16(Vector value) where T : struct { - return (Vector)value; + return (Vector)value; } /// @@ -799,9 +799,9 @@ public static bool IsHardwareAccelerated /// The reinterpreted vector. [CLSCompliant(false)] [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static Vector AsVectorUInt32(Vector value) where T : struct + public static Vector AsVectorUInt32(Vector value) where T : struct { - return (Vector)value; + return (Vector)value; } /// @@ -810,9 +810,9 @@ public static bool IsHardwareAccelerated /// The source vector /// The reinterpreted vector. [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static Vector AsVectorInt32(Vector value) where T : struct + public static Vector AsVectorInt32(Vector value) where T : struct { - return (Vector)value; + return (Vector)value; } /// @@ -822,9 +822,9 @@ public static bool IsHardwareAccelerated /// The reinterpreted vector. [CLSCompliant(false)] [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static Vector AsVectorUInt64(Vector value) where T : struct + public static Vector AsVectorUInt64(Vector value) where T : struct { - return (Vector)value; + return (Vector)value; } @@ -834,9 +834,9 @@ public static bool IsHardwareAccelerated /// The source vector /// The reinterpreted vector. [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static Vector AsVectorInt64(Vector value) where T : struct + public static Vector AsVectorInt64(Vector value) where T : struct { - return (Vector)value; + return (Vector)value; } /// @@ -845,9 +845,9 @@ public static bool IsHardwareAccelerated /// The source vector /// The reinterpreted vector. [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static Vector AsVectorSingle(Vector value) where T : struct + public static Vector AsVectorSingle(Vector value) where T : struct { - return (Vector)value; + return (Vector)value; } /// @@ -856,9 +856,9 @@ public static bool IsHardwareAccelerated /// The source vector /// The reinterpreted vector. [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static Vector AsVectorDouble(Vector value) where T : struct + public static Vector AsVectorDouble(Vector value) where T : struct { - return (Vector)value; + return (Vector)value; } #endregion Conversion Methods } diff --git a/src/System.Private.CoreLib/shared/System/ObsoleteAttribute.cs b/src/System.Private.CoreLib/shared/System/ObsoleteAttribute.cs index a63db137f87..748681756db 100644 --- a/src/System.Private.CoreLib/shared/System/ObsoleteAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/ObsoleteAttribute.cs @@ -26,7 +26,7 @@ namespace System , Inherited = false)] public sealed class ObsoleteAttribute : Attribute { - private String _message; + private string _message; private bool _error; public ObsoleteAttribute() @@ -35,19 +35,19 @@ public ObsoleteAttribute() _error = false; } - public ObsoleteAttribute(String message) + public ObsoleteAttribute(string message) { _message = message; _error = false; } - public ObsoleteAttribute(String message, bool error) + public ObsoleteAttribute(string message, bool error) { _message = message; _error = error; } - public String Message + public string Message { get { return _message; } } diff --git a/src/System.Private.CoreLib/shared/System/OperationCanceledException.cs b/src/System.Private.CoreLib/shared/System/OperationCanceledException.cs index 8a472c9ff03..0c311afd7d8 100644 --- a/src/System.Private.CoreLib/shared/System/OperationCanceledException.cs +++ b/src/System.Private.CoreLib/shared/System/OperationCanceledException.cs @@ -36,13 +36,13 @@ public OperationCanceledException() HResult = HResults.COR_E_OPERATIONCANCELED; } - public OperationCanceledException(String message) + public OperationCanceledException(string message) : base(message) { HResult = HResults.COR_E_OPERATIONCANCELED; } - public OperationCanceledException(String message, Exception innerException) + public OperationCanceledException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_OPERATIONCANCELED; @@ -55,13 +55,13 @@ public OperationCanceledException(CancellationToken token) CancellationToken = token; } - public OperationCanceledException(String message, CancellationToken token) + public OperationCanceledException(string message, CancellationToken token) : this(message) { CancellationToken = token; } - public OperationCanceledException(String message, Exception innerException, CancellationToken token) + public OperationCanceledException(string message, Exception innerException, CancellationToken token) : this(message, innerException) { CancellationToken = token; diff --git a/src/System.Private.CoreLib/shared/System/OutOfMemoryException.cs b/src/System.Private.CoreLib/shared/System/OutOfMemoryException.cs index 7a56c6d7afd..194f3bfdad8 100644 --- a/src/System.Private.CoreLib/shared/System/OutOfMemoryException.cs +++ b/src/System.Private.CoreLib/shared/System/OutOfMemoryException.cs @@ -24,13 +24,13 @@ public class OutOfMemoryException : SystemException HResult = HResults.COR_E_OUTOFMEMORY; } - public OutOfMemoryException(String message) + public OutOfMemoryException(string message) : base(message) { HResult = HResults.COR_E_OUTOFMEMORY; } - public OutOfMemoryException(String message, Exception innerException) + public OutOfMemoryException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_OUTOFMEMORY; diff --git a/src/System.Private.CoreLib/shared/System/OverflowException.cs b/src/System.Private.CoreLib/shared/System/OverflowException.cs index e28dcb87ed5..c18fe3f7b37 100644 --- a/src/System.Private.CoreLib/shared/System/OverflowException.cs +++ b/src/System.Private.CoreLib/shared/System/OverflowException.cs @@ -25,13 +25,13 @@ public OverflowException() HResult = HResults.COR_E_OVERFLOW; } - public OverflowException(String message) + public OverflowException(string message) : base(message) { HResult = HResults.COR_E_OVERFLOW; } - public OverflowException(String message, Exception innerException) + public OverflowException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_OVERFLOW; diff --git a/src/System.Private.CoreLib/shared/System/PlatformNotSupportedException.cs b/src/System.Private.CoreLib/shared/System/PlatformNotSupportedException.cs index 5039f3f4410..f9e461ed0a3 100644 --- a/src/System.Private.CoreLib/shared/System/PlatformNotSupportedException.cs +++ b/src/System.Private.CoreLib/shared/System/PlatformNotSupportedException.cs @@ -25,13 +25,13 @@ public PlatformNotSupportedException() HResult = HResults.COR_E_PLATFORMNOTSUPPORTED; } - public PlatformNotSupportedException(String message) + public PlatformNotSupportedException(string message) : base(message) { HResult = HResults.COR_E_PLATFORMNOTSUPPORTED; } - public PlatformNotSupportedException(String message, Exception inner) + public PlatformNotSupportedException(string message, Exception inner) : base(message, inner) { HResult = HResults.COR_E_PLATFORMNOTSUPPORTED; diff --git a/src/System.Private.CoreLib/shared/System/Random.cs b/src/System.Private.CoreLib/shared/System/Random.cs index 20f035e2e82..ed79732c25a 100644 --- a/src/System.Private.CoreLib/shared/System/Random.cs +++ b/src/System.Private.CoreLib/shared/System/Random.cs @@ -156,7 +156,7 @@ private static unsafe int GenerateGlobalSeed() /*=====================================Next===================================== - **Returns: An int [0..Int32.MaxValue) + **Returns: An int [0..int.MaxValue) **Arguments: None **Exceptions: None. ==============================================================================*/ @@ -169,7 +169,7 @@ 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) + // If we use Sample for a range [int.MinValue..int.MaxValue) // We will end up getting even numbers only. int result = InternalSample(); diff --git a/src/System.Private.CoreLib/shared/System/RankException.cs b/src/System.Private.CoreLib/shared/System/RankException.cs index bdd2cd51f1e..e1e7d169b84 100644 --- a/src/System.Private.CoreLib/shared/System/RankException.cs +++ b/src/System.Private.CoreLib/shared/System/RankException.cs @@ -26,13 +26,13 @@ public RankException() HResult = HResults.COR_E_RANK; } - public RankException(String message) + public RankException(string message) : base(message) { HResult = HResults.COR_E_RANK; } - public RankException(String message, Exception innerException) + public RankException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_RANK; diff --git a/src/System.Private.CoreLib/shared/System/Reflection/Assembly.cs b/src/System.Private.CoreLib/shared/System/Reflection/Assembly.cs index 7280869c026..f22c8c40efa 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/Assembly.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/Assembly.cs @@ -141,7 +141,7 @@ public override string ToString() Returns true if the assembly was loaded from the global assembly cache. */ public virtual bool GlobalAssemblyCache { get { throw NotImplemented.ByDesign; } } - public virtual Int64 HostContext { get { throw NotImplemented.ByDesign; } } + public virtual long HostContext { get { throw NotImplemented.ByDesign; } } public override bool Equals(object o) => base.Equals(o); public override int GetHashCode() => base.GetHashCode(); diff --git a/src/System.Private.CoreLib/shared/System/Reflection/Emit/Label.cs b/src/System.Private.CoreLib/shared/System/Reflection/Emit/Label.cs index d67c0e6a19b..e49d471a99f 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/Emit/Label.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/Emit/Label.cs @@ -49,7 +49,7 @@ public override int GetHashCode() return m_label; } - public override bool Equals(Object obj) + public override bool Equals(object obj) { if (obj is Label) return Equals((Label)obj); diff --git a/src/System.Private.CoreLib/shared/System/Reflection/Emit/Opcode.cs b/src/System.Private.CoreLib/shared/System/Reflection/Emit/Opcode.cs index 78fa735adb3..1a144fcf44b 100644 --- a/src/System.Private.CoreLib/shared/System/Reflection/Emit/Opcode.cs +++ b/src/System.Private.CoreLib/shared/System/Reflection/Emit/Opcode.cs @@ -110,7 +110,7 @@ public short Value private static volatile string[] g_nameCache; - public String Name + public string Name { get { @@ -122,7 +122,7 @@ public String Name string[] nameCache = g_nameCache; if (nameCache == null) { - nameCache = new String[0x11f]; + nameCache = new string[0x11f]; g_nameCache = nameCache; } @@ -144,7 +144,7 @@ public String Name } } - String name = Volatile.Read(ref nameCache[idx]); + string name = Volatile.Read(ref nameCache[idx]); if (name != null) return name; @@ -155,7 +155,7 @@ public String Name } } - public override bool Equals(Object obj) + public override bool Equals(object obj) { if (obj is OpCode) return Equals((OpCode)obj); @@ -183,7 +183,7 @@ public override int GetHashCode() return Value; } - public override String ToString() + public override string ToString() { return Name; } diff --git a/src/System.Private.CoreLib/shared/System/Resources/FastResourceComparer.cs b/src/System.Private.CoreLib/shared/System/Resources/FastResourceComparer.cs index 59ca9437d0a..6b813a0cec3 100644 --- a/src/System.Private.CoreLib/shared/System/Resources/FastResourceComparer.cs +++ b/src/System.Private.CoreLib/shared/System/Resources/FastResourceComparer.cs @@ -26,7 +26,7 @@ internal sealed class FastResourceComparer : IComparer, IEqualityComparer, IComp internal static readonly FastResourceComparer Default = new FastResourceComparer(); // Implements IHashCodeProvider too, due to Hashtable requirements. - public int GetHashCode(Object key) + public int GetHashCode(object key) { string s = (string)key; return FastResourceComparer.HashFunction(s); @@ -52,7 +52,7 @@ internal static int HashFunction(string key) } // Compares Strings quickly in a case-sensitive way - public int Compare(Object a, Object b) + public int Compare(object a, object b) { if (a == b) return 0; string sa = (string)a; @@ -70,7 +70,7 @@ public bool Equals(string a, string b) return string.Equals(a, b); } - public new bool Equals(Object a, Object b) + public new bool Equals(object a, object b) { if (a == b) return true; string sa = (string)a; diff --git a/src/System.Private.CoreLib/shared/System/Resources/MissingSatelliteAssemblyException.cs b/src/System.Private.CoreLib/shared/System/Resources/MissingSatelliteAssemblyException.cs index af547b21f16..0bbc6267345 100644 --- a/src/System.Private.CoreLib/shared/System/Resources/MissingSatelliteAssemblyException.cs +++ b/src/System.Private.CoreLib/shared/System/Resources/MissingSatelliteAssemblyException.cs @@ -24,7 +24,7 @@ namespace System.Resources [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class MissingSatelliteAssemblyException : SystemException { - private String _cultureName; + private string _cultureName; public MissingSatelliteAssemblyException() : base(SR.MissingSatelliteAssembly_Default) @@ -38,7 +38,7 @@ public MissingSatelliteAssemblyException(string message) HResult = System.HResults.COR_E_MISSINGSATELLITEASSEMBLY; } - public MissingSatelliteAssemblyException(string message, String cultureName) + public MissingSatelliteAssemblyException(string message, string cultureName) : base(message) { HResult = System.HResults.COR_E_MISSINGSATELLITEASSEMBLY; @@ -56,7 +56,7 @@ protected MissingSatelliteAssemblyException(SerializationInfo info, StreamingCon { } - public String CultureName + public string CultureName { get { return _cultureName; } } diff --git a/src/System.Private.CoreLib/shared/System/Resources/RuntimeResourceSet.cs b/src/System.Private.CoreLib/shared/System/Resources/RuntimeResourceSet.cs index a63e68c19d2..426e17bdba7 100644 --- a/src/System.Private.CoreLib/shared/System/Resources/RuntimeResourceSet.cs +++ b/src/System.Private.CoreLib/shared/System/Resources/RuntimeResourceSet.cs @@ -173,7 +173,7 @@ sealed class RuntimeResourceSet : ResourceSet, IEnumerable // for arbitrarily long times, since the object is usually a string // literal that will live for the lifetime of the appdomain. The // value is a ResourceLocator instance, which might cache the object. - private Dictionary _resCache; + private Dictionary _resCache; // For our special load-on-demand reader, cache the cast. The @@ -185,15 +185,15 @@ sealed class RuntimeResourceSet : ResourceSet, IEnumerable // want to fill this out if we can avoid it. The problem is resource // fallback will somewhat regularly cause us to look up resources that // don't exist. - private Dictionary _caseInsensitiveTable; + private Dictionary _caseInsensitiveTable; // If we're not using our custom reader, then enumerate through all // the resources once, adding them into the table. private bool _haveReadFromReader; - internal RuntimeResourceSet(String fileName) : base(false) + internal RuntimeResourceSet(string fileName) : base(false) { - _resCache = new Dictionary(FastResourceComparer.Default); + _resCache = new Dictionary(FastResourceComparer.Default); Stream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read); _defaultReader = new ResourceReader(stream, _resCache); Reader = _defaultReader; @@ -201,7 +201,7 @@ internal RuntimeResourceSet(String fileName) : base(false) internal RuntimeResourceSet(Stream stream) : base(false) { - _resCache = new Dictionary(FastResourceComparer.Default); + _resCache = new Dictionary(FastResourceComparer.Default); _defaultReader = new ResourceReader(stream, _resCache); Reader = _defaultReader; } @@ -256,36 +256,36 @@ private IDictionaryEnumerator GetEnumeratorHelper() } - public override String GetString(String key) + public override string GetString(string key) { - Object o = GetObject(key, false, true); - return (String)o; + object o = GetObject(key, false, true); + return (string)o; } - public override String GetString(String key, bool ignoreCase) + public override string GetString(string key, bool ignoreCase) { - Object o = GetObject(key, ignoreCase, true); - return (String)o; + object o = GetObject(key, ignoreCase, true); + return (string)o; } - public override Object GetObject(String key) + public override object GetObject(string key) { return GetObject(key, false, false); } - public override Object GetObject(String key, bool ignoreCase) + public override object GetObject(string key, bool ignoreCase) { return GetObject(key, ignoreCase, false); } - private Object GetObject(String key, bool ignoreCase, bool isString) + private object GetObject(string key, bool ignoreCase, bool isString) { if (key == null) throw new ArgumentNullException(nameof(key)); if (Reader == null || _resCache == null) throw new ObjectDisposedException(null, SR.ObjectDisposed_ResourceSet); - Object value = null; + object value = null; ResourceLocator resLocation; lock (Reader) @@ -348,7 +348,7 @@ private Object GetObject(String key, bool ignoreCase, bool isString) // If necessary, init our case insensitive hash table. if (ignoreCase && _caseInsensitiveTable == null) { - _caseInsensitiveTable = new Dictionary(StringComparer.OrdinalIgnoreCase); + _caseInsensitiveTable = new Dictionary(StringComparer.OrdinalIgnoreCase); } if (_defaultReader == null) @@ -357,7 +357,7 @@ private Object GetObject(String key, bool ignoreCase, bool isString) 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) @@ -375,7 +375,7 @@ private Object GetObject(String key, bool ignoreCase, bool isString) 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); @@ -383,7 +383,7 @@ private Object GetObject(String key, bool ignoreCase, bool isString) } _haveReadFromReader = true; } - Object obj = null; + object obj = null; bool found = false; bool keyInWrongCase = false; if (_defaultReader != null) @@ -410,11 +410,11 @@ private Object GetObject(String key, bool ignoreCase, bool isString) // The last parameter indicates whether the lookup required a // case-insensitive lookup to succeed, indicating we shouldn't add // the ResourceLocation to our case-sensitive cache. - private Object ResolveResourceLocator(ResourceLocator resLocation, String key, Dictionary copyOfCache, bool keyInWrongCase) + private object ResolveResourceLocator(ResourceLocator resLocation, string key, Dictionary copyOfCache, bool keyInWrongCase) { // We need to explicitly resolve loosely linked manifest // resources, and we need to resolve ResourceLocators with null objects. - Object value = resLocation.Value; + object value = resLocation.Value; if (value == null) { ResourceTypeCode typeCode; diff --git a/src/System.Private.CoreLib/shared/System/Resources/SatelliteContractVersionAttribute.cs b/src/System.Private.CoreLib/shared/System/Resources/SatelliteContractVersionAttribute.cs index 0707447677f..aeccadca99b 100644 --- a/src/System.Private.CoreLib/shared/System/Resources/SatelliteContractVersionAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Resources/SatelliteContractVersionAttribute.cs @@ -19,13 +19,13 @@ namespace System.Resources [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)] public sealed class SatelliteContractVersionAttribute : Attribute { - public SatelliteContractVersionAttribute(String version) + public SatelliteContractVersionAttribute(string version) { if (version == null) throw new ArgumentNullException(nameof(version)); Version = version; } - public String Version { get; } + public string Version { get; } } } diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CustomConstantAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CustomConstantAttribute.cs index f75693eb405..d3116cc8ad8 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CustomConstantAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/CustomConstantAttribute.cs @@ -7,6 +7,6 @@ namespace System.Runtime.CompilerServices [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] public abstract class CustomConstantAttribute : Attribute { - public abstract Object Value { get; } + public abstract object Value { get; } } } diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DateTimeConstantAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DateTimeConstantAttribute.cs index 813e6803bfa..44c497706e3 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DateTimeConstantAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DateTimeConstantAttribute.cs @@ -14,6 +14,6 @@ public DateTimeConstantAttribute(long ticks) _date = new DateTime(ticks); } - public override Object Value => _date; + public override object Value => _date; } } diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DecimalConstantAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DecimalConstantAttribute.cs index 19db84eb43b..521a3abe9cb 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DecimalConstantAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DecimalConstantAttribute.cs @@ -9,7 +9,7 @@ namespace System.Runtime.CompilerServices [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] public sealed class DecimalConstantAttribute : Attribute { - private Decimal _dec; + private decimal _dec; [CLSCompliant(false)] public DecimalConstantAttribute( @@ -20,7 +20,7 @@ public sealed class DecimalConstantAttribute : Attribute uint low ) { - _dec = new Decimal((int)low, (int)mid, (int)hi, (sign != 0), scale); + _dec = new decimal((int)low, (int)mid, (int)hi, (sign != 0), scale); } public DecimalConstantAttribute( @@ -31,9 +31,9 @@ uint low int low ) { - _dec = new Decimal(low, mid, hi, (sign != 0), scale); + _dec = new decimal(low, mid, hi, (sign != 0), scale); } - public Decimal Value => _dec; + public decimal Value => _dec; } } diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DependencyAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DependencyAttribute.cs index 0fe07edc9e2..7bb7acec417 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DependencyAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/DependencyAttribute.cs @@ -7,13 +7,13 @@ namespace System.Runtime.CompilerServices [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] public sealed class DependencyAttribute : Attribute { - public DependencyAttribute(String dependentAssemblyArgument, LoadHint loadHintArgument) + public DependencyAttribute(string dependentAssemblyArgument, LoadHint loadHintArgument) { DependentAssembly = dependentAssemblyArgument; LoadHint = loadHintArgument; } - public String DependentAssembly { get; } + public string DependentAssembly { get; } public LoadHint LoadHint { get; } } } \ No newline at end of file diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/IndexerNameAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/IndexerNameAttribute.cs index ea843b3daaa..bc76250adc8 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/IndexerNameAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/IndexerNameAttribute.cs @@ -7,7 +7,7 @@ namespace System.Runtime.CompilerServices [AttributeUsage(AttributeTargets.Property, Inherited = true)] public sealed class IndexerNameAttribute : Attribute { - public IndexerNameAttribute(String indexerName) + public IndexerNameAttribute(string indexerName) { } } diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ReferenceAssemblyAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ReferenceAssemblyAttribute.cs index f3842ec562d..6c6fe9e258c 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ReferenceAssemblyAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/ReferenceAssemblyAttribute.cs @@ -22,11 +22,11 @@ public ReferenceAssemblyAttribute() { } - public ReferenceAssemblyAttribute(String description) + public ReferenceAssemblyAttribute(string description) { Description = description; } - public String Description { get; } + public string Description { get; } } } diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/MarshalDirectiveException.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/MarshalDirectiveException.cs index 1d0d59fab6f..3bb1140f5e9 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/MarshalDirectiveException.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/MarshalDirectiveException.cs @@ -27,13 +27,13 @@ public MarshalDirectiveException() HResult = HResults.COR_E_MARSHALDIRECTIVE; } - public MarshalDirectiveException(String message) + public MarshalDirectiveException(string message) : base(message) { HResult = HResults.COR_E_MARSHALDIRECTIVE; } - public MarshalDirectiveException(String message, Exception inner) + public MarshalDirectiveException(string message, Exception inner) : base(message, inner) { HResult = HResults.COR_E_MARSHALDIRECTIVE; diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/MemoryMarshal.Fast.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/MemoryMarshal.Fast.cs index c71c7820ef4..a954529541a 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/MemoryMarshal.Fast.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/MemoryMarshal.Fast.cs @@ -22,7 +22,7 @@ public static partial class MemoryMarshal /// Thrown when contains pointers. /// /// - /// Thrown if the Length property of the new Span would exceed Int32.MaxValue. + /// Thrown if the Length property of the new Span would exceed int.MaxValue. /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span AsBytes(Span span) @@ -45,7 +45,7 @@ public static Span AsBytes(Span span) /// Thrown when contains pointers. /// /// - /// Thrown if the Length property of the new Span would exceed Int32.MaxValue. + /// Thrown if the Length property of the new Span would exceed int.MaxValue. /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan AsBytes(ReadOnlySpan span) diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/SafeBuffer.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/SafeBuffer.cs index 5b72b013864..661a7edceaf 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/SafeBuffer.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/SafeBuffer.cs @@ -77,7 +77,7 @@ 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); + ((UIntPtr)uint.MaxValue) : ((UIntPtr)ulong.MaxValue); private UIntPtr _numBytes; @@ -94,7 +94,7 @@ protected SafeBuffer(bool ownsHandle) : base(ownsHandle) [CLSCompliant(false)] public void Initialize(ulong numBytes) { - if (IntPtr.Size == 4 && numBytes > UInt32.MaxValue) + if (IntPtr.Size == 4 && numBytes > uint.MaxValue) throw new ArgumentOutOfRangeException(nameof(numBytes), SR.ArgumentOutOfRange_AddressSpace); if (numBytes >= (ulong)Uninitialized) @@ -110,7 +110,7 @@ public void Initialize(ulong numBytes) [CLSCompliant(false)] public void Initialize(uint numElements, uint sizeOfEachElement) { - if (IntPtr.Size == 4 && numElements * sizeOfEachElement > UInt32.MaxValue) + if (IntPtr.Size == 4 && numElements * sizeOfEachElement > uint.MaxValue) throw new ArgumentOutOfRangeException("numBytes", SR.ArgumentOutOfRange_AddressSpace); if (numElements * sizeOfEachElement >= (ulong)Uninitialized) diff --git a/src/System.Private.CoreLib/shared/System/Runtime/Serialization/SerializationException.cs b/src/System.Private.CoreLib/shared/System/Runtime/Serialization/SerializationException.cs index 1c9c21eabbd..92c01ee30f2 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/Serialization/SerializationException.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/Serialization/SerializationException.cs @@ -10,7 +10,7 @@ namespace System.Runtime.Serialization [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class SerializationException : SystemException { - private static String s_nullMessage = SR.SerializationException; + private static string s_nullMessage = SR.SerializationException; // Creates a new SerializationException with its message // string set to a default message. @@ -20,13 +20,13 @@ public SerializationException() HResult = HResults.COR_E_SERIALIZATION; } - public SerializationException(String message) + public SerializationException(string message) : base(message) { HResult = HResults.COR_E_SERIALIZATION; } - public SerializationException(String message, Exception innerException) + public SerializationException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_SERIALIZATION; diff --git a/src/System.Private.CoreLib/shared/System/Runtime/Versioning/TargetFrameworkAttribute.cs b/src/System.Private.CoreLib/shared/System/Runtime/Versioning/TargetFrameworkAttribute.cs index a8190663821..dcb14f0efe9 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/Versioning/TargetFrameworkAttribute.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/Versioning/TargetFrameworkAttribute.cs @@ -19,11 +19,11 @@ namespace System.Runtime.Versioning [AttributeUsageAttribute(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)] public sealed class TargetFrameworkAttribute : Attribute { - private String _frameworkName; // A target framework moniker - private String _frameworkDisplayName; + private string _frameworkName; // A target framework moniker + private string _frameworkDisplayName; // The frameworkName parameter is intended to be the string form of a FrameworkName instance. - public TargetFrameworkAttribute(String frameworkName) + public TargetFrameworkAttribute(string frameworkName) { if (frameworkName == null) throw new ArgumentNullException(nameof(frameworkName)); @@ -32,12 +32,12 @@ public TargetFrameworkAttribute(String frameworkName) // 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/System.Private.CoreLib/shared/System/SByte.cs b/src/System.Private.CoreLib/shared/System/SByte.cs index c7cee2adc24..e3c6d170a1d 100644 --- a/src/System.Private.CoreLib/shared/System/SByte.cs +++ b/src/System.Private.CoreLib/shared/System/SByte.cs @@ -12,7 +12,7 @@ namespace System [Serializable] [CLSCompliant(false)] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] - public struct SByte : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable + public struct SByte : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable { private sbyte m_value; // Do not rename (binary serialization) @@ -29,36 +29,36 @@ public struct SByte : IComparable, IConvertible, IFormattable, IComparable 0 && (format[0] == 'X' || format[0] == 'x')) { @@ -107,14 +107,14 @@ public bool TryFormat(Span destination, out int charsWritten, ReadOnlySpan } [CLSCompliant(false)] - public static sbyte Parse(String s) + public static sbyte Parse(string s) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan)s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } [CLSCompliant(false)] - public static sbyte Parse(String s, NumberStyles style) + public static sbyte Parse(string s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); @@ -122,7 +122,7 @@ public static sbyte Parse(String s, NumberStyles style) } [CLSCompliant(false)] - public static sbyte Parse(String s, IFormatProvider provider) + public static sbyte Parse(string s, IFormatProvider provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan)s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); @@ -133,7 +133,7 @@ public static sbyte Parse(String s, IFormatProvider provider) // NumberFormatInfo is assumed. // [CLSCompliant(false)] - public static sbyte Parse(String s, NumberStyles style, IFormatProvider provider) + public static sbyte Parse(string s, NumberStyles style, IFormatProvider provider) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); @@ -147,7 +147,7 @@ public static sbyte Parse(ReadOnlySpan s, NumberStyles style = NumberStyle 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) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan)s, style, info); @@ -167,7 +167,7 @@ private static sbyte Parse(ReadOnlySpan s, NumberStyles style, NumberForma if ((style & NumberStyles.AllowHexSpecifier) != 0) { // We are parsing a hexadecimal number - if ((i < 0) || i > Byte.MaxValue) + if ((i < 0) || i > byte.MaxValue) { throw new OverflowException(SR.Overflow_SByte); } @@ -179,7 +179,7 @@ private static sbyte Parse(ReadOnlySpan s, NumberStyles style, NumberForma } [CLSCompliant(false)] - public static bool TryParse(String s, out SByte result) + public static bool TryParse(string s, out sbyte result) { if (s == null) { @@ -197,7 +197,7 @@ public static bool TryParse(ReadOnlySpan s, out sbyte result) } [CLSCompliant(false)] - public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out SByte result) + public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, out sbyte result) { NumberFormatInfo.ValidateParseStyleInteger(style); @@ -217,7 +217,7 @@ public static bool TryParse(ReadOnlySpan s, NumberStyles style, IFormatPro return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result); } - private static bool TryParse(ReadOnlySpan s, NumberStyles style, NumberFormatInfo info, out SByte result) + private static bool TryParse(ReadOnlySpan s, NumberStyles style, NumberFormatInfo info, out sbyte result) { result = 0; int i; @@ -228,7 +228,7 @@ private static bool TryParse(ReadOnlySpan s, NumberStyles style, NumberFor if ((style & NumberStyles.AllowHexSpecifier) != 0) { // We are parsing a hexadecimal number - if ((i < 0) || i > Byte.MaxValue) + if ((i < 0) || i > byte.MaxValue) { return false; } @@ -314,7 +314,7 @@ float IConvertible.ToSingle(IFormatProvider provider) return Convert.ToDouble(m_value); } - Decimal IConvertible.ToDecimal(IFormatProvider provider) + decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } @@ -324,7 +324,7 @@ DateTime IConvertible.ToDateTime(IFormatProvider provider) throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "SByte", "DateTime")); } - 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/System.Private.CoreLib/shared/System/Security/SecureString.cs b/src/System.Private.CoreLib/shared/System/Security/SecureString.cs index 22f15accaaf..5eb66290e38 100644 --- a/src/System.Private.CoreLib/shared/System/Security/SecureString.cs +++ b/src/System.Private.CoreLib/shared/System/Security/SecureString.cs @@ -139,7 +139,7 @@ public void SetAt(int index, char c) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexString); } - Debug.Assert(index <= Int32.MaxValue / sizeof(char)); + Debug.Assert(index <= int.MaxValue / sizeof(char)); EnsureNotDisposed(); EnsureNotReadOnly(); diff --git a/src/System.Private.CoreLib/shared/System/Single.cs b/src/System.Private.CoreLib/shared/System/Single.cs index a74d3770fa2..1a778c957c0 100644 --- a/src/System.Private.CoreLib/shared/System/Single.cs +++ b/src/System.Private.CoreLib/shared/System/Single.cs @@ -23,7 +23,7 @@ namespace System [Serializable] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] - public struct Single : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable + public struct Single : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable { private float m_value; // Do not rename (binary serialization) @@ -118,13 +118,13 @@ public static unsafe bool IsSubnormal(float f) // 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) + public int CompareTo(object value) { if (value == null) { return 1; } - if (value is Single) + if (value is float) { float f = (float)value; if (m_value < f) return -1; @@ -141,7 +141,7 @@ public int CompareTo(Object value) } - public int CompareTo(Single value) + public int CompareTo(float value) { if (m_value < value) return -1; if (m_value > value) return 1; @@ -155,48 +155,48 @@ public int CompareTo(Single value) } [NonVersionable] - public static bool operator ==(Single left, Single right) + public static bool operator ==(float left, float right) { return left == right; } [NonVersionable] - public static bool operator !=(Single left, Single right) + public static bool operator !=(float left, float right) { return left != right; } [NonVersionable] - public static bool operator <(Single left, Single right) + public static bool operator <(float left, float right) { return left < right; } [NonVersionable] - public static bool operator >(Single left, Single right) + public static bool operator >(float left, float right) { return left > right; } [NonVersionable] - public static bool operator <=(Single left, Single right) + public static bool operator <=(float left, float right) { return left <= right; } [NonVersionable] - public static bool operator >=(Single left, Single right) + public static bool operator >=(float left, float right) { return left >= right; } - public override bool Equals(Object obj) + public override bool Equals(object obj) { - if (!(obj is Single)) + if (!(obj is float)) { return false; } - float temp = ((Single)obj).m_value; + float temp = ((float)obj).m_value; if (temp == m_value) { return true; @@ -205,7 +205,7 @@ public override bool Equals(Object obj) return IsNaN(temp) && IsNaN(m_value); } - public bool Equals(Single obj) + public bool Equals(float obj) { if (obj == m_value) { @@ -229,22 +229,22 @@ public override int GetHashCode() return bits; } - public override String ToString() + public override string ToString() { return Number.FormatSingle(m_value, null, NumberFormatInfo.CurrentInfo); } - public String ToString(IFormatProvider provider) + public string ToString(IFormatProvider provider) { return Number.FormatSingle(m_value, null, NumberFormatInfo.GetInstance(provider)); } - public String ToString(String format) + public string ToString(string format) { return Number.FormatSingle(m_value, format, NumberFormatInfo.CurrentInfo); } - public String ToString(String format, IFormatProvider provider) + public string ToString(string format, IFormatProvider provider) { return Number.FormatSingle(m_value, format, NumberFormatInfo.GetInstance(provider)); } @@ -262,26 +262,26 @@ public bool TryFormat(Span destination, out int charsWritten, ReadOnlySpan // 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) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseSingle(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo); } - public static float Parse(String s, NumberStyles style) + public static float Parse(string s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseSingle(s, style, NumberFormatInfo.CurrentInfo); } - public static float Parse(String s, IFormatProvider provider) + public static float Parse(string s, IFormatProvider provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseSingle(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.GetInstance(provider)); } - public static float Parse(String s, NumberStyles style, IFormatProvider provider) + public static float Parse(string s, NumberStyles style, IFormatProvider provider) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); @@ -294,7 +294,7 @@ public static float Parse(ReadOnlySpan s, NumberStyles style = NumberStyle return Number.ParseSingle(s, style, NumberFormatInfo.GetInstance(provider)); } - public static Boolean TryParse(String s, out Single result) + public static bool TryParse(string s, out float result) { if (s == null) { @@ -310,7 +310,7 @@ public static bool TryParse(ReadOnlySpan s, out float 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 bool TryParse(string s, NumberStyles style, IFormatProvider provider, out float result) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); @@ -329,7 +329,7 @@ public static bool TryParse(ReadOnlySpan s, NumberStyles style, IFormatPro return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result); } - private static Boolean TryParse(ReadOnlySpan s, NumberStyles style, NumberFormatInfo info, out Single result) + private static bool TryParse(ReadOnlySpan s, NumberStyles style, NumberFormatInfo info, out float result) { bool success = Number.TryParseSingle(s, style, info, out result); if (!success) @@ -425,7 +425,7 @@ float IConvertible.ToSingle(IFormatProvider provider) return Convert.ToDouble(m_value); } - Decimal IConvertible.ToDecimal(IFormatProvider provider) + decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } @@ -435,7 +435,7 @@ DateTime IConvertible.ToDateTime(IFormatProvider provider) throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Single", "DateTime")); } - 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/System.Private.CoreLib/shared/System/StackOverflowException.cs b/src/System.Private.CoreLib/shared/System/StackOverflowException.cs index 6f954cc75a6..a603ea88b28 100644 --- a/src/System.Private.CoreLib/shared/System/StackOverflowException.cs +++ b/src/System.Private.CoreLib/shared/System/StackOverflowException.cs @@ -25,13 +25,13 @@ public StackOverflowException() HResult = HResults.COR_E_STACKOVERFLOW; } - public StackOverflowException(String message) + public StackOverflowException(string message) : base(message) { HResult = HResults.COR_E_STACKOVERFLOW; } - public StackOverflowException(String message, Exception innerException) + public StackOverflowException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_STACKOVERFLOW; diff --git a/src/System.Private.CoreLib/shared/System/String.Manipulation.cs b/src/System.Private.CoreLib/shared/System/String.Manipulation.cs index 5face0764ab..3359410a932 100644 --- a/src/System.Private.CoreLib/shared/System/String.Manipulation.cs +++ b/src/System.Private.CoreLib/shared/System/String.Manipulation.cs @@ -1246,7 +1246,7 @@ public string[] Split(string separator, StringSplitOptions options = StringSplit return SplitInternal(separator ?? string.Empty, null, int.MaxValue, options); } - public string[] Split(string separator, Int32 count, StringSplitOptions options = StringSplitOptions.None) + public string[] Split(string separator, int count, StringSplitOptions options = StringSplitOptions.None) { return SplitInternal(separator ?? string.Empty, null, count, options); } @@ -1256,7 +1256,7 @@ public string[] Split(string[] separator, StringSplitOptions options) return SplitInternal(null, separator, int.MaxValue, options); } - public string[] Split(string[] separator, Int32 count, StringSplitOptions options) + public string[] Split(string[] separator, int count, StringSplitOptions options) { return SplitInternal(null, separator, count, options); } @@ -1682,7 +1682,7 @@ public string ToUpperInvariant() } // Trims the whitespace from both ends of the string. Whitespace is defined by - // Char.IsWhiteSpace. + // char.IsWhiteSpace. // public string Trim() => TrimWhiteSpaceHelper(TrimType.Both); diff --git a/src/System.Private.CoreLib/shared/System/String.cs b/src/System.Private.CoreLib/shared/System/String.cs index 85d0d4ef5df..7050644d9aa 100644 --- a/src/System.Private.CoreLib/shared/System/String.cs +++ b/src/System.Private.CoreLib/shared/System/String.cs @@ -15,13 +15,13 @@ namespace System { // The String class represents a static string of characters. Many of - // the String methods perform some type of transformation on the current - // instance and return the result as a new String. As with arrays, character + // the string methods perform some type of transformation on the current + // instance and return the result as a new string. As with arrays, character // positions (indices) are zero-based. [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] - public sealed partial class String : IComparable, IEnumerable, IConvertible, IEnumerable, IComparable, IEquatable, ICloneable + public sealed partial class String : IComparable, IEnumerable, IConvertible, IEnumerable, IComparable, IEquatable, ICloneable { // String constructors // These are special. The implementation methods for these have a different signature from the @@ -453,7 +453,7 @@ public static bool IsNullOrWhiteSpace(string value) for (int i = 0; i < value.Length; i++) { - if (!Char.IsWhiteSpace(value[i])) return false; + if (!char.IsWhiteSpace(value[i])) return false; } return true; @@ -704,7 +704,7 @@ float IConvertible.ToSingle(IFormatProvider provider) return Convert.ToDouble(this, provider); } - Decimal IConvertible.ToDecimal(IFormatProvider provider) + decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(this, provider); } @@ -714,7 +714,7 @@ DateTime IConvertible.ToDateTime(IFormatProvider provider) return Convert.ToDateTime(this, provider); } - 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/System.Private.CoreLib/shared/System/StringComparer.cs b/src/System.Private.CoreLib/shared/System/StringComparer.cs index cb2d32fccba..8cd8f3756e5 100644 --- a/src/System.Private.CoreLib/shared/System/StringComparer.cs +++ b/src/System.Private.CoreLib/shared/System/StringComparer.cs @@ -114,10 +114,10 @@ public int Compare(object x, object y) if (x == null) return -1; if (y == null) return 1; - String sa = x as String; + string sa = x as string; if (sa != null) { - String sb = y as String; + string sb = y as string; if (sb != null) { return Compare(sa, sb); @@ -133,15 +133,15 @@ public int Compare(object x, object y) throw new ArgumentException(SR.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; + string sa = x as string; if (sa != null) { - String sb = y as String; + string sb = y as string; if (sb != null) { return Equals(sa, sb); @@ -165,8 +165,8 @@ public int GetHashCode(object obj) return obj.GetHashCode(); } - public abstract int Compare(String x, String y); - public abstract bool Equals(String x, String y); + public abstract int Compare(string x, string y); + public abstract bool Equals(string x, string y); public abstract int GetHashCode(string obj); } diff --git a/src/System.Private.CoreLib/shared/System/SystemException.cs b/src/System.Private.CoreLib/shared/System/SystemException.cs index b7e8e421759..9a1daf2104b 100644 --- a/src/System.Private.CoreLib/shared/System/SystemException.cs +++ b/src/System.Private.CoreLib/shared/System/SystemException.cs @@ -16,13 +16,13 @@ public SystemException() HResult = HResults.COR_E_SYSTEM; } - public SystemException(String message) + public SystemException(string message) : base(message) { HResult = HResults.COR_E_SYSTEM; } - public SystemException(String message, Exception innerException) + public SystemException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_SYSTEM; diff --git a/src/System.Private.CoreLib/shared/System/Text/ASCIIEncoding.cs b/src/System.Private.CoreLib/shared/System/Text/ASCIIEncoding.cs index 67fcf1a07f0..217d9346776 100644 --- a/src/System.Private.CoreLib/shared/System/Text/ASCIIEncoding.cs +++ b/src/System.Private.CoreLib/shared/System/Text/ASCIIEncoding.cs @@ -81,7 +81,7 @@ public override unsafe int GetByteCount(char[] chars, int index, int count) // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe - public override unsafe int GetByteCount(String chars) + public override unsafe int GetByteCount(string chars) { // Validate input if (chars==null) @@ -122,7 +122,7 @@ public override unsafe int GetByteCount(ReadOnlySpan chars) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding - public override unsafe int GetBytes(String chars, int charIndex, int charCount, + public override unsafe int GetBytes(string chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (chars == null || bytes == null) @@ -382,7 +382,7 @@ internal sealed override unsafe int GetByteCount(char* chars, int charCount, Enc if (encoder != null) { charLeftOver = encoder._charLeftOver; - Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver), + Debug.Assert(charLeftOver == 0 || char.IsHighSurrogate(charLeftOver), "[ASCIIEncoding.GetByteCount]leftover character should be high surrogate"); fallback = encoder.Fallback as EncoderReplacementFallback; @@ -434,7 +434,7 @@ internal sealed override unsafe int GetByteCount(char* chars, int charCount, Enc // We may have a left over character from last time, try and process it. if (charLeftOver > 0) { - Debug.Assert(Char.IsHighSurrogate(charLeftOver), "[ASCIIEncoding.GetByteCount]leftover character should be high surrogate"); + Debug.Assert(char.IsHighSurrogate(charLeftOver), "[ASCIIEncoding.GetByteCount]leftover character should be high surrogate"); Debug.Assert(encoder != null, "[ASCIIEncoding.GetByteCount]Expected encoder"); // Since left over char was a surrogate, it'll have to be fallen back. @@ -536,7 +536,7 @@ internal sealed override unsafe int GetByteCount(char* chars, int charCount, Enc fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, true); } - Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver), + Debug.Assert(charLeftOver == 0 || char.IsHighSurrogate(charLeftOver), "[ASCIIEncoding.GetBytes]leftover character should be high surrogate"); // Verify that we have no fallbackbuffer, for ASCII its always empty, so just assert diff --git a/src/System.Private.CoreLib/shared/System/Text/DecoderBestFitFallback.cs b/src/System.Private.CoreLib/shared/System/Text/DecoderBestFitFallback.cs index 30c817c91a5..8c62730c26e 100644 --- a/src/System.Private.CoreLib/shared/System/Text/DecoderBestFitFallback.cs +++ b/src/System.Private.CoreLib/shared/System/Text/DecoderBestFitFallback.cs @@ -38,7 +38,7 @@ public override int MaxCharCount } } - public override bool Equals(Object value) + public override bool Equals(object value) { InternalDecoderBestFitFallback that = value as InternalDecoderBestFitFallback; if (that != null) @@ -63,15 +63,15 @@ internal sealed class InternalDecoderBestFitFallbackBuffer : DecoderFallbackBuff private InternalDecoderBestFitFallback _oFallback; // Private object for locking instead of locking on a public type for SQL reliability work. - private static Object s_InternalSyncObject; - private static Object InternalSyncObject + private static object s_InternalSyncObject; + private static object InternalSyncObject { get { if (s_InternalSyncObject == null) { - Object o = new Object(); - Interlocked.CompareExchange(ref s_InternalSyncObject, o, null); + object o = new object(); + Interlocked.CompareExchange(ref s_InternalSyncObject, o, null); } return s_InternalSyncObject; } diff --git a/src/System.Private.CoreLib/shared/System/Text/DecoderExceptionFallback.cs b/src/System.Private.CoreLib/shared/System/Text/DecoderExceptionFallback.cs index 8bfc1f32d31..56c004714f0 100644 --- a/src/System.Private.CoreLib/shared/System/Text/DecoderExceptionFallback.cs +++ b/src/System.Private.CoreLib/shared/System/Text/DecoderExceptionFallback.cs @@ -29,7 +29,7 @@ public override int MaxCharCount } } - public override bool Equals(Object value) + public override bool Equals(object value) { DecoderExceptionFallback that = value as DecoderExceptionFallback; if (that != null) @@ -112,19 +112,19 @@ public DecoderFallbackException() HResult = HResults.COR_E_ARGUMENT; } - public DecoderFallbackException(String message) + public DecoderFallbackException(string message) : base(message) { HResult = HResults.COR_E_ARGUMENT; } - public DecoderFallbackException(String message, Exception innerException) + public DecoderFallbackException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_ARGUMENT; } - public DecoderFallbackException(String message, byte[] bytesUnknown, int index) + public DecoderFallbackException(string message, byte[] bytesUnknown, int index) : base(message) { _bytesUnknown = bytesUnknown; diff --git a/src/System.Private.CoreLib/shared/System/Text/DecoderFallback.cs b/src/System.Private.CoreLib/shared/System/Text/DecoderFallback.cs index 11b9539b5c3..fff8ad1d7bb 100644 --- a/src/System.Private.CoreLib/shared/System/Text/DecoderFallback.cs +++ b/src/System.Private.CoreLib/shared/System/Text/DecoderFallback.cs @@ -104,9 +104,9 @@ internal unsafe virtual bool InternalFallback(byte[] bytes, byte* pBytes, ref ch while ((ch = GetNextChar()) != 0) { // Make sure no mixed up surrogates - if (Char.IsSurrogate(ch)) + if (char.IsSurrogate(ch)) { - if (Char.IsHighSurrogate(ch)) + if (char.IsHighSurrogate(ch)) { // High Surrogate if (bHighSurrogate) @@ -159,9 +159,9 @@ internal unsafe virtual int InternalFallback(byte[] bytes, byte* pBytes) while ((ch = GetNextChar()) != 0) { // Make sure no mixed up surrogates - if (Char.IsSurrogate(ch)) + if (char.IsSurrogate(ch)) { - if (Char.IsHighSurrogate(ch)) + if (char.IsHighSurrogate(ch)) { // High Surrogate if (bHighSurrogate) diff --git a/src/System.Private.CoreLib/shared/System/Text/DecoderReplacementFallback.cs b/src/System.Private.CoreLib/shared/System/Text/DecoderReplacementFallback.cs index 422b80bb2fc..a97baf05cb0 100644 --- a/src/System.Private.CoreLib/shared/System/Text/DecoderReplacementFallback.cs +++ b/src/System.Private.CoreLib/shared/System/Text/DecoderReplacementFallback.cs @@ -9,14 +9,14 @@ namespace System.Text public sealed class DecoderReplacementFallback : DecoderFallback { // Our variables - private String _strDefault; + private string _strDefault; // Construction. Default replacement fallback uses no best fit and ? replacement string public DecoderReplacementFallback() : this("?") { } - public DecoderReplacementFallback(String replacement) + public DecoderReplacementFallback(string replacement) { if (replacement == null) throw new ArgumentNullException(nameof(replacement)); @@ -26,10 +26,10 @@ public DecoderReplacementFallback(String replacement) 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)) + if (char.IsHighSurrogate(replacement, i)) { // if already had a high one, stop if (bFoundHigh) @@ -60,7 +60,7 @@ public DecoderReplacementFallback(String replacement) _strDefault = replacement; } - public String DefaultString + public string DefaultString { get { @@ -82,7 +82,7 @@ public override int MaxCharCount } } - public override bool Equals(Object value) + public override bool Equals(object value) { DecoderReplacementFallback that = value as DecoderReplacementFallback; if (that != null) @@ -103,7 +103,7 @@ public override int GetHashCode() public sealed class DecoderReplacementFallbackBuffer : DecoderFallbackBuffer { // Store our default string - private String _strDefault; + private string _strDefault; private int _fallbackCount = -1; private int _fallbackIndex = -1; diff --git a/src/System.Private.CoreLib/shared/System/Text/EncoderBestFitFallback.cs b/src/System.Private.CoreLib/shared/System/Text/EncoderBestFitFallback.cs index 7f3be2a7a69..4aab3f62a33 100644 --- a/src/System.Private.CoreLib/shared/System/Text/EncoderBestFitFallback.cs +++ b/src/System.Private.CoreLib/shared/System/Text/EncoderBestFitFallback.cs @@ -38,7 +38,7 @@ public override int MaxCharCount } } - public override bool Equals(Object value) + public override bool Equals(object value) { InternalEncoderBestFitFallback that = value as InternalEncoderBestFitFallback; if (that != null) @@ -63,15 +63,15 @@ internal sealed class InternalEncoderBestFitFallbackBuffer : EncoderFallbackBuff private int _iSize; // Private object for locking instead of locking on a public type for SQL reliability work. - private static Object s_InternalSyncObject; - private static Object InternalSyncObject + private static object s_InternalSyncObject; + private static object InternalSyncObject { get { if (s_InternalSyncObject == null) { - Object o = new Object(); - Interlocked.CompareExchange(ref s_InternalSyncObject, o, null); + object o = new object(); + Interlocked.CompareExchange(ref s_InternalSyncObject, o, null); } return s_InternalSyncObject; } @@ -113,12 +113,12 @@ public override bool Fallback(char charUnknown, int index) public override bool Fallback(char charUnknownHigh, char charUnknownLow, int index) { // Double check input surrogate pair - if (!Char.IsHighSurrogate(charUnknownHigh)) + if (!char.IsHighSurrogate(charUnknownHigh)) throw new ArgumentOutOfRangeException(nameof(charUnknownHigh), SR.Format(SR.ArgumentOutOfRange_Range, 0xD800, 0xDBFF)); - if (!Char.IsLowSurrogate(charUnknownLow)) + if (!char.IsLowSurrogate(charUnknownLow)) throw new ArgumentOutOfRangeException(nameof(charUnknownLow), SR.Format(SR.ArgumentOutOfRange_Range, 0xDC00, 0xDFFF)); diff --git a/src/System.Private.CoreLib/shared/System/Text/EncoderExceptionFallback.cs b/src/System.Private.CoreLib/shared/System/Text/EncoderExceptionFallback.cs index 66de1940f64..92afcf701ac 100644 --- a/src/System.Private.CoreLib/shared/System/Text/EncoderExceptionFallback.cs +++ b/src/System.Private.CoreLib/shared/System/Text/EncoderExceptionFallback.cs @@ -28,7 +28,7 @@ public override int MaxCharCount } } - public override bool Equals(Object value) + public override bool Equals(object value) { EncoderExceptionFallback that = value as EncoderExceptionFallback; if (that != null) @@ -57,18 +57,18 @@ public override bool Fallback(char charUnknown, int index) public override bool Fallback(char charUnknownHigh, char charUnknownLow, int index) { - if (!Char.IsHighSurrogate(charUnknownHigh)) + if (!char.IsHighSurrogate(charUnknownHigh)) { throw new ArgumentOutOfRangeException(nameof(charUnknownHigh), SR.Format(SR.ArgumentOutOfRange_Range, 0xD800, 0xDBFF)); } - if (!Char.IsLowSurrogate(charUnknownLow)) + if (!char.IsLowSurrogate(charUnknownLow)) { throw new ArgumentOutOfRangeException(nameof(charUnknownLow), SR.Format(SR.ArgumentOutOfRange_Range, 0xDC00, 0xDFFF)); } - int iTemp = Char.ConvertToUtf32(charUnknownHigh, charUnknownLow); + int iTemp = char.ConvertToUtf32(charUnknownHigh, charUnknownLow); // Fall back our char throw new EncoderFallbackException( @@ -111,34 +111,34 @@ public EncoderFallbackException() HResult = HResults.COR_E_ARGUMENT; } - public EncoderFallbackException(String message) + public EncoderFallbackException(string message) : base(message) { HResult = HResults.COR_E_ARGUMENT; } - public EncoderFallbackException(String message, Exception innerException) + public EncoderFallbackException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_ARGUMENT; } internal EncoderFallbackException( - String message, char charUnknown, int index) : base(message) + string message, char charUnknown, int index) : base(message) { _charUnknown = charUnknown; _index = index; } internal EncoderFallbackException( - String message, char charUnknownHigh, char charUnknownLow, int index) : base(message) + string message, char charUnknownHigh, char charUnknownLow, int index) : base(message) { - if (!Char.IsHighSurrogate(charUnknownHigh)) + if (!char.IsHighSurrogate(charUnknownHigh)) { throw new ArgumentOutOfRangeException(nameof(charUnknownHigh), SR.Format(SR.ArgumentOutOfRange_Range, 0xD800, 0xDBFF)); } - if (!Char.IsLowSurrogate(charUnknownLow)) + if (!char.IsLowSurrogate(charUnknownLow)) { throw new ArgumentOutOfRangeException(nameof(CharUnknownLow), SR.Format(SR.ArgumentOutOfRange_Range, 0xDC00, 0xDFFF)); diff --git a/src/System.Private.CoreLib/shared/System/Text/EncoderFallback.cs b/src/System.Private.CoreLib/shared/System/Text/EncoderFallback.cs index d860a02a76a..f98b15e0786 100644 --- a/src/System.Private.CoreLib/shared/System/Text/EncoderFallback.cs +++ b/src/System.Private.CoreLib/shared/System/Text/EncoderFallback.cs @@ -142,7 +142,7 @@ internal unsafe virtual bool InternalFallback(char ch, ref char* chars) int index = (int)(chars - charStart) - 1; // See if it was a high surrogate - if (Char.IsHighSurrogate(ch)) + if (char.IsHighSurrogate(ch)) { // See if there's a low surrogate to go with it if (chars >= this.charEnd) @@ -165,11 +165,11 @@ internal unsafe virtual bool InternalFallback(char ch, ref char* chars) { // Might have a low surrogate char cNext = *chars; - if (Char.IsLowSurrogate(cNext)) + if (char.IsLowSurrogate(cNext)) { // If already falling back then fail if (bFallingBack && iRecursionCount++ > iMaxRecursion) - ThrowLastCharRecursive(Char.ConvertToUtf32(ch, cNext)); + ThrowLastCharRecursive(char.ConvertToUtf32(ch, cNext)); // Next is a surrogate, add it as surrogate pair, and increment chars chars++; diff --git a/src/System.Private.CoreLib/shared/System/Text/EncoderReplacementFallback.cs b/src/System.Private.CoreLib/shared/System/Text/EncoderReplacementFallback.cs index a1d0bbcd95a..760c280fde3 100644 --- a/src/System.Private.CoreLib/shared/System/Text/EncoderReplacementFallback.cs +++ b/src/System.Private.CoreLib/shared/System/Text/EncoderReplacementFallback.cs @@ -11,14 +11,14 @@ namespace System.Text public sealed class EncoderReplacementFallback : EncoderFallback { // Our variables - private String _strDefault; + private string _strDefault; // Construction. Default replacement fallback uses no best fit and ? replacement string public EncoderReplacementFallback() : this("?") { } - public EncoderReplacementFallback(String replacement) + public EncoderReplacementFallback(string replacement) { // Must not be null if (replacement == null) @@ -29,10 +29,10 @@ public EncoderReplacementFallback(String replacement) 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)) + if (char.IsHighSurrogate(replacement, i)) { // if already had a high one, stop if (bFoundHigh) @@ -63,7 +63,7 @@ public EncoderReplacementFallback(String replacement) _strDefault = replacement; } - public String DefaultString + public string DefaultString { get { @@ -85,7 +85,7 @@ public override int MaxCharCount } } - public override bool Equals(Object value) + public override bool Equals(object value) { EncoderReplacementFallback that = value as EncoderReplacementFallback; if (that != null) @@ -106,7 +106,7 @@ public override int GetHashCode() public sealed class EncoderReplacementFallbackBuffer : EncoderFallbackBuffer { // Store our default string - private String _strDefault; + private string _strDefault; private int _fallbackCount = -1; private int _fallbackIndex = -1; @@ -127,7 +127,7 @@ public override bool Fallback(char charUnknown, int index) // 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])); + ThrowLastCharRecursive(char.ConvertToUtf32(charUnknown, _strDefault[_fallbackIndex + 1])); // Nope, just one character ThrowLastCharRecursive(unchecked((int)charUnknown)); @@ -144,18 +144,18 @@ public override bool Fallback(char charUnknown, int index) public override bool Fallback(char charUnknownHigh, char charUnknownLow, int index) { // Double check input surrogate pair - if (!Char.IsHighSurrogate(charUnknownHigh)) + if (!char.IsHighSurrogate(charUnknownHigh)) throw new ArgumentOutOfRangeException(nameof(charUnknownHigh), SR.Format(SR.ArgumentOutOfRange_Range, 0xD800, 0xDBFF)); - if (!Char.IsLowSurrogate(charUnknownLow)) + if (!char.IsLowSurrogate(charUnknownLow)) throw new ArgumentOutOfRangeException(nameof(charUnknownLow), SR.Format(SR.ArgumentOutOfRange_Range, 0xDC00, 0xDFFF)); // If we had a buffer already we're being recursive, throw, it's probably at the suspect // character in our array. if (_fallbackCount >= 1) - ThrowLastCharRecursive(Char.ConvertToUtf32(charUnknownHigh, charUnknownLow)); + ThrowLastCharRecursive(char.ConvertToUtf32(charUnknownHigh, charUnknownLow)); // Go ahead and get our fallback _fallbackCount = _strDefault.Length; diff --git a/src/System.Private.CoreLib/shared/System/Text/Encoding.cs b/src/System.Private.CoreLib/shared/System/Text/Encoding.cs index a67859f2339..005f08afd7e 100644 --- a/src/System.Private.CoreLib/shared/System/Text/Encoding.cs +++ b/src/System.Private.CoreLib/shared/System/Text/Encoding.cs @@ -603,7 +603,7 @@ public DecoderFallback DecoderFallback } - public virtual Object Clone() + public virtual object Clone() { Encoding newEncoding = (Encoding)this.MemberwiseClone(); @@ -1241,7 +1241,7 @@ public virtual string GetString(byte[] bytes, int index, int count) 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) @@ -1325,7 +1325,7 @@ public DefaultEncoder(Encoding encoding) _encoding = encoding; } - public Object GetRealObject(StreamingContext context) + public object GetRealObject(StreamingContext context) { throw new PlatformNotSupportedException(); } @@ -1390,7 +1390,7 @@ public DefaultDecoder(Encoding encoding) _encoding = encoding; } - public Object GetRealObject(StreamingContext context) + public object GetRealObject(StreamingContext context) { throw new PlatformNotSupportedException(); } diff --git a/src/System.Private.CoreLib/shared/System/Text/EncodingInfo.cs b/src/System.Private.CoreLib/shared/System/Text/EncodingInfo.cs index 99995f759b2..8e71e58fab4 100644 --- a/src/System.Private.CoreLib/shared/System/Text/EncodingInfo.cs +++ b/src/System.Private.CoreLib/shared/System/Text/EncodingInfo.cs @@ -53,7 +53,7 @@ public Encoding GetEncoding() return Encoding.GetEncoding(iCodePage); } - public override bool Equals(Object value) + public override bool Equals(object value) { EncodingInfo that = value as EncodingInfo; if (that != null) diff --git a/src/System.Private.CoreLib/shared/System/Text/EncodingNLS.cs b/src/System.Private.CoreLib/shared/System/Text/EncodingNLS.cs index bbd2dd62886..e6fa0627d3e 100644 --- a/src/System.Private.CoreLib/shared/System/Text/EncodingNLS.cs +++ b/src/System.Private.CoreLib/shared/System/Text/EncodingNLS.cs @@ -61,7 +61,7 @@ public override unsafe int GetByteCount(char[] chars, int index, int count) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe - public override unsafe int GetByteCount(String s) + public override unsafe int GetByteCount(string s) { // Validate input if (s==null) @@ -91,7 +91,7 @@ public override unsafe int GetByteCount(char* chars, int count) // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding - public override unsafe int GetBytes(String s, int charIndex, int charCount, + public override unsafe int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (s == null || bytes == null) diff --git a/src/System.Private.CoreLib/shared/System/Text/EncodingProvider.cs b/src/System.Private.CoreLib/shared/System/Text/EncodingProvider.cs index ce8c3e02087..4d15eea01a2 100644 --- a/src/System.Private.CoreLib/shared/System/Text/EncodingProvider.cs +++ b/src/System.Private.CoreLib/shared/System/Text/EncodingProvider.cs @@ -130,7 +130,7 @@ internal static Encoding GetEncodingFromProvider(string encodingName, EncoderFal return null; } - private static Object s_InternalSyncObject = new Object(); + private static object s_InternalSyncObject = new object(); private static volatile EncodingProvider[] s_providers; } } diff --git a/src/System.Private.CoreLib/shared/System/Text/Latin1Encoding.cs b/src/System.Private.CoreLib/shared/System/Text/Latin1Encoding.cs index bd49a337b93..736fff5d260 100644 --- a/src/System.Private.CoreLib/shared/System/Text/Latin1Encoding.cs +++ b/src/System.Private.CoreLib/shared/System/Text/Latin1Encoding.cs @@ -42,7 +42,7 @@ internal override unsafe int GetByteCount(char* chars, int charCount, EncoderNLS if (encoder != null) { charLeftOver = encoder._charLeftOver; - Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver), + Debug.Assert(charLeftOver == 0 || char.IsHighSurrogate(charLeftOver), "[Latin1Encoding.GetByteCount]leftover character should be high surrogate"); fallback = encoder.Fallback as EncoderReplacementFallback; @@ -164,7 +164,7 @@ internal override unsafe int GetByteCount(char* chars, int charCount, EncoderNLS { charLeftOver = encoder._charLeftOver; fallback = encoder.Fallback as EncoderReplacementFallback; - Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver), + Debug.Assert(charLeftOver == 0 || char.IsHighSurrogate(charLeftOver), "[Latin1Encoding.GetBytes]leftover character should be high surrogate"); // Verify that we have no fallbackbuffer, for ASCII its always empty, so just assert diff --git a/src/System.Private.CoreLib/shared/System/Text/StringBuilder.cs b/src/System.Private.CoreLib/shared/System/Text/StringBuilder.cs index bbdfb39f219..99021e2dda3 100644 --- a/src/System.Private.CoreLib/shared/System/Text/StringBuilder.cs +++ b/src/System.Private.CoreLib/shared/System/Text/StringBuilder.cs @@ -201,7 +201,7 @@ private StringBuilder(SerializationInfo info, StreamingContext context) int persistedCapacity = 0; string persistedString = null; - int persistedMaxCapacity = Int32.MaxValue; + int persistedMaxCapacity = int.MaxValue; bool capacityPresent = false; // Get the data @@ -1431,7 +1431,7 @@ public StringBuilder Insert(int index, char[] value, int startIndex, int charCou [CLSCompliant(false)] public StringBuilder Insert(int index, ulong value) => Insert(index, value.ToString(), 1); - public StringBuilder Insert(int index, Object value) => (value == null) ? this : Insert(index, value.ToString(), 1); + public StringBuilder Insert(int index, object value) => (value == null) ? this : Insert(index, value.ToString(), 1); public StringBuilder Insert(int index, ReadOnlySpan value) { @@ -1451,13 +1451,13 @@ public StringBuilder Insert(int index, ReadOnlySpan value) return this; } - public StringBuilder AppendFormat(string format, Object arg0) => AppendFormatHelper(null, format, new ParamsArray(arg0)); + public StringBuilder AppendFormat(string format, object arg0) => AppendFormatHelper(null, format, new ParamsArray(arg0)); - public StringBuilder AppendFormat(string format, Object arg0, Object arg1) => AppendFormatHelper(null, format, new ParamsArray(arg0, arg1)); + public StringBuilder AppendFormat(string format, object arg0, object arg1) => AppendFormatHelper(null, format, new ParamsArray(arg0, arg1)); - public StringBuilder AppendFormat(string format, Object arg0, Object arg1, Object arg2) => AppendFormatHelper(null, format, new ParamsArray(arg0, arg1, arg2)); + public StringBuilder AppendFormat(string format, object arg0, object arg1, object arg2) => 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) { @@ -1470,13 +1470,13 @@ public StringBuilder AppendFormat(string format, params Object[] args) return AppendFormatHelper(null, format, new ParamsArray(args)); } - public StringBuilder AppendFormat(IFormatProvider provider, string format, Object arg0) => AppendFormatHelper(provider, format, new ParamsArray(arg0)); + public StringBuilder AppendFormat(IFormatProvider provider, string format, object arg0) => AppendFormatHelper(provider, format, new ParamsArray(arg0)); - public StringBuilder AppendFormat(IFormatProvider provider, string format, Object arg0, Object arg1) => AppendFormatHelper(provider, format, new ParamsArray(arg0, arg1)); + public StringBuilder AppendFormat(IFormatProvider provider, string format, object arg0, object arg1) => AppendFormatHelper(provider, format, new ParamsArray(arg0, arg1)); - public StringBuilder AppendFormat(IFormatProvider provider, string format, Object arg0, Object arg1, Object arg2) => AppendFormatHelper(provider, format, new ParamsArray(arg0, arg1, arg2)); + public StringBuilder AppendFormat(IFormatProvider provider, string format, object arg0, object arg1, object arg2) => 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) { @@ -1634,7 +1634,7 @@ internal StringBuilder AppendFormatHelper(IFormatProvider provider, string forma // // Start of parsing of optional formatting parameter. // - Object arg = args[index]; + object arg = args[index]; string itemFormat = null; ReadOnlySpan itemFormatSpan = default; // used if itemFormat is null // Is current character a colon? which indicates start of formatting parameter. diff --git a/src/System.Private.CoreLib/shared/System/Text/UTF32Encoding.cs b/src/System.Private.CoreLib/shared/System/Text/UTF32Encoding.cs index 185eef16fe3..86169e6b16a 100644 --- a/src/System.Private.CoreLib/shared/System/Text/UTF32Encoding.cs +++ b/src/System.Private.CoreLib/shared/System/Text/UTF32Encoding.cs @@ -125,7 +125,7 @@ public override unsafe int GetByteCount(char[] chars, int index, int count) // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe - public override unsafe int GetByteCount(String s) + public override unsafe int GetByteCount(string s) { // Validate input if (s==null) @@ -158,7 +158,7 @@ public override unsafe int GetByteCount(char* chars, int count) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding - public override unsafe int GetBytes(String s, int charIndex, int charCount, + public override unsafe int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (s == null || bytes == null) @@ -417,7 +417,7 @@ internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS enc // // In previous char, we encounter a high surrogate, so we are expecting a low surrogate here. // - if (Char.IsLowSurrogate(ch)) + if (char.IsLowSurrogate(ch)) { // They're all legal highSurrogate = '\0'; @@ -447,7 +447,7 @@ internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS enc } // Do we have another high surrogate? - if (Char.IsHighSurrogate(ch)) + if (char.IsHighSurrogate(ch)) { // // We'll have a high surrogate to check next time. @@ -457,7 +457,7 @@ internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS enc } // Check for illegal characters - if (Char.IsLowSurrogate(ch)) + if (char.IsLowSurrogate(ch)) { // We have a leading low surrogate, do the fallback charsForFallback = chars; @@ -552,7 +552,7 @@ internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS enc // // In previous char, we encountered a high surrogate, so we are expecting a low surrogate here. // - if (Char.IsLowSurrogate(ch)) + if (char.IsLowSurrogate(ch)) { // Is it a legal one? uint iTemp = GetSurrogate(highSurrogate, ch); @@ -616,7 +616,7 @@ internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS enc } // Do we have another high surrogate?, if so remember it - if (Char.IsHighSurrogate(ch)) + if (char.IsHighSurrogate(ch)) { // // We'll have a high surrogate to check next time. @@ -626,7 +626,7 @@ internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS enc } // Check for illegal characters (low surrogate) - if (Char.IsLowSurrogate(ch)) + if (char.IsLowSurrogate(ch)) { // We have a leading low surrogate, do the fallback charsForFallback = chars; @@ -1159,7 +1159,7 @@ public override byte[] GetPreamble() _emitUTF32ByteOrderMark ? (_bigEndian ? s_bigEndianPreamble : s_littleEndianPreamble) : Array.Empty(); - public override bool Equals(Object value) + public override bool Equals(object value) { UTF32Encoding that = value as UTF32Encoding; if (that != null) diff --git a/src/System.Private.CoreLib/shared/System/Text/UTF7Encoding.cs b/src/System.Private.CoreLib/shared/System/Text/UTF7Encoding.cs index 3ed99b69b34..5c51c81076c 100644 --- a/src/System.Private.CoreLib/shared/System/Text/UTF7Encoding.cs +++ b/src/System.Private.CoreLib/shared/System/Text/UTF7Encoding.cs @@ -97,7 +97,7 @@ internal sealed override void SetDefaultFallbacks() this.decoderFallback = new DecoderUTF7Fallback(); } - public override bool Equals(Object value) + public override bool Equals(object value) { UTF7Encoding that = value as UTF7Encoding; if (that != null) @@ -873,7 +873,7 @@ public override int MaxCharCount } } - public override bool Equals(Object value) + public override bool Equals(object value) { DecoderUTF7Fallback that = value as DecoderUTF7Fallback; if (that != null) diff --git a/src/System.Private.CoreLib/shared/System/Text/UTF8Encoding.cs b/src/System.Private.CoreLib/shared/System/Text/UTF8Encoding.cs index b4594784c1f..c9e51f661e0 100644 --- a/src/System.Private.CoreLib/shared/System/Text/UTF8Encoding.cs +++ b/src/System.Private.CoreLib/shared/System/Text/UTF8Encoding.cs @@ -152,7 +152,7 @@ public override unsafe int GetByteCount(char[] chars, int index, int count) // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe - public override unsafe int GetByteCount(String chars) + public override unsafe int GetByteCount(string chars) { // Validate input if (chars==null) @@ -193,7 +193,7 @@ public override unsafe int GetByteCount(ReadOnlySpan chars) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding - public override unsafe int GetBytes(String s, int charIndex, int charCount, + public override unsafe int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (s == null || bytes == null) @@ -2553,7 +2553,7 @@ public override byte[] GetPreamble() _emitUTF8Identifier ? s_preamble : Array.Empty(); - public override bool Equals(Object value) + public override bool Equals(object value) { UTF8Encoding that = value as UTF8Encoding; if (that != null) diff --git a/src/System.Private.CoreLib/shared/System/Text/UnicodeEncoding.cs b/src/System.Private.CoreLib/shared/System/Text/UnicodeEncoding.cs index a94d243a7d0..6a27d2c8556 100644 --- a/src/System.Private.CoreLib/shared/System/Text/UnicodeEncoding.cs +++ b/src/System.Private.CoreLib/shared/System/Text/UnicodeEncoding.cs @@ -116,7 +116,7 @@ public override unsafe int GetByteCount(char[] chars, int index, int count) // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe - public override unsafe int GetByteCount(String s) + public override unsafe int GetByteCount(string s) { // Validate input if (s==null) @@ -149,7 +149,7 @@ public override unsafe int GetByteCount(char* chars, int count) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding - public override unsafe int GetBytes(String s, int charIndex, int charCount, + public override unsafe int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (s == null || bytes == null) @@ -1789,7 +1789,7 @@ public override byte[] GetPreamble() else return new byte[2] { 0xff, 0xfe }; } - return Array.Empty(); + return Array.Empty(); } public override ReadOnlySpan Preamble => @@ -1842,7 +1842,7 @@ public override int GetMaxCharCount(int byteCount) } - public override bool Equals(Object value) + public override bool Equals(object value) { UnicodeEncoding that = value as UnicodeEncoding; if (that != null) diff --git a/src/System.Private.CoreLib/shared/System/Threading/AbandonedMutexException.cs b/src/System.Private.CoreLib/shared/System/Threading/AbandonedMutexException.cs index c7e604f33dd..bd504dd27a7 100644 --- a/src/System.Private.CoreLib/shared/System/Threading/AbandonedMutexException.cs +++ b/src/System.Private.CoreLib/shared/System/Threading/AbandonedMutexException.cs @@ -27,13 +27,13 @@ public AbandonedMutexException() HResult = HResults.COR_E_ABANDONEDMUTEX; } - public AbandonedMutexException(String message) + public AbandonedMutexException(string message) : base(message) { HResult = HResults.COR_E_ABANDONEDMUTEX; } - public AbandonedMutexException(String message, Exception inner) + public AbandonedMutexException(string message, Exception inner) : base(message, inner) { HResult = HResults.COR_E_ABANDONEDMUTEX; @@ -46,14 +46,14 @@ public AbandonedMutexException(int location, WaitHandle handle) SetupException(location, handle); } - public AbandonedMutexException(String message, int location, WaitHandle handle) + public AbandonedMutexException(string message, int location, WaitHandle handle) : base(message) { HResult = HResults.COR_E_ABANDONEDMUTEX; SetupException(location, handle); } - public AbandonedMutexException(String message, Exception inner, int location, WaitHandle handle) + public AbandonedMutexException(string message, Exception inner, int location, WaitHandle handle) : base(message, inner) { HResult = HResults.COR_E_ABANDONEDMUTEX; diff --git a/src/System.Private.CoreLib/shared/System/Threading/ExecutionContext.cs b/src/System.Private.CoreLib/shared/System/Threading/ExecutionContext.cs index 975ed02d427..694514ef07e 100644 --- a/src/System.Private.CoreLib/shared/System/Threading/ExecutionContext.cs +++ b/src/System.Private.CoreLib/shared/System/Threading/ExecutionContext.cs @@ -19,7 +19,7 @@ namespace System.Threading { - public delegate void ContextCallback(Object state); + public delegate void ContextCallback(object state); public sealed class ExecutionContext : IDisposable, ISerializable { @@ -112,7 +112,7 @@ public static bool IsFlowSuppressed() internal bool IsDefault => m_isDefault; - public static void Run(ExecutionContext executionContext, ContextCallback callback, Object state) + public static void Run(ExecutionContext executionContext, ContextCallback callback, object state) { // Note: ExecutionContext.Run is an extremely hot function and used by every await, ThreadPool execution, etc. if (executionContext == null) @@ -123,7 +123,7 @@ public static void Run(ExecutionContext executionContext, ContextCallback callba RunInternal(executionContext, callback, state); } - internal static void RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state) + internal static void RunInternal(ExecutionContext executionContext, ContextCallback callback, object state) { // Note: ExecutionContext.RunInternal is an extremely hot function and used by every await, ThreadPool execution, etc. // Note: Manual enregistering may be addressed by "Exception Handling Write Through Optimization" diff --git a/src/System.Private.CoreLib/shared/System/Threading/ReaderWriterLockSlim.cs b/src/System.Private.CoreLib/shared/System/Threading/ReaderWriterLockSlim.cs index 45175488e7e..9424fbd5b49 100644 --- a/src/System.Private.CoreLib/shared/System/Threading/ReaderWriterLockSlim.cs +++ b/src/System.Private.CoreLib/shared/System/Threading/ReaderWriterLockSlim.cs @@ -241,7 +241,7 @@ private struct TimeoutTracker public TimeoutTracker(TimeSpan timeout) { long ltm = (long)timeout.TotalMilliseconds; - if (ltm < -1 || ltm > (long)Int32.MaxValue) + if (ltm < -1 || ltm > (long)int.MaxValue) throw new ArgumentOutOfRangeException(nameof(timeout)); _total = (int)ltm; if (_total != -1 && _total != 0) diff --git a/src/System.Private.CoreLib/shared/System/Threading/Semaphore.cs b/src/System.Private.CoreLib/shared/System/Threading/Semaphore.cs index 1135a1f911a..6014fcd1c84 100644 --- a/src/System.Private.CoreLib/shared/System/Threading/Semaphore.cs +++ b/src/System.Private.CoreLib/shared/System/Threading/Semaphore.cs @@ -12,7 +12,7 @@ namespace System.Threading public sealed partial class Semaphore : WaitHandle { // creates a nameless semaphore object - // Win32 only takes maximum count of Int32.MaxValue + // Win32 only takes maximum count of int.MaxValue public Semaphore(int initialCount, int maximumCount) : this(initialCount, maximumCount, null) { } public Semaphore(int initialCount, int maximumCount, string name) : diff --git a/src/System.Private.CoreLib/shared/System/Threading/SemaphoreFullException.cs b/src/System.Private.CoreLib/shared/System/Threading/SemaphoreFullException.cs index 18558b19e01..a6cff781df6 100644 --- a/src/System.Private.CoreLib/shared/System/Threading/SemaphoreFullException.cs +++ b/src/System.Private.CoreLib/shared/System/Threading/SemaphoreFullException.cs @@ -15,11 +15,11 @@ public SemaphoreFullException() : base(SR.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) { } diff --git a/src/System.Private.CoreLib/shared/System/Threading/SendOrPostCallback.cs b/src/System.Private.CoreLib/shared/System/Threading/SendOrPostCallback.cs index 6692d35ab2e..b96914ab2c6 100644 --- a/src/System.Private.CoreLib/shared/System/Threading/SendOrPostCallback.cs +++ b/src/System.Private.CoreLib/shared/System/Threading/SendOrPostCallback.cs @@ -4,5 +4,5 @@ namespace System.Threading { - public delegate void SendOrPostCallback(Object state); + public delegate void SendOrPostCallback(object state); } diff --git a/src/System.Private.CoreLib/shared/System/Threading/SpinWait.cs b/src/System.Private.CoreLib/shared/System/Threading/SpinWait.cs index 414ad1852f8..d23569294c4 100644 --- a/src/System.Private.CoreLib/shared/System/Threading/SpinWait.cs +++ b/src/System.Private.CoreLib/shared/System/Threading/SpinWait.cs @@ -255,7 +255,7 @@ public static void SpinUntil(Func condition) /// The argument is null. /// is a negative number /// other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater than - /// . + /// . public static bool SpinUntil(Func condition, TimeSpan timeout) { // Validate the timeout diff --git a/src/System.Private.CoreLib/shared/System/Threading/SynchronizationLockException.cs b/src/System.Private.CoreLib/shared/System/Threading/SynchronizationLockException.cs index e050e1539d0..3b5d31f3c03 100644 --- a/src/System.Private.CoreLib/shared/System/Threading/SynchronizationLockException.cs +++ b/src/System.Private.CoreLib/shared/System/Threading/SynchronizationLockException.cs @@ -26,13 +26,13 @@ public SynchronizationLockException() HResult = HResults.COR_E_SYNCHRONIZATIONLOCK; } - public SynchronizationLockException(String message) + public SynchronizationLockException(string message) : base(message) { HResult = HResults.COR_E_SYNCHRONIZATIONLOCK; } - public SynchronizationLockException(String message, Exception innerException) + public SynchronizationLockException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_SYNCHRONIZATIONLOCK; diff --git a/src/System.Private.CoreLib/shared/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs b/src/System.Private.CoreLib/shared/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs index 146e477e2ca..9e3b0bc28b3 100644 --- a/src/System.Private.CoreLib/shared/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs +++ b/src/System.Private.CoreLib/shared/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs @@ -62,7 +62,7 @@ public class ConcurrentExclusiveSchedulerPair /// Default MaxItemsPerTask to use for processing if none is specified. private const int DEFAULT_MAXITEMSPERTASK = UNLIMITED_PROCESSING; /// Default MaxConcurrencyLevel is the processor count if not otherwise specified. - private static Int32 DefaultMaxConcurrencyLevel { get { return Environment.ProcessorCount; } } + private static int DefaultMaxConcurrencyLevel { get { return Environment.ProcessorCount; } } /// Gets the sync obj used to protect all state on this instance. private object ValueLock { get { return m_threadProcessingMode; } } @@ -116,8 +116,8 @@ public ConcurrentExclusiveSchedulerPair(TaskScheduler taskScheduler, int maxConc // Treat UNLIMITED_PROCESSING/-1 for both MCL and MIPT as the biggest possible value so that we don't // have to special case UNLIMITED_PROCESSING later on in processing. - if (m_maxConcurrencyLevel == UNLIMITED_PROCESSING) m_maxConcurrencyLevel = Int32.MaxValue; - if (m_maxItemsPerTask == UNLIMITED_PROCESSING) m_maxItemsPerTask = Int32.MaxValue; + if (m_maxConcurrencyLevel == UNLIMITED_PROCESSING) m_maxConcurrencyLevel = int.MaxValue; + if (m_maxItemsPerTask == UNLIMITED_PROCESSING) m_maxItemsPerTask = int.MaxValue; // Create the concurrent/exclusive schedulers for this pair m_exclusiveTaskScheduler = new ConcurrentExclusiveTaskScheduler(this, 1, ProcessingMode.ProcessingExclusiveTask); diff --git a/src/System.Private.CoreLib/shared/System/Threading/ThreadInterruptedException.cs b/src/System.Private.CoreLib/shared/System/Threading/ThreadInterruptedException.cs index 33c1a431047..0d0288da248 100644 --- a/src/System.Private.CoreLib/shared/System/Threading/ThreadInterruptedException.cs +++ b/src/System.Private.CoreLib/shared/System/Threading/ThreadInterruptedException.cs @@ -24,13 +24,13 @@ public class ThreadInterruptedException : SystemException HResult = HResults.COR_E_THREADINTERRUPTED; } - public ThreadInterruptedException(String message) + public ThreadInterruptedException(string message) : base(message) { HResult = HResults.COR_E_THREADINTERRUPTED; } - public ThreadInterruptedException(String message, Exception innerException) + public ThreadInterruptedException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_THREADINTERRUPTED; diff --git a/src/System.Private.CoreLib/shared/System/Threading/ThreadStateException.cs b/src/System.Private.CoreLib/shared/System/Threading/ThreadStateException.cs index 6fc06a8516b..d9ba48dfc84 100644 --- a/src/System.Private.CoreLib/shared/System/Threading/ThreadStateException.cs +++ b/src/System.Private.CoreLib/shared/System/Threading/ThreadStateException.cs @@ -26,13 +26,13 @@ public ThreadStateException() HResult = HResults.COR_E_THREADSTATE; } - public ThreadStateException(String message) + public ThreadStateException(string message) : base(message) { HResult = HResults.COR_E_THREADSTATE; } - public ThreadStateException(String message, Exception innerException) + public ThreadStateException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_THREADSTATE; diff --git a/src/System.Private.CoreLib/shared/System/Threading/WaitHandleCannotBeOpenedException.cs b/src/System.Private.CoreLib/shared/System/Threading/WaitHandleCannotBeOpenedException.cs index e60e46d2be5..60821542b5f 100644 --- a/src/System.Private.CoreLib/shared/System/Threading/WaitHandleCannotBeOpenedException.cs +++ b/src/System.Private.CoreLib/shared/System/Threading/WaitHandleCannotBeOpenedException.cs @@ -15,12 +15,12 @@ public WaitHandleCannotBeOpenedException() : base(SR.Threading_WaitHandleCannotB HResult = HResults.COR_E_WAITHANDLECANNOTBEOPENED; } - public WaitHandleCannotBeOpenedException(String message) : base(message) + public WaitHandleCannotBeOpenedException(string message) : base(message) { HResult = HResults.COR_E_WAITHANDLECANNOTBEOPENED; } - public WaitHandleCannotBeOpenedException(String message, Exception innerException) : base(message, innerException) + public WaitHandleCannotBeOpenedException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_WAITHANDLECANNOTBEOPENED; } diff --git a/src/System.Private.CoreLib/shared/System/TimeSpan.cs b/src/System.Private.CoreLib/shared/System/TimeSpan.cs index f9b9c17f01a..4716ab6c140 100644 --- a/src/System.Private.CoreLib/shared/System/TimeSpan.cs +++ b/src/System.Private.CoreLib/shared/System/TimeSpan.cs @@ -50,18 +50,18 @@ public struct TimeSpan : IComparable, IComparable, IEquatable MaxMilliSeconds || totalMilliSeconds < MinMilliSeconds) throw new ArgumentOutOfRangeException(null, SR.Overflow_TimeSpanTooLong); _ticks = (long)totalMilliSeconds * TicksPerMillisecond; @@ -178,7 +178,7 @@ public static int Compare(TimeSpan t1, TimeSpan t2) } // 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)) @@ -209,7 +209,7 @@ public TimeSpan Duration() return new TimeSpan(_ticks >= 0 ? _ticks : -_ticks); } - public override bool Equals(Object value) + public override bool Equals(object value) { if (value is TimeSpan) { @@ -240,11 +240,11 @@ public static TimeSpan FromHours(double value) private static TimeSpan Interval(double value, int scale) { - if (Double.IsNaN(value)) + if (double.IsNaN(value)) throw new ArgumentException(SR.Arg_CannotBeNaN); double tmp = value * scale; double millis = tmp + (value >= 0 ? 0.5 : -0.5); - if ((millis > Int64.MaxValue / TicksPerMillisecond) || (millis < Int64.MinValue / TicksPerMillisecond)) + if ((millis > long.MaxValue / TicksPerMillisecond) || (millis < long.MinValue / TicksPerMillisecond)) throw new OverflowException(SR.Overflow_TimeSpanTooLong); return new TimeSpan((long)millis * TicksPerMillisecond); } @@ -305,18 +305,18 @@ internal static long TimeToTicks(int hour, int minute, int second) // See System.Globalization.TimeSpanParse and System.Globalization.TimeSpanFormat #region ParseAndFormat - private static void ValidateStyles(TimeSpanStyles style, String parameterName) + private static void ValidateStyles(TimeSpanStyles style, string parameterName) { if (style != TimeSpanStyles.None && style != TimeSpanStyles.AssumeNegative) throw new ArgumentException(SR.Argument_InvalidTimeSpanStyles, parameterName); } - public static TimeSpan Parse(String s) + public static TimeSpan Parse(string s) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); /* Constructs a TimeSpan from a string. Leading and trailing white space characters are allowed. */ return TimeSpanParse.Parse(s, null); } - public static TimeSpan Parse(String input, IFormatProvider formatProvider) + public static TimeSpan Parse(string input, IFormatProvider formatProvider) { if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); return TimeSpanParse.Parse(input, formatProvider); @@ -325,18 +325,18 @@ public static TimeSpan Parse(ReadOnlySpan input, IFormatProvider formatPro { 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) { if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); if (format == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.format); return TimeSpanParse.ParseExact(input, format, formatProvider, TimeSpanStyles.None); } - public static TimeSpan ParseExact(String input, String[] formats, IFormatProvider formatProvider) + public static TimeSpan ParseExact(string input, string[] formats, IFormatProvider formatProvider) { if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); return TimeSpanParse.ParseExactMultiple(input, formats, formatProvider, TimeSpanStyles.None); } - public static TimeSpan ParseExact(String input, String format, IFormatProvider formatProvider, TimeSpanStyles styles) + public static TimeSpan ParseExact(string input, string format, IFormatProvider formatProvider, TimeSpanStyles styles) { ValidateStyles(styles, nameof(styles)); if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); @@ -349,7 +349,7 @@ public static TimeSpan ParseExact(ReadOnlySpan input, ReadOnlySpan f 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) { ValidateStyles(styles, nameof(styles)); if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); @@ -360,7 +360,7 @@ public static TimeSpan ParseExact(ReadOnlySpan input, string[] formats, IF ValidateStyles(styles, nameof(styles)); return TimeSpanParse.ParseExactMultiple(input, formats, formatProvider, styles); } - public static Boolean TryParse(String s, out TimeSpan result) + public static bool TryParse(string s, out TimeSpan result) { if (s == null) { @@ -374,7 +374,7 @@ public static bool TryParse(ReadOnlySpan s, out TimeSpan result) return TimeSpanParse.TryParse(s, null, out result); } - public static Boolean TryParse(String input, IFormatProvider formatProvider, out TimeSpan result) + public static bool TryParse(string input, IFormatProvider formatProvider, out TimeSpan result) { if (input == null) { @@ -387,7 +387,7 @@ public static bool TryParse(ReadOnlySpan input, IFormatProvider formatProv { return TimeSpanParse.TryParse(input, formatProvider, out result); } - public static Boolean TryParseExact(String input, String format, IFormatProvider formatProvider, out TimeSpan result) + public static bool TryParseExact(string input, string format, IFormatProvider formatProvider, out TimeSpan result) { if (input == null || format == null) { @@ -401,7 +401,7 @@ public static bool TryParseExact(ReadOnlySpan input, ReadOnlySpan fo { 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 bool TryParseExact(string input, string[] formats, IFormatProvider formatProvider, out TimeSpan result) { if (input == null) { @@ -415,7 +415,7 @@ public static bool TryParseExact(ReadOnlySpan input, string[] formats, IFo 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 bool TryParseExact(string input, string format, IFormatProvider formatProvider, TimeSpanStyles styles, out TimeSpan result) { ValidateStyles(styles, nameof(styles)); if (input == null || format == null) @@ -432,7 +432,7 @@ public static bool TryParseExact(ReadOnlySpan input, ReadOnlySpan fo 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 bool TryParseExact(string input, string[] formats, IFormatProvider formatProvider, TimeSpanStyles styles, out TimeSpan result) { ValidateStyles(styles, nameof(styles)); if (input == null) @@ -448,15 +448,15 @@ public static bool TryParseExact(ReadOnlySpan input, string[] formats, IFo 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) + public string ToString(string format, IFormatProvider formatProvider) { return TimeSpanFormat.Format(this, format, formatProvider); } diff --git a/src/System.Private.CoreLib/shared/System/TimeZone.cs b/src/System.Private.CoreLib/shared/System/TimeZone.cs index d4059babfc3..010db8090f4 100644 --- a/src/System.Private.CoreLib/shared/System/TimeZone.cs +++ b/src/System.Private.CoreLib/shared/System/TimeZone.cs @@ -32,15 +32,15 @@ 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 + private static object s_InternalSyncObject; + private static object InternalSyncObject { get { if (s_InternalSyncObject == null) { - Object o = new Object(); - Interlocked.CompareExchange(ref s_InternalSyncObject, o, null); + object o = new object(); + Interlocked.CompareExchange(ref s_InternalSyncObject, o, null); } return s_InternalSyncObject; } @@ -87,12 +87,12 @@ internal static void ResetTimeZone() } } - public abstract String StandardName + public abstract string StandardName { get; } - public abstract String DaylightName + public abstract string DaylightName { get; } @@ -129,8 +129,8 @@ public virtual DateTime ToLocalTime(DateTime time) { return time; } - Boolean isAmbiguousLocalDst = false; - Int64 offset = ((CurrentSystemTimeZone)(TimeZone.CurrentTimeZone)).GetUtcOffsetFromUniversalTime(time, ref isAmbiguousLocalDst); + bool isAmbiguousLocalDst = false; + long offset = ((CurrentSystemTimeZone)(TimeZone.CurrentTimeZone)).GetUtcOffsetFromUniversalTime(time, ref isAmbiguousLocalDst); return new DateTime(time.Ticks + offset, DateTimeKind.Local, isAmbiguousLocalDst); } @@ -247,7 +247,7 @@ internal static TimeSpan CalculateUtcOffset(DateTime time, DaylightTime daylight ambiguousEnd = startTime - daylightTimes.Delta; } - Boolean isDst = false; + bool isDst = false; if (startTime > endTime) { // In southern hemisphere, the daylight saving time starts later in the year, and ends in the beginning of next year. diff --git a/src/System.Private.CoreLib/shared/System/TimeZoneNotFoundException.cs b/src/System.Private.CoreLib/shared/System/TimeZoneNotFoundException.cs index f83c6443c34..3dc1bb1d4cd 100644 --- a/src/System.Private.CoreLib/shared/System/TimeZoneNotFoundException.cs +++ b/src/System.Private.CoreLib/shared/System/TimeZoneNotFoundException.cs @@ -14,12 +14,12 @@ public TimeZoneNotFoundException() { } - public TimeZoneNotFoundException(String message) + public TimeZoneNotFoundException(string message) : base(message) { } - public TimeZoneNotFoundException(String message, Exception innerException) + public TimeZoneNotFoundException(string message, Exception innerException) : base(message, innerException) { } diff --git a/src/System.Private.CoreLib/shared/System/TimeoutException.cs b/src/System.Private.CoreLib/shared/System/TimeoutException.cs index ddaa47747d2..2480f4bc28a 100644 --- a/src/System.Private.CoreLib/shared/System/TimeoutException.cs +++ b/src/System.Private.CoreLib/shared/System/TimeoutException.cs @@ -25,13 +25,13 @@ public TimeoutException() HResult = HResults.COR_E_TIMEOUT; } - public TimeoutException(String message) + public TimeoutException(string message) : base(message) { HResult = HResults.COR_E_TIMEOUT; } - public TimeoutException(String message, Exception innerException) + public TimeoutException(string message, Exception innerException) : base(message, innerException) { HResult = HResults.COR_E_TIMEOUT; diff --git a/src/System.Private.CoreLib/shared/System/Tuple.cs b/src/System.Private.CoreLib/shared/System/Tuple.cs index 2d027cd40ca..ebbd156dda4 100644 --- a/src/System.Private.CoreLib/shared/System/Tuple.cs +++ b/src/System.Private.CoreLib/shared/System/Tuple.cs @@ -115,12 +115,12 @@ public Tuple(T1 item1) m_Item1 = item1; } - public override Boolean Equals(Object obj) + public override bool Equals(object obj) { - return ((IStructuralEquatable)this).Equals(obj, EqualityComparer.Default); + return ((IStructuralEquatable)this).Equals(obj, EqualityComparer.Default); } - Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) + bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) { if (other == null) return false; @@ -134,12 +134,12 @@ Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) return comparer.Equals(m_Item1, objTuple.m_Item1); } - Int32 IComparable.CompareTo(Object obj) + int IComparable.CompareTo(object obj) { - return ((IStructuralComparable)this).CompareTo(obj, Comparer.Default); + return ((IStructuralComparable)this).CompareTo(obj, Comparer.Default); } - Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) + int IStructuralComparable.CompareTo(object other, IComparer comparer) { if (other == null) return 1; @@ -155,15 +155,15 @@ Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) public override int GetHashCode() { - return ((IStructuralEquatable)this).GetHashCode(EqualityComparer.Default); + return ((IStructuralEquatable)this).GetHashCode(EqualityComparer.Default); } - Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) + int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return comparer.GetHashCode(m_Item1); } - Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer) + int ITupleInternal.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } @@ -218,12 +218,12 @@ public Tuple(T1 item1, T2 item2) m_Item2 = item2; } - public override Boolean Equals(Object obj) + public override bool Equals(object obj) { - return ((IStructuralEquatable)this).Equals(obj, EqualityComparer.Default); ; + return ((IStructuralEquatable)this).Equals(obj, EqualityComparer.Default); ; } - Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) + bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) { if (other == null) return false; @@ -237,12 +237,12 @@ Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2); } - Int32 IComparable.CompareTo(Object obj) + int IComparable.CompareTo(object obj) { - return ((IStructuralComparable)this).CompareTo(obj, Comparer.Default); + return ((IStructuralComparable)this).CompareTo(obj, Comparer.Default); } - Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) + int IStructuralComparable.CompareTo(object other, IComparer comparer) { if (other == null) return 1; @@ -264,15 +264,15 @@ Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) public override int GetHashCode() { - return ((IStructuralEquatable)this).GetHashCode(EqualityComparer.Default); + return ((IStructuralEquatable)this).GetHashCode(EqualityComparer.Default); } - Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) + int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2)); } - Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer) + int ITupleInternal.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } @@ -336,12 +336,12 @@ public Tuple(T1 item1, T2 item2, T3 item3) m_Item3 = item3; } - public override Boolean Equals(Object obj) + public override bool Equals(object obj) { - return ((IStructuralEquatable)this).Equals(obj, EqualityComparer.Default); ; + return ((IStructuralEquatable)this).Equals(obj, EqualityComparer.Default); ; } - Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) + bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) { if (other == null) return false; @@ -355,12 +355,12 @@ Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3); } - Int32 IComparable.CompareTo(Object obj) + int IComparable.CompareTo(object obj) { - return ((IStructuralComparable)this).CompareTo(obj, Comparer.Default); + return ((IStructuralComparable)this).CompareTo(obj, Comparer.Default); } - Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) + int IStructuralComparable.CompareTo(object other, IComparer comparer) { if (other == null) return 1; @@ -386,15 +386,15 @@ Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) public override int GetHashCode() { - return ((IStructuralEquatable)this).GetHashCode(EqualityComparer.Default); + return ((IStructuralEquatable)this).GetHashCode(EqualityComparer.Default); } - Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) + int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3)); } - Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer) + int ITupleInternal.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } @@ -465,12 +465,12 @@ public Tuple(T1 item1, T2 item2, T3 item3, T4 item4) m_Item4 = item4; } - public override Boolean Equals(Object obj) + public override bool Equals(object obj) { - return ((IStructuralEquatable)this).Equals(obj, EqualityComparer.Default); ; + return ((IStructuralEquatable)this).Equals(obj, EqualityComparer.Default); ; } - Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) + bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) { if (other == null) return false; @@ -484,12 +484,12 @@ Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3) && comparer.Equals(m_Item4, objTuple.m_Item4); } - Int32 IComparable.CompareTo(Object obj) + int IComparable.CompareTo(object obj) { - return ((IStructuralComparable)this).CompareTo(obj, Comparer.Default); + return ((IStructuralComparable)this).CompareTo(obj, Comparer.Default); } - Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) + int IStructuralComparable.CompareTo(object other, IComparer comparer) { if (other == null) return 1; @@ -519,15 +519,15 @@ Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) public override int GetHashCode() { - return ((IStructuralEquatable)this).GetHashCode(EqualityComparer.Default); + return ((IStructuralEquatable)this).GetHashCode(EqualityComparer.Default); } - Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) + int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4)); } - Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer) + int ITupleInternal.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } @@ -605,12 +605,12 @@ public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5) m_Item5 = item5; } - public override Boolean Equals(Object obj) + public override bool Equals(object obj) { - return ((IStructuralEquatable)this).Equals(obj, EqualityComparer.Default); ; + return ((IStructuralEquatable)this).Equals(obj, EqualityComparer.Default); ; } - Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) + bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) { if (other == null) return false; @@ -624,12 +624,12 @@ Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3) && comparer.Equals(m_Item4, objTuple.m_Item4) && comparer.Equals(m_Item5, objTuple.m_Item5); } - Int32 IComparable.CompareTo(Object obj) + int IComparable.CompareTo(object obj) { - return ((IStructuralComparable)this).CompareTo(obj, Comparer.Default); + return ((IStructuralComparable)this).CompareTo(obj, Comparer.Default); } - Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) + int IStructuralComparable.CompareTo(object other, IComparer comparer) { if (other == null) return 1; @@ -663,15 +663,15 @@ Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) public override int GetHashCode() { - return ((IStructuralEquatable)this).GetHashCode(EqualityComparer.Default); + return ((IStructuralEquatable)this).GetHashCode(EqualityComparer.Default); } - Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) + int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5)); } - Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer) + int ITupleInternal.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } @@ -756,12 +756,12 @@ public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6) m_Item6 = item6; } - public override Boolean Equals(Object obj) + public override bool Equals(object obj) { - return ((IStructuralEquatable)this).Equals(obj, EqualityComparer.Default); ; + return ((IStructuralEquatable)this).Equals(obj, EqualityComparer.Default); ; } - Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) + bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) { if (other == null) return false; @@ -775,12 +775,12 @@ Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3) && comparer.Equals(m_Item4, objTuple.m_Item4) && comparer.Equals(m_Item5, objTuple.m_Item5) && comparer.Equals(m_Item6, objTuple.m_Item6); } - Int32 IComparable.CompareTo(Object obj) + int IComparable.CompareTo(object obj) { - return ((IStructuralComparable)this).CompareTo(obj, Comparer.Default); + return ((IStructuralComparable)this).CompareTo(obj, Comparer.Default); } - Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) + int IStructuralComparable.CompareTo(object other, IComparer comparer) { if (other == null) return 1; @@ -818,15 +818,15 @@ Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) public override int GetHashCode() { - return ((IStructuralEquatable)this).GetHashCode(EqualityComparer.Default); + return ((IStructuralEquatable)this).GetHashCode(EqualityComparer.Default); } - Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) + int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6)); } - Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer) + int ITupleInternal.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } @@ -918,12 +918,12 @@ public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item m_Item7 = item7; } - public override Boolean Equals(Object obj) + public override bool Equals(object obj) { - return ((IStructuralEquatable)this).Equals(obj, EqualityComparer.Default); ; + return ((IStructuralEquatable)this).Equals(obj, EqualityComparer.Default); ; } - Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) + bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) { if (other == null) return false; @@ -937,12 +937,12 @@ Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3) && comparer.Equals(m_Item4, objTuple.m_Item4) && comparer.Equals(m_Item5, objTuple.m_Item5) && comparer.Equals(m_Item6, objTuple.m_Item6) && comparer.Equals(m_Item7, objTuple.m_Item7); } - Int32 IComparable.CompareTo(Object obj) + int IComparable.CompareTo(object obj) { - return ((IStructuralComparable)this).CompareTo(obj, Comparer.Default); + return ((IStructuralComparable)this).CompareTo(obj, Comparer.Default); } - Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) + int IStructuralComparable.CompareTo(object other, IComparer comparer) { if (other == null) return 1; @@ -984,15 +984,15 @@ Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) public override int GetHashCode() { - return ((IStructuralEquatable)this).GetHashCode(EqualityComparer.Default); + return ((IStructuralEquatable)this).GetHashCode(EqualityComparer.Default); } - Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) + int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7)); } - Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer) + int ITupleInternal.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } @@ -1096,12 +1096,12 @@ public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item m_Rest = rest; } - public override Boolean Equals(Object obj) + public override bool Equals(object obj) { - return ((IStructuralEquatable)this).Equals(obj, EqualityComparer.Default); ; + return ((IStructuralEquatable)this).Equals(obj, EqualityComparer.Default); ; } - Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) + bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) { if (other == null) return false; @@ -1115,12 +1115,12 @@ Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) return comparer.Equals(m_Item1, objTuple.m_Item1) && comparer.Equals(m_Item2, objTuple.m_Item2) && comparer.Equals(m_Item3, objTuple.m_Item3) && comparer.Equals(m_Item4, objTuple.m_Item4) && comparer.Equals(m_Item5, objTuple.m_Item5) && comparer.Equals(m_Item6, objTuple.m_Item6) && comparer.Equals(m_Item7, objTuple.m_Item7) && comparer.Equals(m_Rest, objTuple.m_Rest); } - Int32 IComparable.CompareTo(Object obj) + int IComparable.CompareTo(object obj) { - return ((IStructuralComparable)this).CompareTo(obj, Comparer.Default); + return ((IStructuralComparable)this).CompareTo(obj, Comparer.Default); } - Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) + int IStructuralComparable.CompareTo(object other, IComparer comparer) { if (other == null) return 1; @@ -1166,10 +1166,10 @@ Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) public override int GetHashCode() { - return ((IStructuralEquatable)this).GetHashCode(EqualityComparer.Default); + return ((IStructuralEquatable)this).GetHashCode(EqualityComparer.Default); } - Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) + int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { // We want to have a limited hash in this case. We'll use the last 8 elements of the tuple ITupleInternal t = (ITupleInternal)m_Rest; @@ -1198,7 +1198,7 @@ Int32 IStructuralEquatable.GetHashCode(IEqualityComparer comparer) return -1; } - Int32 ITupleInternal.GetHashCode(IEqualityComparer comparer) + int ITupleInternal.GetHashCode(IEqualityComparer comparer) { return ((IStructuralEquatable)this).GetHashCode(comparer); } diff --git a/src/System.Private.CoreLib/shared/System/UInt16.cs b/src/System.Private.CoreLib/shared/System/UInt16.cs index 3047d18198e..cd09894c626 100644 --- a/src/System.Private.CoreLib/shared/System/UInt16.cs +++ b/src/System.Private.CoreLib/shared/System/UInt16.cs @@ -13,7 +13,7 @@ namespace System [CLSCompliant(false)] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] - public struct UInt16 : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable + public struct UInt16 : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable { private ushort m_value; // Do not rename (binary serialization) @@ -27,35 +27,35 @@ public struct UInt16 : IComparable, IConvertible, IFormattable, IComparable destination, out int charsWritten, ReadOnlySpan } [CLSCompliant(false)] - public static ushort Parse(String s) + public static ushort Parse(string s) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan)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); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); @@ -110,14 +110,14 @@ public static ushort Parse(String s, NumberStyles style) [CLSCompliant(false)] - public static ushort Parse(String s, IFormatProvider provider) + public static ushort Parse(string s, IFormatProvider provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan)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); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); @@ -148,7 +148,7 @@ private static ushort Parse(ReadOnlySpan s, NumberStyles style, NumberForm } [CLSCompliant(false)] - public static bool TryParse(String s, out UInt16 result) + public static bool TryParse(string s, out ushort result) { if (s == null) { @@ -166,7 +166,7 @@ public static bool TryParse(ReadOnlySpan s, out ushort 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 ushort result) { NumberFormatInfo.ValidateParseStyleInteger(style); @@ -186,10 +186,10 @@ public static bool TryParse(ReadOnlySpan s, NumberStyles style, IFormatPro return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result); } - private static bool TryParse(ReadOnlySpan s, NumberStyles style, NumberFormatInfo info, out UInt16 result) + private static bool TryParse(ReadOnlySpan s, NumberStyles style, NumberFormatInfo info, out ushort result) { result = 0; - UInt32 i; + uint i; if (!Number.TryParseUInt32(s, style, info, out i)) { return false; @@ -198,7 +198,7 @@ private static bool TryParse(ReadOnlySpan s, NumberStyles style, NumberFor { return false; } - result = (UInt16)i; + result = (ushort)i; return true; } @@ -271,7 +271,7 @@ float IConvertible.ToSingle(IFormatProvider provider) return Convert.ToDouble(m_value); } - Decimal IConvertible.ToDecimal(IFormatProvider provider) + decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } @@ -281,7 +281,7 @@ DateTime IConvertible.ToDateTime(IFormatProvider provider) throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "UInt16", "DateTime")); } - 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/System.Private.CoreLib/shared/System/UInt32.cs b/src/System.Private.CoreLib/shared/System/UInt32.cs index 1e33dcf17ba..d72a0a19562 100644 --- a/src/System.Private.CoreLib/shared/System/UInt32.cs +++ b/src/System.Private.CoreLib/shared/System/UInt32.cs @@ -13,7 +13,7 @@ namespace System [CLSCompliant(false)] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] - public struct UInt32 : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable + public struct UInt32 : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable { private uint m_value; // Do not rename (binary serialization) @@ -27,13 +27,13 @@ public struct UInt32 : IComparable, IConvertible, IFormattable, IComparable destination, out int charsWritten, ReadOnlySpan } [CLSCompliant(false)] - public static uint Parse(String s) + public static uint Parse(string s) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.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); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); @@ -118,14 +118,14 @@ public static uint Parse(String s, NumberStyles style) [CLSCompliant(false)] - public static uint Parse(String s, IFormatProvider provider) + public static uint Parse(string s, IFormatProvider provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); 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); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); @@ -140,7 +140,7 @@ public static uint Parse(ReadOnlySpan s, NumberStyles style = NumberStyles } [CLSCompliant(false)] - public static bool TryParse(String s, out UInt32 result) + public static bool TryParse(string s, out uint result) { if (s == null) { @@ -158,7 +158,7 @@ public static bool TryParse(ReadOnlySpan s, out uint 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 uint result) { NumberFormatInfo.ValidateParseStyleInteger(style); @@ -247,7 +247,7 @@ float IConvertible.ToSingle(IFormatProvider provider) return Convert.ToDouble(m_value); } - Decimal IConvertible.ToDecimal(IFormatProvider provider) + decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } @@ -257,7 +257,7 @@ DateTime IConvertible.ToDateTime(IFormatProvider provider) throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "UInt32", "DateTime")); } - 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/System.Private.CoreLib/shared/System/UInt64.cs b/src/System.Private.CoreLib/shared/System/UInt64.cs index d30fbe1e42b..3b1010a51f4 100644 --- a/src/System.Private.CoreLib/shared/System/UInt64.cs +++ b/src/System.Private.CoreLib/shared/System/UInt64.cs @@ -13,7 +13,7 @@ namespace System [CLSCompliant(false)] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] - public struct UInt64 : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable + public struct UInt64 : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable { private ulong m_value; // Do not rename (binary serialization) @@ -26,13 +26,13 @@ public struct UInt64 : IComparable, IConvertible, IFormattable, IComparable> 32); } - public override String ToString() + public override string ToString() { return Number.FormatUInt64(m_value, null, null); } - public String ToString(IFormatProvider provider) + public string ToString(IFormatProvider provider) { return Number.FormatUInt64(m_value, null, provider); } - public String ToString(String format) + public string ToString(string format) { return Number.FormatUInt64(m_value, format, null); } - public String ToString(String format, IFormatProvider provider) + public string ToString(string format, IFormatProvider provider) { return Number.FormatUInt64(m_value, format, provider); } @@ -100,14 +100,14 @@ public bool TryFormat(Span destination, out int charsWritten, ReadOnlySpan } [CLSCompliant(false)] - public static ulong Parse(String s) + public static ulong Parse(string s) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.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); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); @@ -122,7 +122,7 @@ public static ulong Parse(string s, IFormatProvider 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); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); @@ -137,7 +137,7 @@ public static ulong Parse(ReadOnlySpan s, NumberStyles style = NumberStyle } [CLSCompliant(false)] - public static Boolean TryParse(String s, out UInt64 result) + public static bool TryParse(string s, out ulong result) { if (s == null) { @@ -155,7 +155,7 @@ public static bool TryParse(ReadOnlySpan s, out ulong result) } [CLSCompliant(false)] - public static Boolean TryParse(String s, NumberStyles style, IFormatProvider provider, out UInt64 result) + public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, out ulong result) { NumberFormatInfo.ValidateParseStyleInteger(style); @@ -244,7 +244,7 @@ float IConvertible.ToSingle(IFormatProvider provider) return Convert.ToDouble(m_value); } - Decimal IConvertible.ToDecimal(IFormatProvider provider) + decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } @@ -254,7 +254,7 @@ DateTime IConvertible.ToDateTime(IFormatProvider provider) throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "UInt64", "DateTime")); } - 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/System.Private.CoreLib/shared/System/UIntPtr.cs b/src/System.Private.CoreLib/shared/System/UIntPtr.cs index 8b2568fde1e..484eef4b61b 100644 --- a/src/System.Private.CoreLib/shared/System/UIntPtr.cs +++ b/src/System.Private.CoreLib/shared/System/UIntPtr.cs @@ -68,7 +68,7 @@ unsafe void ISerializable.GetObjectData(SerializationInfo info, StreamingContext info.AddValue("value", ToUInt64()); } - public unsafe override bool Equals(Object obj) + public unsafe override bool Equals(object obj) { if (obj is UIntPtr) { diff --git a/src/System.Private.CoreLib/shared/System/UnauthorizedAccessException.cs b/src/System.Private.CoreLib/shared/System/UnauthorizedAccessException.cs index a28f6dd73ce..e384dfeb315 100644 --- a/src/System.Private.CoreLib/shared/System/UnauthorizedAccessException.cs +++ b/src/System.Private.CoreLib/shared/System/UnauthorizedAccessException.cs @@ -29,13 +29,13 @@ public UnauthorizedAccessException() HResult = HResults.COR_E_UNAUTHORIZEDACCESS; } - public UnauthorizedAccessException(String message) + public UnauthorizedAccessException(string message) : base(message) { HResult = HResults.COR_E_UNAUTHORIZEDACCESS; } - public UnauthorizedAccessException(String message, Exception inner) + public UnauthorizedAccessException(string message, Exception inner) : base(message, inner) { HResult = HResults.COR_E_UNAUTHORIZEDACCESS; diff --git a/src/System.Private.CoreLib/shared/System/UnhandledExceptionEventArgs.cs b/src/System.Private.CoreLib/shared/System/UnhandledExceptionEventArgs.cs index 5cde5721616..c214afdc711 100644 --- a/src/System.Private.CoreLib/shared/System/UnhandledExceptionEventArgs.cs +++ b/src/System.Private.CoreLib/shared/System/UnhandledExceptionEventArgs.cs @@ -6,16 +6,16 @@ namespace System { public class UnhandledExceptionEventArgs : EventArgs { - private Object _exception; + private object _exception; private bool _isTerminating; - public UnhandledExceptionEventArgs(Object exception, bool isTerminating) + public UnhandledExceptionEventArgs(object exception, bool isTerminating) { _exception = exception; _isTerminating = isTerminating; } - public Object ExceptionObject + public object ExceptionObject { get { return _exception; } } diff --git a/src/System.Private.CoreLib/shared/System/UnhandledExceptionEventHandler.cs b/src/System.Private.CoreLib/shared/System/UnhandledExceptionEventHandler.cs index 14e31c7bbde..58f1eb5145d 100644 --- a/src/System.Private.CoreLib/shared/System/UnhandledExceptionEventHandler.cs +++ b/src/System.Private.CoreLib/shared/System/UnhandledExceptionEventHandler.cs @@ -4,5 +4,5 @@ namespace System { - public delegate void UnhandledExceptionEventHandler(Object sender, UnhandledExceptionEventArgs e); + public delegate void UnhandledExceptionEventHandler(object sender, UnhandledExceptionEventArgs e); } diff --git a/src/System.Private.CoreLib/shared/System/Version.cs b/src/System.Private.CoreLib/shared/System/Version.cs index 6bdf969f173..9d24270eb3a 100644 --- a/src/System.Private.CoreLib/shared/System/Version.cs +++ b/src/System.Private.CoreLib/shared/System/Version.cs @@ -73,7 +73,7 @@ public Version(int major, int minor) _Minor = minor; } - public Version(String version) + public Version(string version) { Version v = Version.Parse(version); _Major = v.Major; @@ -134,7 +134,7 @@ public short MinorRevision get { return (short)(_Revision & 0xFFFF); } } - public int CompareTo(Object version) + public int CompareTo(object version) { if (version == null) { @@ -162,7 +162,7 @@ public int CompareTo(Version value) 0; } - public override bool Equals(Object obj) + public override bool Equals(object obj) { return Equals(obj as Version); } @@ -422,14 +422,14 @@ private static bool TryParseComponent(ReadOnlySpan component, string compo public static bool operator <(Version v1, Version v2) { - if ((Object)v1 == null) + if ((object)v1 == null) throw new ArgumentNullException(nameof(v1)); return (v1.CompareTo(v2) < 0); } public static bool operator <=(Version v1, Version v2) { - if ((Object)v1 == null) + if ((object)v1 == null) throw new ArgumentNullException(nameof(v1)); return (v1.CompareTo(v2) <= 0); } From c101f3e39d77ce14939cd532258170b8f1ded80b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michal=20Strehovsk=C3=BD?= Date: Sun, 24 Jun 2018 16:04:06 +0200 Subject: [PATCH 13/69] Update CoreCLR.issues.targets (#6003) These tests started failing after RyuJIT update in #5969. ``` at System.Diagnostics.Debug.Assert(Boolean condition, String message, String detailMessage) at Internal.JitInterface.CorInfoImpl.convertPInvokeCalliToCall(CORINFO_RESOLVED_TOKEN& pResolvedToken, Boolean mustConvert) in D:\j\workspace\debug_windows_nt28ae10f6\src\JitInterface\src\CorInfoImpl.cs:line 3453 at Internal.JitInterface.CorInfoImpl._convertPInvokeCalliToCall(IntPtr thisHandle, IntPtr* ppException, CORINFO_RESOLVED_TOKEN& pResolvedToken, Boolean mustConvert) in D:\j\workspace\debug_windows_nt28ae10f6\src\JitInterface\src\CorInfoBase.cs:line 2488 ``` --- tests/CoreCLR.issues.targets | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/tests/CoreCLR.issues.targets b/tests/CoreCLR.issues.targets index d7b9ad48603..a2efda51848 100644 --- a/tests/CoreCLR.issues.targets +++ b/tests/CoreCLR.issues.targets @@ -2,6 +2,12 @@ xmlns="http://schemas.microsoft.com/developer/msbuild/2003" > + + + + + + From 280fedd8343f69dfe8823eb1d27ec6983204eea4 Mon Sep 17 00:00:00 2001 From: Jan Kotas Date: Sun, 24 Jun 2018 10:32:31 -0700 Subject: [PATCH 14/69] Update dependencies (#6006) --- dependencies.props | 8 ++++---- src/Framework/Framework.depproj | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/dependencies.props b/dependencies.props index 64bc52ed3f6..228c65c950c 100644 --- a/dependencies.props +++ b/dependencies.props @@ -1,10 +1,10 @@ - 2.2.0-preview1-26620-01 + 3.0.0-preview1-26624-03 1.0.0-alpha-26412-0 - 4.6.0-preview1-26621-04 - 4.7.0-preview1-26621-04 - 2.2.0-preview1-26620-01 + 4.6.0-preview1-26624-03 + 4.7.0-preview1-26624-03 + 3.0.0-preview1-26624-03 2.1.0 1.0.1-prerelease-02104-02 diff --git a/src/Framework/Framework.depproj b/src/Framework/Framework.depproj index fb064e4def7..2199f01022c 100644 --- a/src/Framework/Framework.depproj +++ b/src/Framework/Framework.depproj @@ -5,8 +5,8 @@ - .NETCoreApp,Version=v2.2 - netcoreapp2.2 + .NETCoreApp,Version=v3.0 + netcoreapp3.0 $(NuPkgRid) true From 89982841836cb7c54198673537502049dc2c39fe Mon Sep 17 00:00:00 2001 From: Jan Kotas Date: Sun, 24 Jun 2018 10:32:39 -0700 Subject: [PATCH 15/69] Update to latest released dotnet SDK (#6005) --- DotnetCLIVersion.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DotnetCLIVersion.txt b/DotnetCLIVersion.txt index 9d572733d28..5e908d682fa 100644 --- a/DotnetCLIVersion.txt +++ b/DotnetCLIVersion.txt @@ -1 +1 @@ -2.1.300-rc1-008673 +2.1.301 From a4c6faac2c31bffc6f13287c6cb8c6a7bb9667fd Mon Sep 17 00:00:00 2001 From: Stephen Toub Date: Sun, 24 Jun 2018 23:21:25 -0400 Subject: [PATCH 16/69] Simplify types in non-shared corelib (#6008) --- .../NativeFormat/NativeFormatReader.cs | 2 +- .../CompilerHelpers/StartupCodeHelpers.cs | 2 +- src/Common/src/Internal/Runtime/EEType.cs | 160 ++++++------ .../src/Internal/Runtime/ModuleHeaders.cs | 14 +- .../advapi32/Interop.RegDeleteValue.cs | 2 +- .../Windows/mincore/Interop.MemAllocFree.cs | 2 +- .../Windows/mincore/Interop.MemReAlloc.cs | 2 +- .../Windows/mincore/Interop.RegCreateKeyEx.cs | 4 +- .../mincore/Interop.RegQueryValueEx.cs | 6 +- .../Concurrent/ConcurrentUnifier.cs | 2 +- .../Concurrent/ConcurrentUnifierW.cs | 2 +- .../Concurrent/ConcurrentUnifierWKeyed.cs | 2 +- src/Common/src/System/CommonRuntimeTypes.cs | 30 +-- .../System/Numerics/Hashing/HashHelpers.cs | 2 +- src/Common/src/System/SR.cs | 18 +- .../System/Runtime/CachedInterfaceDispatch.cs | 2 +- .../System/Runtime/CastableObjectSupport.cs | 4 +- .../src/System/Runtime/DispatchResolve.cs | 10 +- .../src/System/Runtime/InternalCalls.cs | 26 +- .../src/System/Runtime/RuntimeExports.cs | 14 +- .../src/System/Runtime/TypeCast.cs | 18 +- .../src/System/Runtime/__Finalizer.cs | 2 +- .../Diagnostics/Tracing/StubEnvironment.cs | 2 +- .../shared/System/IO/TextWriter.cs | 6 +- .../DeveloperExperience.cs | 12 +- .../IntrinsicSupport/ComparerHelpers.cs | 6 +- .../EqualityComparerHelpers.cs | 8 +- .../Reflection/ExplicitScopeAttribute.cs | 2 +- .../CustomAttributeInstantiator.cs | 14 +- .../ReflectionExecutionDomainCallbacks.cs | 2 +- .../Runtime/Augments/RuntimeAugments.cs | 48 ++-- .../Runtime/Augments/RuntimeThread.cs | 4 +- .../Runtime/CompilerHelpers/InteropHelpers.cs | 16 +- .../Runtime/CompilerHelpers/MathHelpers.cs | 90 +++---- .../SynchronizedMethodHelpers.cs | 2 +- .../RelocatedTypeAttribute.cs | 2 +- .../src/Internal/Runtime/ThreadStatics.cs | 10 +- .../Threading/Tasks/AsyncCausalitySupport.cs | 2 +- .../Microsoft/Win32/RegistryKey.Windows.cs | 8 +- .../src/System/AppContext.cs | 2 +- .../src/System/AppContextDefaultValues.cs | 10 +- .../src/System/Array.CoreRT.cs | 46 ++-- .../src/System/Array.cs | 92 +++---- .../src/System/Attribute.cs | 24 +- .../Generic/CompatibilityEqualityComparers.cs | 2 +- .../Collections/Generic/EqualOnlyComparer.cs | 52 ++-- .../src/System/Decimal.DecCalc.cs | 60 ++--- .../src/System/Decimal.cs | 232 +++++++++--------- .../src/System/DefaultBinder.CanConvert.cs | 2 +- .../src/System/Delegate.DefaultParameters.cs | 4 +- .../src/System/Delegate.cs | 26 +- .../System/Diagnostics/Contracts/Contracts.cs | 52 ++-- .../Diagnostics/Contracts/ContractsBCL.cs | 38 +-- .../src/System/Diagnostics/Debug.Windows.cs | 2 +- .../src/System/Diagnostics/Debugger.cs | 4 +- .../Diagnostics/Tracing/EventSource_CoreRT.cs | 4 +- .../Tracing/UnsafeNativeMethods.cs | 2 +- .../src/System/EETypePtr.cs | 2 +- src/System.Private.CoreLib/src/System/Enum.cs | 190 +++++++------- .../src/System/Environment.cs | 10 +- .../src/System/Exception.cs | 54 ++-- src/System.Private.CoreLib/src/System/GC.cs | 18 +- .../Globalization/CultureInfo.Windows.cs | 2 +- .../src/System/Globalization/CultureInfo.cs | 44 ++-- .../src/System/InvokeUtils.cs | 8 +- .../src/System/MulticastDelegate.cs | 14 +- .../src/System/Number.CoreRT.cs | 10 +- .../src/System/Object.cs | 8 +- .../System/Reflection/AssemblyNameLexer.cs | 10 +- .../System/Reflection/AssemblyNameParser.cs | 32 +-- .../System/Reflection/RuntimeAssemblyName.cs | 12 +- .../Resources/FileBasedResourceGroveler.cs | 14 +- .../src/System/Resources/IResourceGroveler.cs | 2 +- .../ManifestBasedResourceGroveler.cs | 14 +- .../src/System/Resources/ResourceManager.cs | 24 +- .../src/System/Resources/ResourceReader.cs | 60 ++--- .../src/System/Resources/ResourceSet.cs | 30 +-- .../CompilerServices/AsyncMethodBuilder.cs | 2 +- .../ClassConstructorRunner.cs | 4 +- .../CompilerServices/ConditionalWeakTable.cs | 2 +- .../CompilerServices/RuntimeHelpers.cs | 14 +- .../Runtime/InteropServices/GCHandle.cs | 16 +- .../InteropServices/InteropExtensions.cs | 18 +- .../System/Runtime/InteropServices/Marshal.cs | 4 +- .../Runtime/InteropServices/PInvokeMarshal.cs | 12 +- .../Runtime/InteropServices/UnsafeGCHandle.cs | 6 +- .../src/System/Runtime/RuntimeImports.cs | 40 +-- .../src/System/Runtime/TypeLoaderExports.cs | 20 +- .../src/System/RuntimeExceptionHelpers.cs | 22 +- .../src/System/RuntimeFieldHandle.cs | 2 +- .../src/System/RuntimeMethodHandle.cs | 2 +- .../src/System/RuntimeTypeHandle.cs | 8 +- .../src/System/String.CoreRT.cs | 4 +- .../src/System/Text/EncodingData.cs | 4 +- .../src/System/Text/StringBuilder.CoreRT.cs | 2 +- .../src/System/Threading/CancellationToken.cs | 14 +- .../Threading/CancellationTokenSource.cs | 10 +- .../src/System/Threading/Interlocked.cs | 4 +- .../src/System/Threading/ManagedThreadId.cs | 6 +- .../System/Threading/ManualResetEventSlim.cs | 8 +- .../src/System/Threading/Monitor.cs | 36 +-- .../src/System/Threading/SemaphoreSlim.cs | 16 +- .../src/System/Threading/SpinLock.cs | 6 +- .../Threading/SynchronizationContext.cs | 4 +- .../Threading/Tasks/DebuggerSupport.Dummy.cs | 2 +- .../System/Threading/Tasks/DebuggerSupport.cs | 2 +- .../src/System/Threading/Tasks/Future.cs | 24 +- .../System/Threading/Tasks/FutureFactory.cs | 8 +- .../Threading/Tasks/ProducerConsumerQueues.cs | 6 +- .../src/System/Threading/Tasks/Task.cs | 36 +-- .../src/System/Threading/Tasks/TaskFactory.cs | 16 +- .../System/Threading/Tasks/TaskScheduler.cs | 10 +- .../System/Threading/ThreadPool.Windows.cs | 2 +- .../src/System/Threading/ThreadPool.cs | 44 ++-- .../src/System/Threading/Timer.Unix.cs | 2 +- .../src/System/Threading/Timer.cs | 44 ++-- .../src/System/Threading/Volatile.cs | 102 ++++---- .../src/System/TimeZoneInfo.WinRT.cs | 20 +- .../src/System/ValueType.cs | 2 +- .../src/System/WeakReference.cs | 14 +- .../src/System/WeakReferenceOfT.cs | 2 +- 121 files changed, 1197 insertions(+), 1197 deletions(-) diff --git a/src/Common/src/Internal/NativeFormat/NativeFormatReader.cs b/src/Common/src/Internal/NativeFormat/NativeFormatReader.cs index beb49d93210..f10028e4fdc 100644 --- a/src/Common/src/Internal/NativeFormat/NativeFormatReader.cs +++ b/src/Common/src/Internal/NativeFormat/NativeFormatReader.cs @@ -223,7 +223,7 @@ internal unsafe partial class NativeReader public NativeReader(byte* base_, uint size) { // Limit the maximum blob size to prevent buffer overruns triggered by boundary integer overflows - if (size >= UInt32.MaxValue / 4) + if (size >= uint.MaxValue / 4) ThrowBadImageFormatException(); Debug.Assert(base_ <= base_ + size); diff --git a/src/Common/src/Internal/Runtime/CompilerHelpers/StartupCodeHelpers.cs b/src/Common/src/Internal/Runtime/CompilerHelpers/StartupCodeHelpers.cs index d5192c4b554..b7e299219be 100644 --- a/src/Common/src/Internal/Runtime/CompilerHelpers/StartupCodeHelpers.cs +++ b/src/Common/src/Internal/Runtime/CompilerHelpers/StartupCodeHelpers.cs @@ -304,6 +304,6 @@ private static unsafe void InitializeStatics(IntPtr gcStaticRegionStart, int len internal unsafe struct TypeManagerSlot { public TypeManagerHandle TypeManager; - public Int32 ModuleIndex; + public int ModuleIndex; } } diff --git a/src/Common/src/Internal/Runtime/EEType.cs b/src/Common/src/Internal/Runtime/EEType.cs index c9852dd80a1..635448ef938 100644 --- a/src/Common/src/Internal/Runtime/EEType.cs +++ b/src/Common/src/Internal/Runtime/EEType.cs @@ -63,12 +63,12 @@ internal unsafe struct DispatchMap [StructLayout(LayoutKind.Sequential)] internal unsafe struct DispatchMapEntry { - internal UInt16 _usInterfaceIndex; - internal UInt16 _usInterfaceMethodSlot; - internal UInt16 _usImplMethodSlot; + internal ushort _usInterfaceIndex; + internal ushort _usInterfaceMethodSlot; + internal ushort _usImplMethodSlot; } - private UInt32 _entryCount; + private uint _entryCount; private DispatchMapEntry _dispatchMap; // at least one entry if any interfaces defined public bool IsEmpty @@ -79,7 +79,7 @@ public bool IsEmpty } } - public UInt32 NumEntries + public uint NumEntries { get { @@ -97,7 +97,7 @@ public int Size { get { - return sizeof(UInt32) + sizeof(DispatchMapEntry) * (int)_entryCount; + return sizeof(uint) + sizeof(DispatchMapEntry) * (int)_entryCount; } } @@ -106,7 +106,7 @@ public int Size get { fixed (DispatchMap* pThis = &this) - return (DispatchMapEntry*)((byte*)pThis + sizeof(UInt32) + (sizeof(DispatchMapEntry) * index)); + return (DispatchMapEntry*)((byte*)pThis + sizeof(uint) + (sizeof(DispatchMapEntry) * index)); } } } @@ -147,7 +147,7 @@ private unsafe struct RelatedTypeUnion private static unsafe class OptionalFieldsReader { - internal static UInt32 GetInlineField(byte* pFields, EETypeOptionalFieldTag eTag, UInt32 uiDefaultValue) + internal static uint GetInlineField(byte* pFields, EETypeOptionalFieldTag eTag, uint uiDefaultValue) { if (pFields == null) return uiDefaultValue; @@ -158,7 +158,7 @@ internal static UInt32 GetInlineField(byte* pFields, EETypeOptionalFieldTag eTag byte fieldHeader = NativePrimitiveDecoder.ReadUInt8(ref pFields); isLastField = (fieldHeader & 0x80) != 0; EETypeOptionalFieldTag eCurrentTag = (EETypeOptionalFieldTag)(fieldHeader & 0x7f); - UInt32 uiCurrentValue = NativePrimitiveDecoder.DecodeUnsigned(ref pFields); + uint uiCurrentValue = NativePrimitiveDecoder.DecodeUnsigned(ref pFields); // If we found a tag match return the current value. if (eCurrentTag == eTag) @@ -170,13 +170,13 @@ internal static UInt32 GetInlineField(byte* pFields, EETypeOptionalFieldTag eTag } } - private UInt16 _usComponentSize; - private UInt16 _usFlags; - private UInt32 _uBaseSize; + private ushort _usComponentSize; + private ushort _usFlags; + private uint _uBaseSize; private RelatedTypeUnion _relatedType; - private UInt16 _usNumVtableSlots; - private UInt16 _usNumInterfaces; - private UInt32 _uHashCode; + private ushort _usNumVtableSlots; + private ushort _usNumInterfaces; + private uint _uHashCode; #if EETYPE_TYPE_MANAGER private IntPtr _ppTypeManager; @@ -187,14 +187,14 @@ internal static UInt32 GetInlineField(byte* pFields, EETypeOptionalFieldTag eTag // if the alignment is 8 bytes or less. If the alignment is higher then there may be a need for more bits to hold // the rest of the padding data. // If paddings of greater than 7 bytes are necessary, then the high bits of the field represent that padding - private const UInt32 ValueTypePaddingLowMask = 0x7; - private const UInt32 ValueTypePaddingHighMask = 0xFFFFFF00; - private const UInt32 ValueTypePaddingMax = 0x07FFFFFF; + private const uint ValueTypePaddingLowMask = 0x7; + private const uint ValueTypePaddingHighMask = 0xFFFFFF00; + private const uint ValueTypePaddingMax = 0x07FFFFFF; private const int ValueTypePaddingHighShift = 8; - private const UInt32 ValueTypePaddingAlignmentMask = 0xF8; + private const uint ValueTypePaddingAlignmentMask = 0xF8; private const int ValueTypePaddingAlignmentShift = 3; - internal UInt16 ComponentSize + internal ushort ComponentSize { get { @@ -208,7 +208,7 @@ internal UInt16 ComponentSize #endif } - internal UInt16 GenericArgumentCount + internal ushort GenericArgumentCount { get { @@ -224,7 +224,7 @@ internal UInt16 GenericArgumentCount #endif } - internal UInt16 Flags + internal ushort Flags { get { @@ -238,7 +238,7 @@ internal UInt16 Flags #endif } - internal UInt32 BaseSize + internal uint BaseSize { get { @@ -252,7 +252,7 @@ internal UInt32 BaseSize #endif } - internal UInt16 NumVtableSlots + internal ushort NumVtableSlots { get { @@ -266,7 +266,7 @@ internal UInt16 NumVtableSlots #endif } - internal UInt16 NumInterfaces + internal ushort NumInterfaces { get { @@ -280,7 +280,7 @@ internal UInt16 NumInterfaces #endif } - internal UInt32 HashCode + internal uint HashCode { get { @@ -298,7 +298,7 @@ private EETypeKind Kind { get { - return (EETypeKind)(_usFlags & (UInt16)EETypeFlags.EETypeKindMask); + return (EETypeKind)(_usFlags & (ushort)EETypeFlags.EETypeKindMask); } } @@ -306,7 +306,7 @@ internal bool HasOptionalFields { get { - return ((_usFlags & (UInt16)EETypeFlags.OptionalFieldsFlag) != 0); + return ((_usFlags & (ushort)EETypeFlags.OptionalFieldsFlag) != 0); } } @@ -316,7 +316,7 @@ internal bool HasGenericVariance { get { - return ((_usFlags & (UInt16)EETypeFlags.GenericVarianceFlag) != 0); + return ((_usFlags & (ushort)EETypeFlags.GenericVarianceFlag) != 0); } } @@ -399,7 +399,7 @@ internal bool IsGeneric { get { - return ((_usFlags & (UInt16)EETypeFlags.IsGenericFlag) != 0); + return ((_usFlags & (ushort)EETypeFlags.IsGenericFlag) != 0); } } @@ -416,7 +416,7 @@ internal bool IsGenericTypeDefinition get { Debug.Assert(IsGeneric); - UInt32 cbOffset = GetFieldOffset(EETypeField.ETF_GenericDefinition); + uint cbOffset = GetFieldOffset(EETypeField.ETF_GenericDefinition); fixed (EEType* pThis = &this) { return ((EETypeRef*)((byte*)pThis + cbOffset))->Value; @@ -440,11 +440,11 @@ internal uint GenericArity get { Debug.Assert(IsGeneric); - UInt32 cbOffset = GetFieldOffset(EETypeField.ETF_GenericComposition); + uint cbOffset = GetFieldOffset(EETypeField.ETF_GenericComposition); fixed (EEType* pThis = &this) { // Number of generic arguments is the first UInt16 of the composition stream. - return **(UInt16**)((byte*)pThis + cbOffset); + return **(ushort**)((byte*)pThis + cbOffset); } } } @@ -454,7 +454,7 @@ internal uint GenericArity get { Debug.Assert(IsGeneric); - UInt32 cbOffset = GetFieldOffset(EETypeField.ETF_GenericComposition); + uint cbOffset = GetFieldOffset(EETypeField.ETF_GenericComposition); fixed (EEType* pThis = &this) { // Generic arguments follow after a (padded) UInt16 specifying their count @@ -473,7 +473,7 @@ internal uint GenericArity if (!HasGenericVariance) return null; - UInt32 cbOffset = GetFieldOffset(EETypeField.ETF_GenericComposition); + uint cbOffset = GetFieldOffset(EETypeField.ETF_GenericComposition); fixed (EEType* pThis = &this) { // Variance info follows immediatelly after the generic arguments @@ -504,7 +504,7 @@ internal bool IsInterface { get { - return ((_usFlags & (UInt16)EETypeFlags.IsInterfaceFlag) != 0); + return ((_usFlags & (ushort)EETypeFlags.IsInterfaceFlag) != 0); } } @@ -561,7 +561,7 @@ internal bool IsParameterizedType // Currently, the meaning is a shape of 0 indicates that this is a Pointer, // shape of 1 indicates a ByRef, and >=SZARRAY_BASE_SIZE indicates that this is an array. // Two types are not equivalent if their shapes do not exactly match. - internal UInt32 ParameterizedTypeShape + internal uint ParameterizedTypeShape { get { @@ -579,7 +579,7 @@ internal bool IsRelatedTypeViaIAT { get { - return ((_usFlags & (UInt16)EETypeFlags.RelatedTypeViaIATFlag) != 0); + return ((_usFlags & (ushort)EETypeFlags.RelatedTypeViaIATFlag) != 0); } } @@ -595,7 +595,7 @@ internal bool IsICastable { get { - return ((_usFlags & (UInt16)EETypeFlags.ICastableFlag) != 0); + return ((_usFlags & (ushort)EETypeFlags.ICastableFlag) != 0); } } @@ -611,14 +611,14 @@ internal IntPtr ICastableIsInstanceOfInterfaceMethod byte* optionalFields = OptionalFieldsPtr; if(optionalFields != null) { - const UInt16 NoSlot = 0xFFFF; - UInt16 uiSlot = (UInt16)OptionalFieldsReader.GetInlineField(optionalFields, EETypeOptionalFieldTag.ICastableIsInstSlot, NoSlot); + const ushort NoSlot = 0xFFFF; + ushort uiSlot = (ushort)OptionalFieldsReader.GetInlineField(optionalFields, EETypeOptionalFieldTag.ICastableIsInstSlot, NoSlot); if (uiSlot != NoSlot) { if (uiSlot < NumVtableSlots) return GetVTableStartAddress()[uiSlot]; else - return GetSealedVirtualSlot((UInt16)(uiSlot - NumVtableSlots)); + return GetSealedVirtualSlot((ushort)(uiSlot - NumVtableSlots)); } } @@ -643,14 +643,14 @@ internal IntPtr ICastableGetImplTypeMethod byte* optionalFields = OptionalFieldsPtr; if(optionalFields != null) { - const UInt16 NoSlot = 0xFFFF; - UInt16 uiSlot = (UInt16)OptionalFieldsReader.GetInlineField(optionalFields, EETypeOptionalFieldTag.ICastableGetImplTypeSlot, NoSlot); + const ushort NoSlot = 0xFFFF; + ushort uiSlot = (ushort)OptionalFieldsReader.GetInlineField(optionalFields, EETypeOptionalFieldTag.ICastableGetImplTypeSlot, NoSlot); if (uiSlot != NoSlot) { if (uiSlot < NumVtableSlots) return GetVTableStartAddress()[uiSlot]; else - return GetSealedVirtualSlot((UInt16)(uiSlot - NumVtableSlots)); + return GetSealedVirtualSlot((ushort)(uiSlot - NumVtableSlots)); } } @@ -667,7 +667,7 @@ internal bool IsValueType { get { - return ((_usFlags & (UInt16)EETypeFlags.ValueTypeFlag) != 0); + return ((_usFlags & (ushort)EETypeFlags.ValueTypeFlag) != 0); } } @@ -675,7 +675,7 @@ internal bool HasGCPointers { get { - return ((_usFlags & (UInt16)EETypeFlags.HasPointersFlag) != 0); + return ((_usFlags & (ushort)EETypeFlags.HasPointersFlag) != 0); } #if TYPE_LOADER_IMPLEMENTATION set @@ -700,7 +700,7 @@ internal bool IsHFA } } - internal UInt32 ValueTypeFieldPadding + internal uint ValueTypeFieldPadding { get { @@ -712,15 +712,15 @@ internal UInt32 ValueTypeFieldPadding // Get the value from the optional fields. The default is zero if that particular field was not included. // The low bits of this field is the ValueType field padding, the rest of the byte is the alignment if present - UInt32 ValueTypeFieldPaddingData = OptionalFieldsReader.GetInlineField(optionalFields, EETypeOptionalFieldTag.ValueTypeFieldPadding, 0); - UInt32 padding = ValueTypeFieldPaddingData & ValueTypePaddingLowMask; + uint ValueTypeFieldPaddingData = OptionalFieldsReader.GetInlineField(optionalFields, EETypeOptionalFieldTag.ValueTypeFieldPadding, 0); + uint padding = ValueTypeFieldPaddingData & ValueTypePaddingLowMask; // If there is additional padding, the other bits have that data padding |= (ValueTypeFieldPaddingData & ValueTypePaddingHighMask) >> (ValueTypePaddingHighShift - ValueTypePaddingAlignmentShift); return padding; } } - internal UInt32 ValueTypeSize + internal uint ValueTypeSize { get { @@ -732,7 +732,7 @@ internal UInt32 ValueTypeSize } } - internal UInt32 FieldByteCountNonGCAligned + internal uint FieldByteCountNonGCAligned { get { @@ -769,7 +769,7 @@ internal bool HasDispatchMap byte* optionalFields = OptionalFieldsPtr; if (optionalFields == null) return false; - UInt32 idxDispatchMap = OptionalFieldsReader.GetInlineField(optionalFields, EETypeOptionalFieldTag.DispatchMap, 0xffffffff); + uint idxDispatchMap = OptionalFieldsReader.GetInlineField(optionalFields, EETypeOptionalFieldTag.DispatchMap, 0xffffffff); if (idxDispatchMap == 0xffffffff) { if (HasDynamicallyAllocatedDispatchMap) @@ -912,7 +912,7 @@ internal IntPtr FinalizerCode get { Debug.Assert(IsNullable); - UInt32 cbNullableTypeOffset = GetFieldOffset(EETypeField.ETF_NullableType); + uint cbNullableTypeOffset = GetFieldOffset(EETypeField.ETF_NullableType); fixed (EEType* pThis = &this) { if (IsNullableTypeViaIAT) @@ -987,14 +987,14 @@ internal byte NullableValueOffset return (IntPtr*)pResult; } - private static IntPtr FollowRelativePointer(Int32* pDist) + private static IntPtr FollowRelativePointer(int* pDist) { - Int32 dist = *pDist; + int dist = *pDist; IntPtr result = (IntPtr)((byte*)pDist + dist); return result; } - internal IntPtr GetSealedVirtualSlot(UInt16 slotNumber) + internal IntPtr GetSealedVirtualSlot(ushort slotNumber) { Debug.Assert(!IsNullable); Debug.Assert((RareFlags & EETypeRareFlags.HasSealedVTableEntriesFlag) != 0); @@ -1003,14 +1003,14 @@ internal IntPtr GetSealedVirtualSlot(UInt16 slotNumber) { if (IsDynamicType) { - UInt32 cbSealedVirtualSlotsTypeOffset = GetFieldOffset(EETypeField.ETF_SealedVirtualSlots); + uint cbSealedVirtualSlotsTypeOffset = GetFieldOffset(EETypeField.ETF_SealedVirtualSlots); IntPtr* pSealedVirtualsSlotTable = *(IntPtr**)((byte*)pThis + cbSealedVirtualSlotsTypeOffset); return pSealedVirtualsSlotTable[slotNumber]; } else { - UInt32 cbSealedVirtualSlotsTypeOffset = GetFieldOffset(EETypeField.ETF_SealedVirtualSlots); - Int32* pSealedVirtualsSlotTable = (Int32*)FollowRelativePointer((Int32*)((byte*)pThis + cbSealedVirtualSlotsTypeOffset)); + uint cbSealedVirtualSlotsTypeOffset = GetFieldOffset(EETypeField.ETF_SealedVirtualSlots); + int* pSealedVirtualsSlotTable = (int*)FollowRelativePointer((int*)((byte*)pThis + cbSealedVirtualSlotsTypeOffset)); IntPtr result = FollowRelativePointer(&pSealedVirtualsSlotTable[slotNumber]); return result; } @@ -1038,7 +1038,7 @@ internal void SetSealedVirtualSlot(IntPtr value, UInt16 slotNumber) if (!HasOptionalFields) return null; - UInt32 cbOptionalFieldsOffset = GetFieldOffset(EETypeField.ETF_OptionalFieldsPtr); + uint cbOptionalFieldsOffset = GetFieldOffset(EETypeField.ETF_OptionalFieldsPtr); fixed (EEType* pThis = &this) { return *(byte**)((byte*)pThis + cbOptionalFieldsOffset); @@ -1063,7 +1063,7 @@ internal void SetSealedVirtualSlot(IntPtr value, UInt16 slotNumber) get { Debug.Assert(IsDynamicType); - UInt32 cbOffset = GetFieldOffset(EETypeField.ETF_DynamicTemplateType); + uint cbOffset = GetFieldOffset(EETypeField.ETF_DynamicTemplateType); fixed (EEType* pThis = &this) { return *(EEType**)((byte*)pThis + cbOffset); @@ -1087,7 +1087,7 @@ internal IntPtr DynamicGcStaticsData get { Debug.Assert((RareFlags & EETypeRareFlags.IsDynamicTypeWithGcStatics) != 0); - UInt32 cbOffset = GetFieldOffset(EETypeField.ETF_DynamicGcStatics); + uint cbOffset = GetFieldOffset(EETypeField.ETF_DynamicGcStatics); fixed (EEType* pThis = &this) { return (IntPtr)((byte*)pThis + cbOffset); @@ -1111,7 +1111,7 @@ internal IntPtr DynamicNonGcStaticsData get { Debug.Assert((RareFlags & EETypeRareFlags.IsDynamicTypeWithNonGcStatics) != 0); - UInt32 cbOffset = GetFieldOffset(EETypeField.ETF_DynamicNonGcStatics); + uint cbOffset = GetFieldOffset(EETypeField.ETF_DynamicNonGcStatics); fixed (EEType* pThis = &this) { return (IntPtr)((byte*)pThis + cbOffset); @@ -1136,7 +1136,7 @@ internal IntPtr DynamicNonGcStaticsData { if ((RareFlags & EETypeRareFlags.HasDynamicModuleFlag) != 0) { - UInt32 cbOffset = GetFieldOffset(EETypeField.ETF_DynamicModule); + uint cbOffset = GetFieldOffset(EETypeField.ETF_DynamicModule); fixed (EEType* pThis = &this) { return *(DynamicModule**)((byte*)pThis + cbOffset); @@ -1209,7 +1209,7 @@ internal int FieldAlignmentRequirement // Get the value from the optional fields. The default is zero if that particular field was not included. // The low bits of this field is the ValueType field padding, the rest of the value is the alignment if present - UInt32 alignmentValue = (OptionalFieldsReader.GetInlineField(optionalFields, EETypeOptionalFieldTag.ValueTypeFieldPadding, 0) & ValueTypePaddingAlignmentMask) >> ValueTypePaddingAlignmentShift; + uint alignmentValue = (OptionalFieldsReader.GetInlineField(optionalFields, EETypeOptionalFieldTag.ValueTypeFieldPadding, 0) & ValueTypePaddingAlignmentMask) >> ValueTypePaddingAlignmentShift; // Alignment is stored as 1 + the log base 2 of the alignment, except a 0 indicates standard pointer alignment. if (alignmentValue == 0) @@ -1235,10 +1235,10 @@ public bool HasCctor } } - public UInt32 GetFieldOffset(EETypeField eField) + public uint GetFieldOffset(EETypeField eField) { // First part of EEType consists of the fixed portion followed by the vtable. - UInt32 cbOffset = (UInt32)(sizeof(EEType) + (IntPtr.Size * _usNumVtableSlots)); + uint cbOffset = (uint)(sizeof(EEType) + (IntPtr.Size * _usNumVtableSlots)); // Then we have the interface map. if (eField == EETypeField.ETF_InterfaceMap) @@ -1246,7 +1246,7 @@ public UInt32 GetFieldOffset(EETypeField eField) Debug.Assert(NumInterfaces > 0); return cbOffset; } - cbOffset += (UInt32)(sizeof(EEInterfaceInfo) * NumInterfaces); + cbOffset += (uint)(sizeof(EEInterfaceInfo) * NumInterfaces); // Followed by the pointer to the finalizer method. if (eField == EETypeField.ETF_Finalizer) @@ -1255,7 +1255,7 @@ public UInt32 GetFieldOffset(EETypeField eField) return cbOffset; } if (IsFinalizable) - cbOffset += (UInt32)IntPtr.Size; + cbOffset += (uint)IntPtr.Size; // Followed by the pointer to the optional fields. if (eField == EETypeField.ETF_OptionalFieldsPtr) @@ -1264,7 +1264,7 @@ public UInt32 GetFieldOffset(EETypeField eField) return cbOffset; } if (HasOptionalFields) - cbOffset += (UInt32)IntPtr.Size; + cbOffset += (uint)IntPtr.Size; // Followed by the pointer to the type target of a Nullable. if (eField == EETypeField.ETF_NullableType) @@ -1278,13 +1278,13 @@ public UInt32 GetFieldOffset(EETypeField eField) return cbOffset; if (IsNullable) - cbOffset += (UInt32)IntPtr.Size; + cbOffset += (uint)IntPtr.Size; EETypeRareFlags rareFlags = RareFlags; // in the case of sealed vtable entries on static types, we have a UInt sized relative pointer if ((rareFlags & EETypeRareFlags.HasSealedVTableEntriesFlag) != 0) - cbOffset += (IsDynamicType ? (UInt32)IntPtr.Size : 4); + cbOffset += (IsDynamicType ? (uint)IntPtr.Size : 4); if (eField == EETypeField.ETF_DynamicDispatchMap) { @@ -1292,7 +1292,7 @@ public UInt32 GetFieldOffset(EETypeField eField) return cbOffset; } if ((rareFlags & EETypeRareFlags.HasDynamicallyAllocatedDispatchMapFlag) != 0) - cbOffset += (UInt32)IntPtr.Size; + cbOffset += (uint)IntPtr.Size; if (eField == EETypeField.ETF_GenericDefinition) { @@ -1300,7 +1300,7 @@ public UInt32 GetFieldOffset(EETypeField eField) return cbOffset; } if (IsGeneric) - cbOffset += (UInt32)IntPtr.Size; + cbOffset += (uint)IntPtr.Size; if (eField == EETypeField.ETF_GenericComposition) { @@ -1308,7 +1308,7 @@ public UInt32 GetFieldOffset(EETypeField eField) return cbOffset; } if (IsGeneric) - cbOffset += (UInt32)IntPtr.Size; + cbOffset += (uint)IntPtr.Size; if (eField == EETypeField.ETF_DynamicModule) { @@ -1316,7 +1316,7 @@ public UInt32 GetFieldOffset(EETypeField eField) } if ((rareFlags & EETypeRareFlags.HasDynamicModuleFlag) != 0) - cbOffset += (UInt32)IntPtr.Size; + cbOffset += (uint)IntPtr.Size; if (eField == EETypeField.ETF_DynamicTemplateType) { @@ -1324,7 +1324,7 @@ public UInt32 GetFieldOffset(EETypeField eField) return cbOffset; } if (IsDynamicType) - cbOffset += (UInt32)IntPtr.Size; + cbOffset += (uint)IntPtr.Size; if (eField == EETypeField.ETF_DynamicGcStatics) { @@ -1332,7 +1332,7 @@ public UInt32 GetFieldOffset(EETypeField eField) return cbOffset; } if ((rareFlags & EETypeRareFlags.IsDynamicTypeWithGcStatics) != 0) - cbOffset += (UInt32)IntPtr.Size; + cbOffset += (uint)IntPtr.Size; if (eField == EETypeField.ETF_DynamicNonGcStatics) { @@ -1340,7 +1340,7 @@ public UInt32 GetFieldOffset(EETypeField eField) return cbOffset; } if ((rareFlags & EETypeRareFlags.IsDynamicTypeWithNonGcStatics) != 0) - cbOffset += (UInt32)IntPtr.Size; + cbOffset += (uint)IntPtr.Size; if (eField == EETypeField.ETF_DynamicThreadStaticOffset) { diff --git a/src/Common/src/Internal/Runtime/ModuleHeaders.cs b/src/Common/src/Internal/Runtime/ModuleHeaders.cs index 20195b7cc61..af312f84e1f 100644 --- a/src/Common/src/Internal/Runtime/ModuleHeaders.cs +++ b/src/Common/src/Internal/Runtime/ModuleHeaders.cs @@ -22,15 +22,15 @@ internal struct ReadyToRunHeaderConstants #pragma warning disable 0169 internal struct ReadyToRunHeader { - private UInt32 Signature; // ReadyToRunHeaderConstants.Signature - private UInt16 MajorVersion; - private UInt16 MinorVersion; + private uint Signature; // ReadyToRunHeaderConstants.Signature + private ushort MajorVersion; + private ushort MinorVersion; - private UInt32 Flags; + private uint Flags; - private UInt16 NumberOfSections; - private Byte EntrySize; - private Byte EntryType; + private ushort NumberOfSections; + private byte EntrySize; + private byte EntryType; // Array of sections follows. }; diff --git a/src/Common/src/Interop/Windows/advapi32/Interop.RegDeleteValue.cs b/src/Common/src/Interop/Windows/advapi32/Interop.RegDeleteValue.cs index 91369a01fc7..2597b23d016 100644 --- a/src/Common/src/Interop/Windows/advapi32/Interop.RegDeleteValue.cs +++ b/src/Common/src/Interop/Windows/advapi32/Interop.RegDeleteValue.cs @@ -11,6 +11,6 @@ internal partial class Interop internal partial class Advapi32 { [DllImport("advapi32.dll", CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegDeleteValueW")] - internal static extern int RegDeleteValue(SafeRegistryHandle hKey, String lpValueName); + internal static extern int RegDeleteValue(SafeRegistryHandle hKey, string lpValueName); } } diff --git a/src/Common/src/Interop/Windows/mincore/Interop.MemAllocFree.cs b/src/Common/src/Interop/Windows/mincore/Interop.MemAllocFree.cs index c93c2bf7528..6632580a59e 100644 --- a/src/Common/src/Interop/Windows/mincore/Interop.MemAllocFree.cs +++ b/src/Common/src/Interop/Windows/mincore/Interop.MemAllocFree.cs @@ -17,7 +17,7 @@ internal static unsafe partial class mincore internal static extern IntPtr HeapAlloc(IntPtr hHeap, uint dwFlags, UIntPtr dwBytes); [DllImport("api-ms-win-core-heap-l1-1-0.dll")] - internal static extern int HeapFree(IntPtr hHeap, UInt32 dwFlags, IntPtr lpMem); + internal static extern int HeapFree(IntPtr hHeap, uint dwFlags, IntPtr lpMem); } internal static IntPtr MemAlloc(UIntPtr sizeInBytes) diff --git a/src/Common/src/Interop/Windows/mincore/Interop.MemReAlloc.cs b/src/Common/src/Interop/Windows/mincore/Interop.MemReAlloc.cs index 45dc7c675cb..c195f481bec 100644 --- a/src/Common/src/Interop/Windows/mincore/Interop.MemReAlloc.cs +++ b/src/Common/src/Interop/Windows/mincore/Interop.MemReAlloc.cs @@ -11,7 +11,7 @@ internal static partial class Interop internal static unsafe partial class mincore { [DllImport("api-ms-win-core-heap-l1-1-0.dll")] - internal static extern unsafe IntPtr HeapReAlloc(IntPtr hHeap, UInt32 dwFlags, IntPtr lpMem, UIntPtr dwBytes); + internal static extern unsafe IntPtr HeapReAlloc(IntPtr hHeap, uint dwFlags, IntPtr lpMem, UIntPtr dwBytes); } internal static unsafe IntPtr MemReAlloc(IntPtr ptr, UIntPtr newSize) diff --git a/src/Common/src/Interop/Windows/mincore/Interop.RegCreateKeyEx.cs b/src/Common/src/Interop/Windows/mincore/Interop.RegCreateKeyEx.cs index 8f9d3eed31c..b1ccf69b93c 100644 --- a/src/Common/src/Interop/Windows/mincore/Interop.RegCreateKeyEx.cs +++ b/src/Common/src/Interop/Windows/mincore/Interop.RegCreateKeyEx.cs @@ -15,9 +15,9 @@ internal partial class mincore [DllImport(Libraries.Registry_L1, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegCreateKeyExW")] internal static extern int RegCreateKeyEx( SafeRegistryHandle hKey, - String lpSubKey, + string lpSubKey, int Reserved, - String lpClass, + string lpClass, int dwOptions, int samDesired, ref Kernel32.SECURITY_ATTRIBUTES secAttrs, diff --git a/src/Common/src/Interop/Windows/mincore/Interop.RegQueryValueEx.cs b/src/Common/src/Interop/Windows/mincore/Interop.RegQueryValueEx.cs index 10e5c430fb6..8c748aa67ee 100644 --- a/src/Common/src/Interop/Windows/mincore/Interop.RegQueryValueEx.cs +++ b/src/Common/src/Interop/Windows/mincore/Interop.RegQueryValueEx.cs @@ -32,7 +32,7 @@ internal partial class mincore [DllImport(Libraries.Registry_L1, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegQueryValueExW")] internal static extern int RegQueryValueEx( SafeRegistryHandle hKey, - String lpValueName, + string lpValueName, int[] lpReserved, ref int lpType, ref long lpData, @@ -41,7 +41,7 @@ internal partial class mincore [DllImport(Libraries.Registry_L1, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegQueryValueExW")] internal static extern int RegQueryValueEx( SafeRegistryHandle hKey, - String lpValueName, + string lpValueName, int[] lpReserved, ref int lpType, [Out] char[] lpData, @@ -50,7 +50,7 @@ internal partial class mincore [DllImport(Libraries.Registry_L1, CharSet = CharSet.Unicode, BestFitMapping = false, EntryPoint = "RegQueryValueExW")] internal static extern int RegQueryValueEx( SafeRegistryHandle hKey, - String lpValueName, + string lpValueName, int[] lpReserved, ref int lpType, [Out]StringBuilder lpData, diff --git a/src/Common/src/System/Collections/Concurrent/ConcurrentUnifier.cs b/src/Common/src/System/Collections/Concurrent/ConcurrentUnifier.cs index cc7edb0a402..bbb5959caaa 100644 --- a/src/Common/src/System/Collections/Concurrent/ConcurrentUnifier.cs +++ b/src/Common/src/System/Collections/Concurrent/ConcurrentUnifier.cs @@ -102,7 +102,7 @@ public V GetOrAdd(K key) // State of a key must never go from found to not found, and only one value may exist per key. Debug.Assert(checkedFound); if (default(V) == null) // No good way to do the "only one value" check for value types. - Debug.Assert(Object.ReferenceEquals(checkedValue, value)); + Debug.Assert(object.ReferenceEquals(checkedValue, value)); } } #endif //DEBUG diff --git a/src/Common/src/System/Collections/Concurrent/ConcurrentUnifierW.cs b/src/Common/src/System/Collections/Concurrent/ConcurrentUnifierW.cs index 8324b6c398d..b2b70d8af3f 100644 --- a/src/Common/src/System/Collections/Concurrent/ConcurrentUnifierW.cs +++ b/src/Common/src/System/Collections/Concurrent/ConcurrentUnifierW.cs @@ -112,7 +112,7 @@ public V GetOrAdd(K key) // Since this DEBUG code is holding a strong reference to "value", state of a key must never go from found to not found, // and only one value may exist per key. Debug.Assert(checkedFound); - Debug.Assert(Object.ReferenceEquals(checkedValue, value)); + Debug.Assert(object.ReferenceEquals(checkedValue, value)); GC.KeepAlive(value); } } diff --git a/src/Common/src/System/Collections/Concurrent/ConcurrentUnifierWKeyed.cs b/src/Common/src/System/Collections/Concurrent/ConcurrentUnifierWKeyed.cs index 8aa21984db0..5dfcab17ae9 100644 --- a/src/Common/src/System/Collections/Concurrent/ConcurrentUnifierWKeyed.cs +++ b/src/Common/src/System/Collections/Concurrent/ConcurrentUnifierWKeyed.cs @@ -125,7 +125,7 @@ public V GetOrAdd(K key) // Since this DEBUG code is holding a strong reference to "value", state of a key must never go from found to not found, // and only one value may exist per key. Debug.Assert(checkedFound); - Debug.Assert(Object.ReferenceEquals(checkedValue, value)); + Debug.Assert(object.ReferenceEquals(checkedValue, value)); GC.KeepAlive(value); } } diff --git a/src/Common/src/System/CommonRuntimeTypes.cs b/src/Common/src/System/CommonRuntimeTypes.cs index f4cfec4693b..435a1867eb9 100644 --- a/src/Common/src/System/CommonRuntimeTypes.cs +++ b/src/Common/src/System/CommonRuntimeTypes.cs @@ -37,28 +37,28 @@ internal static class CommonRuntimeTypes internal static Type Void { get { return s_void; } } internal static Type MulticastDelegate { get { return s_multicastDelegate; } } - private static Type s_object = typeof(Object); + private static Type s_object = typeof(object); private static Type s_valuetype = typeof(ValueType); private static Type s_type = typeof(Type); private static Type s_attribute = typeof(Attribute); - private static Type s_string = typeof(String); + private static Type s_string = typeof(string); private static Type s_array = typeof(Array); private static Type s_enum = typeof(Enum); - private static Type s_boolean = typeof(Boolean); - private static Type s_char = typeof(Char); - private static Type s_byte = typeof(Byte); - private static Type s_sByte = typeof(SByte); - private static Type s_uInt16 = typeof(UInt16); - private static Type s_int16 = typeof(Int16); - private static Type s_uInt32 = typeof(UInt32); - private static Type s_int32 = typeof(Int32); - private static Type s_uInt64 = typeof(UInt64); - private static Type s_int64 = typeof(Int64); + private static Type s_boolean = typeof(bool); + private static Type s_char = typeof(char); + private static Type s_byte = typeof(byte); + private static Type s_sByte = typeof(sbyte); + private static Type s_uInt16 = typeof(ushort); + private static Type s_int16 = typeof(short); + private static Type s_uInt32 = typeof(uint); + private static Type s_int32 = typeof(int); + private static Type s_uInt64 = typeof(ulong); + private static Type s_int64 = typeof(long); private static Type s_uIntPtr = typeof(UIntPtr); private static Type s_intPtr = typeof(IntPtr); - private static Type s_single = typeof(Single); - private static Type s_double = typeof(Double); - private static Type s_decimal = typeof(Decimal); + private static Type s_single = typeof(float); + private static Type s_double = typeof(double); + private static Type s_decimal = typeof(decimal); private static Type s_datetime = typeof(DateTime); private static Type s_nullable = typeof(Nullable<>); private static Type s_void = typeof(void); diff --git a/src/Common/src/System/Numerics/Hashing/HashHelpers.cs b/src/Common/src/System/Numerics/Hashing/HashHelpers.cs index f017309a904..dd405eba78f 100644 --- a/src/Common/src/System/Numerics/Hashing/HashHelpers.cs +++ b/src/Common/src/System/Numerics/Hashing/HashHelpers.cs @@ -8,7 +8,7 @@ namespace System.Numerics.Hashing internal static class HashHelpers { - public static readonly int RandomSeed = new Random().Next(Int32.MinValue, Int32.MaxValue); + public static readonly int RandomSeed = new Random().Next(int.MinValue, int.MaxValue); public static int Combine(int h1, int h2) { diff --git a/src/Common/src/System/SR.cs b/src/Common/src/System/SR.cs index 3aeb59dade2..ef42e9a6b4c 100644 --- a/src/Common/src/System/SR.cs +++ b/src/Common/src/System/SR.cs @@ -42,7 +42,7 @@ private static bool UsingResourceKeys() // Needed for debugger integration internal static string GetResourceString(string resourceKey) { - return GetResourceString(resourceKey, String.Empty); + return GetResourceString(resourceKey, string.Empty); } internal static string GetResourceString(string resourceKey, string defaultString) @@ -146,10 +146,10 @@ internal static string Format(string resourceFormat, params object[] args) { if (UsingResourceKeys()) { - return resourceFormat + String.Join(", ", args); + return resourceFormat + string.Join(", ", args); } - return String.Format(resourceFormat, args); + return string.Format(resourceFormat, args); } return resourceFormat; @@ -159,29 +159,29 @@ internal static string Format(string resourceFormat, object p1) { if (UsingResourceKeys()) { - return String.Join(", ", resourceFormat, p1); + return string.Join(", ", resourceFormat, p1); } - return String.Format(resourceFormat, p1); + return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { - return String.Join(", ", resourceFormat, p1, p2); + return string.Join(", ", resourceFormat, p1, p2); } - return String.Format(resourceFormat, p1, p2); + return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { - return String.Join(", ", resourceFormat, p1, p2, p3); + return string.Join(", ", resourceFormat, p1, p2, p3); } - return String.Format(resourceFormat, p1, p2, p3); + return string.Format(resourceFormat, p1, p2, p3); } } } diff --git a/src/Runtime.Base/src/System/Runtime/CachedInterfaceDispatch.cs b/src/Runtime.Base/src/System/Runtime/CachedInterfaceDispatch.cs index 6ca1646c760..e4adb402e32 100644 --- a/src/Runtime.Base/src/System/Runtime/CachedInterfaceDispatch.cs +++ b/src/Runtime.Base/src/System/Runtime/CachedInterfaceDispatch.cs @@ -17,7 +17,7 @@ internal static unsafe class CachedInterfaceDispatch unsafe private static IntPtr RhpCidResolve(IntPtr callerTransitionBlockParam, IntPtr pCell) { IntPtr locationOfThisPointer = callerTransitionBlockParam + TransitionBlock.GetThisOffset(); - object pObject = Unsafe.As(ref *(IntPtr*)locationOfThisPointer); + object pObject = Unsafe.As(ref *(IntPtr*)locationOfThisPointer); IntPtr dispatchResolveTarget = RhpCidResolve_Worker(pObject, pCell); if (dispatchResolveTarget == InternalCalls.RhpGetCastableObjectDispatchHelper()) diff --git a/src/Runtime.Base/src/System/Runtime/CastableObjectSupport.cs b/src/Runtime.Base/src/System/Runtime/CastableObjectSupport.cs index 20f0ce285ef..5ed1679c582 100644 --- a/src/Runtime.Base/src/System/Runtime/CastableObjectSupport.cs +++ b/src/Runtime.Base/src/System/Runtime/CastableObjectSupport.cs @@ -324,7 +324,7 @@ internal static unsafe IntPtr GetCastableObjectDispatchCellThunk(EEType* pInstan unsafe private static IntPtr RhpCastableObjectResolve(IntPtr callerTransitionBlockParam, IntPtr pCell) { IntPtr locationOfThisPointer = callerTransitionBlockParam + TransitionBlock.GetThisOffset(); - object pObject = Unsafe.As(ref *(IntPtr*)locationOfThisPointer); + object pObject = Unsafe.As(ref *(IntPtr*)locationOfThisPointer); DispatchCellInfo cellInfo; InternalCalls.RhpGetDispatchCellInfo(pCell, out cellInfo); @@ -343,7 +343,7 @@ unsafe private static IntPtr RhpCastableObjectResolve(IntPtr callerTransitionBlo if (targetObject == null) EH.FailFastViaClasslib(RhFailFastReason.InternalError, null, pObject.EEType->GetAssociatedModuleAddress()); - Unsafe.As(ref *(IntPtr*)locationOfThisPointer) = targetObject; + Unsafe.As(ref *(IntPtr*)locationOfThisPointer) = targetObject; InternalCalls.RhpSetTLSDispatchCell(pCell); return InternalCalls.RhpGetTailCallTLSDispatchCell(); diff --git a/src/Runtime.Base/src/System/Runtime/DispatchResolve.cs b/src/Runtime.Base/src/System/Runtime/DispatchResolve.cs index c609d878b6d..1b45f6aecd6 100644 --- a/src/Runtime.Base/src/System/Runtime/DispatchResolve.cs +++ b/src/Runtime.Base/src/System/Runtime/DispatchResolve.cs @@ -47,7 +47,7 @@ public struct DispatchMap while (pCur != null) { - UInt16 implSlotNumber; + ushort implSlotNumber; if (FindImplSlotForCurrentType( pCur, pItfType, itfSlotNumber, &implSlotNumber)) { @@ -76,8 +76,8 @@ public struct DispatchMap private static bool FindImplSlotForCurrentType(EEType* pTgtType, EEType* pItfType, - UInt16 itfSlotNumber, - UInt16* pImplSlotNumber) + ushort itfSlotNumber, + ushort* pImplSlotNumber) { bool fRes = false; @@ -117,8 +117,8 @@ public struct DispatchMap private static bool FindImplSlotInSimpleMap(EEType* pTgtType, EEType* pItfType, - UInt32 itfSlotNumber, - UInt16* pImplSlotNumber, + uint itfSlotNumber, + ushort* pImplSlotNumber, bool actuallyCheckVariance) { Debug.Assert(pTgtType->HasDispatchMap, "Missing dispatch map"); diff --git a/src/Runtime.Base/src/System/Runtime/InternalCalls.cs b/src/Runtime.Base/src/System/Runtime/InternalCalls.cs index e647e3ab030..866247ac2c9 100644 --- a/src/Runtime.Base/src/System/Runtime/InternalCalls.cs +++ b/src/Runtime.Base/src/System/Runtime/InternalCalls.cs @@ -72,13 +72,13 @@ internal static long RhGetGcTotalMemory() private static extern long RhpGetGcTotalMemory(); [RuntimeExport("RhStartNoGCRegion")] - internal static Int32 RhStartNoGCRegion(Int64 totalSize, bool hasLohSize, Int64 lohSize, bool disallowFullBlockingGC) + internal static int RhStartNoGCRegion(long totalSize, bool hasLohSize, long lohSize, bool disallowFullBlockingGC) { return RhpStartNoGCRegion(totalSize, hasLohSize, lohSize, disallowFullBlockingGC); } [RuntimeExport("RhEndNoGCRegion")] - internal static Int32 RhEndNoGCRegion() + internal static int RhEndNoGCRegion() { return RhpEndNoGCRegion(); } @@ -91,7 +91,7 @@ internal static Int32 RhEndNoGCRegion() [RuntimeImport(Redhawk.BaseName, "RhpGetNextFinalizableObject")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] - internal static extern Object RhpGetNextFinalizableObject(); + internal static extern object RhpGetNextFinalizableObject(); // // internalcalls for System.Runtime.InteropServices.GCHandle. @@ -101,29 +101,29 @@ internal static Int32 RhEndNoGCRegion() [RuntimeImport(Redhawk.BaseName, "RhpHandleAlloc")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] - internal static extern IntPtr RhpHandleAlloc(Object value, GCHandleType type); + internal static extern IntPtr RhpHandleAlloc(object value, GCHandleType type); // Allocate dependent handle. [RuntimeImport(Redhawk.BaseName, "RhpHandleAllocDependent")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] - internal static extern IntPtr RhpHandleAllocDependent(Object primary, Object secondary); + internal static extern IntPtr RhpHandleAllocDependent(object primary, object secondary); // Allocate variable handle. [RuntimeImport(Redhawk.BaseName, "RhpHandleAllocVariable")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] - internal static extern IntPtr RhpHandleAllocVariable(Object value, uint type); + internal static extern IntPtr RhpHandleAllocVariable(object value, uint type); [RuntimeImport(Redhawk.BaseName, "RhHandleGet")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] - internal static extern Object RhHandleGet(IntPtr handle); + internal static extern object RhHandleGet(IntPtr handle); [RuntimeImport(Redhawk.BaseName, "RhHandleSet")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] - internal static extern IntPtr RhHandleSet(IntPtr handle, Object value); + internal static extern IntPtr RhHandleSet(IntPtr handle, object value); // // internal calls for allocation @@ -188,7 +188,7 @@ internal static Int32 RhEndNoGCRegion() [RuntimeImport(Redhawk.BaseName, "RhpAssignRef")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] - internal extern static unsafe void RhpAssignRef(ref Object address, object obj); + internal extern static unsafe void RhpAssignRef(ref object address, object obj); #if FEATURE_GC_STRESS // @@ -289,7 +289,7 @@ internal static Int32 RhEndNoGCRegion() [RuntimeImport(Redhawk.BaseName, "RhpGetEETypeRareFlags")] [MethodImpl(MethodImplOptions.InternalCall)] [ManuallyManaged(GcPollPolicy.Never)] - internal extern static unsafe UInt32 RhpGetEETypeRareFlags(EEType* pEEType); + internal extern static unsafe uint RhpGetEETypeRareFlags(EEType* pEEType); // Retrieve the offset of the value embedded in a Nullable. [RuntimeImport(Redhawk.BaseName, "RhpGetNullableEETypeValueOffset")] @@ -428,7 +428,7 @@ internal static Int32 RhEndNoGCRegion() // Block the current thread until at least one object needs to be finalized (returns true) or // memory is low (returns false and the finalizer thread should initiate a garbage collection). [DllImport(Redhawk.BaseName, CallingConvention = CallingConvention.Cdecl)] - internal static extern UInt32 RhpWaitForFinalizerRequest(); + internal static extern uint RhpWaitForFinalizerRequest(); // Indicate that the current round of finalizations is complete. [DllImport(Redhawk.BaseName, CallingConvention = CallingConvention.Cdecl)] @@ -455,11 +455,11 @@ internal static Int32 RhEndNoGCRegion() // Enters a no GC region, possibly doing a blocking GC if there is not enough // memory available to satisfy the caller's request. [DllImport(Redhawk.BaseName, CallingConvention = CallingConvention.Cdecl)] - internal static extern Int32 RhpStartNoGCRegion(Int64 totalSize, bool hasLohSize, Int64 lohSize, bool disallowFullBlockingGC); + internal static extern int RhpStartNoGCRegion(long totalSize, bool hasLohSize, long lohSize, bool disallowFullBlockingGC); // Exits a no GC region, possibly doing a GC to clean up the garbage that // the caller allocated. [DllImport(Redhawk.BaseName, CallingConvention = CallingConvention.Cdecl)] - internal static extern Int32 RhpEndNoGCRegion(); + internal static extern int RhpEndNoGCRegion(); } } diff --git a/src/Runtime.Base/src/System/Runtime/RuntimeExports.cs b/src/Runtime.Base/src/System/Runtime/RuntimeExports.cs index db9b5de744e..0c84e7c1f2c 100644 --- a/src/Runtime.Base/src/System/Runtime/RuntimeExports.cs +++ b/src/Runtime.Base/src/System/Runtime/RuntimeExports.cs @@ -121,7 +121,7 @@ public static unsafe object RhBoxAny(ref byte data, EETypePtr pEEType) } else { - return Unsafe.As(ref data); + return Unsafe.As(ref data); } } @@ -189,7 +189,7 @@ public static unsafe void RhUnboxAny(object o, ref byte data, EETypePtr pUnboxTo throw ptrUnboxToEEType->GetClasslibException(ExceptionIDs.InvalidCast); } - Unsafe.As(ref data) = o; + Unsafe.As(ref data) = o; } } @@ -197,7 +197,7 @@ public static unsafe void RhUnboxAny(object o, ref byte data, EETypePtr pUnboxTo // Unbox helpers with RyuJIT conventions // [RuntimeExport("RhUnbox2")] - public static unsafe ref byte RhUnbox2(EETypePtr pUnboxToEEType, Object obj) + public static unsafe ref byte RhUnbox2(EETypePtr pUnboxToEEType, object obj) { EEType* ptrUnboxToEEType = (EEType*)pUnboxToEEType.ToPointer(); if ((obj == null) || !UnboxAnyTypeCompare(obj.EEType, ptrUnboxToEEType)) @@ -209,7 +209,7 @@ public static unsafe void RhUnboxAny(object o, ref byte data, EETypePtr pUnboxTo } [RuntimeExport("RhUnboxNullable")] - public static unsafe void RhUnboxNullable(ref byte data, EETypePtr pUnboxToEEType, Object obj) + public static unsafe void RhUnboxNullable(ref byte data, EETypePtr pUnboxToEEType, object obj) { EEType* ptrUnboxToEEType = (EEType*)pUnboxToEEType.ToPointer(); if ((obj != null) && !TypeCast.AreTypesEquivalentInternal(obj.EEType, ptrUnboxToEEType->NullableType)) @@ -235,7 +235,7 @@ public static unsafe void RhArrayStoreCheckAny(object array, ref byte data) return; } - TypeCast.CheckArrayStore(array, Unsafe.As(ref data)); + TypeCast.CheckArrayStore(array, Unsafe.As(ref data)); } [RuntimeExport("RhBoxAndNullCheck")] @@ -245,13 +245,13 @@ public static unsafe bool RhBoxAndNullCheck(ref byte data, EETypePtr pEEType) if (ptrEEType->IsValueType) return true; else - return Unsafe.As(ref data) != null; + return Unsafe.As(ref data) != null; } #pragma warning disable 169 // The field 'System.Runtime.RuntimeExports.Wrapper.o' is never used. private class Wrapper { - private Object _o; + private object _o; } #pragma warning restore 169 diff --git a/src/Runtime.Base/src/System/Runtime/TypeCast.cs b/src/Runtime.Base/src/System/Runtime/TypeCast.cs index 568892a6521..21fd9b8459e 100644 --- a/src/Runtime.Base/src/System/Runtime/TypeCast.cs +++ b/src/Runtime.Base/src/System/Runtime/TypeCast.cs @@ -154,7 +154,7 @@ public static unsafe object IsInstanceOfClass(object obj, void* pvTargetType) } [RuntimeExport("RhTypeCast_CheckCastClass")] - public static unsafe object CheckCastClass(Object obj, void* pvTargetEEType) + public static unsafe object CheckCastClass(object obj, void* pvTargetEEType) { // a null value can be cast to anything if (obj == null) @@ -174,7 +174,7 @@ public static unsafe object CheckCastClass(Object obj, void* pvTargetEEType) } [RuntimeExport("RhTypeCast_CheckUnbox")] - public static unsafe void CheckUnbox(Object obj, byte expectedCorElementType) + public static unsafe void CheckUnbox(object obj, byte expectedCorElementType) { if (obj == null) { @@ -239,7 +239,7 @@ public static unsafe object IsInstanceOfArray(object obj, void* pvTargetType) } [RuntimeExport("RhTypeCast_CheckCastArray")] - public static unsafe object CheckCastArray(Object obj, void* pvTargetEEType) + public static unsafe object CheckCastArray(object obj, void* pvTargetEEType) { // a null value can be cast to anything if (obj == null) @@ -734,7 +734,7 @@ internal static unsafe bool AreTypesAssignableInternal(EEType* pSourceType, EETy } [RuntimeExport("RhTypeCast_CheckCastInterface")] - public static unsafe object CheckCastInterface(Object obj, void* pvTargetEEType) + public static unsafe object CheckCastInterface(object obj, void* pvTargetEEType) { // a null value can be cast to anything if (obj == null) @@ -858,7 +858,7 @@ public static unsafe void StelemRef(Array array, int index, object obj) // Both bounds and type check are ok. // Call write barrier directly. Assigning object reference would call slower checked write barrier. - ref Object rawData = ref Unsafe.As(ref array.GetRawSzArrayData()); + ref object rawData = ref Unsafe.As(ref array.GetRawSzArrayData()); InternalCalls.RhpAssignRef(ref Unsafe.Add(ref rawData, index), obj); } else @@ -870,7 +870,7 @@ public static unsafe void StelemRef(Array array, int index, object obj) } [RuntimeExport("RhpLdelemaRef")] - public static unsafe ref Object LdelemaRef(Array array, int index, IntPtr elementType) + public static unsafe ref object LdelemaRef(Array array, int index, IntPtr elementType) { Debug.Assert(array.EEType->IsArray, "first argument must be an array"); @@ -885,7 +885,7 @@ public static unsafe void StelemRef(Array array, int index, object obj) throw array.EEType->GetClasslibException(ExceptionIDs.ArrayTypeMismatch); } - ref Object rawData = ref Unsafe.As(ref array.GetRawSzArrayData()); + ref object rawData = ref Unsafe.As(ref array.GetRawSzArrayData()); return ref Unsafe.Add(ref rawData, index); } @@ -976,13 +976,13 @@ public static unsafe object IsInstanceOf(object obj, void* pvTargetType) } [RuntimeExport("RhTypeCast_CheckCast2")] // Helper with RyuJIT calling convention - public static unsafe object CheckCast2(void* pvTargetType, Object obj) + public static unsafe object CheckCast2(void* pvTargetType, object obj) { return CheckCast(obj, pvTargetType); } [RuntimeExport("RhTypeCast_CheckCast")] - public static unsafe object CheckCast(Object obj, void* pvTargetType) + public static unsafe object CheckCast(object obj, void* pvTargetType) { // @TODO: consider using the cache directly, but beware of ICastable in the interface case EEType* pTargetType = (EEType*)pvTargetType; diff --git a/src/Runtime.Base/src/System/Runtime/__Finalizer.cs b/src/Runtime.Base/src/System/Runtime/__Finalizer.cs index 6fd7d7ea3f6..0dbc18de441 100644 --- a/src/Runtime.Base/src/System/Runtime/__Finalizer.cs +++ b/src/Runtime.Base/src/System/Runtime/__Finalizer.cs @@ -58,7 +58,7 @@ private static unsafe void DrainQueue() // Drain the queue of finalizable objects. while (true) { - Object target = InternalCalls.RhpGetNextFinalizableObject(); + object target = InternalCalls.RhpGetNextFinalizableObject(); if (target == null) return; diff --git a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/StubEnvironment.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/StubEnvironment.cs index 13de05a7012..6f2eb9ba216 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/StubEnvironment.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/StubEnvironment.cs @@ -301,7 +301,7 @@ public static TypeCode GetTypeCode(this Type type) else if (type == typeof(float)) return TypeCode.Single; else if (type == typeof(double)) return TypeCode.Double; else if (type == typeof(DateTime)) return TypeCode.DateTime; - else if (type == (typeof(Decimal))) return TypeCode.Decimal; + else if (type == (typeof(decimal))) return TypeCode.Decimal; else return TypeCode.Object; } diff --git a/src/System.Private.CoreLib/shared/System/IO/TextWriter.cs b/src/System.Private.CoreLib/shared/System/IO/TextWriter.cs index 4ab3c708cc6..547c597f033 100644 --- a/src/System.Private.CoreLib/shared/System/IO/TextWriter.cs +++ b/src/System.Private.CoreLib/shared/System/IO/TextWriter.cs @@ -184,7 +184,7 @@ public virtual void Write(ReadOnlySpan buffer) } // Writes the text representation of a boolean to the text stream. This - // method outputs either Boolean.TrueString or Boolean.FalseString. + // method outputs either bool.TrueString or bool.FalseString. // public virtual void Write(bool value) { @@ -231,7 +231,7 @@ public virtual void Write(ulong value) // Writes the text representation of a float to the text stream. The // text representation of the given value is produced by calling the - // Float.toString(float) method. + // float.ToString(float) method. // public virtual void Write(float value) { @@ -240,7 +240,7 @@ public virtual void Write(float value) // Writes the text representation of a double to the text stream. The // text representation of the given value is produced by calling the - // Double.toString(double) method. + // double.ToString(double) method. // public virtual void Write(double value) { diff --git a/src/System.Private.CoreLib/src/Internal/DeveloperExperience/DeveloperExperience.cs b/src/System.Private.CoreLib/src/Internal/DeveloperExperience/DeveloperExperience.cs index f23eb0df5d2..c507307c615 100644 --- a/src/System.Private.CoreLib/src/Internal/DeveloperExperience/DeveloperExperience.cs +++ b/src/System.Private.CoreLib/src/Internal/DeveloperExperience/DeveloperExperience.cs @@ -34,13 +34,13 @@ private static bool IsMetadataStackTraceResolutionDisabled() return disableMetadata; } - public virtual void WriteLine(String s) + public virtual void WriteLine(string s) { Debug.WriteLine(s); return; } - public virtual String CreateStackTraceString(IntPtr ip, bool includeFileInfo) + public virtual string CreateStackTraceString(IntPtr ip, bool includeFileInfo) { if (!IsMetadataStackTraceResolutionDisabled()) { @@ -74,7 +74,7 @@ public virtual String CreateStackTraceString(IntPtr ip, bool includeFileInfo) } StringBuilder sb = new StringBuilder(); - String fileNameWithoutExtension = GetFileNameWithoutExtension(moduleFullFileName); + string fileNameWithoutExtension = GetFileNameWithoutExtension(moduleFullFileName); int rva = RuntimeAugments.ConvertIpToRva(ip); sb.Append(fileNameWithoutExtension); sb.Append("!+0x"); @@ -107,7 +107,7 @@ public virtual void TryGetMethodBase(IntPtr methodStartAddress, out MethodBase m } } - public virtual bool OnContractFailure(String stackTrace, ContractFailureKind contractFailureKind, String displayMessage, String userMessage, String conditionText, Exception innerException) + public virtual bool OnContractFailure(string stackTrace, ContractFailureKind contractFailureKind, string displayMessage, string userMessage, string conditionText, Exception innerException) { Debug.WriteLine("Assertion failed: " + (displayMessage == null ? "" : displayMessage)); if (Debugger.IsAttached) @@ -131,7 +131,7 @@ public static DeveloperExperience Default } } - private static String GetFileNameWithoutExtension(String path) + private static string GetFileNameWithoutExtension(string path) { path = GetFileName(path); int i; @@ -141,7 +141,7 @@ private static String GetFileNameWithoutExtension(String path) return path.Substring(0, i); } - private static String GetFileName(String path) + private static string GetFileName(string path) { int length = path.Length; for (int i = length; --i >= 0;) diff --git a/src/System.Private.CoreLib/src/Internal/IntrinsicSupport/ComparerHelpers.cs b/src/System.Private.CoreLib/src/Internal/IntrinsicSupport/ComparerHelpers.cs index bcbd541dd06..f8822391707 100644 --- a/src/System.Private.CoreLib/src/Internal/IntrinsicSupport/ComparerHelpers.cs +++ b/src/System.Private.CoreLib/src/Internal/IntrinsicSupport/ComparerHelpers.cs @@ -175,7 +175,7 @@ public sealed override int Compare(T x, T y) } // Equals method for the comparer itself. - public sealed override bool Equals(Object obj) => obj != null && GetType() == obj.GetType(); + public sealed override bool Equals(object obj) => obj != null && GetType() == obj.GetType(); public sealed override int GetHashCode() => GetType().GetHashCode(); } @@ -201,7 +201,7 @@ public sealed override int Compare(Nullable x, Nullable y) } // Equals method for the comparer itself. - public sealed override bool Equals(Object obj) => obj != null && GetType() == obj.GetType(); + public sealed override bool Equals(object obj) => obj != null && GetType() == obj.GetType(); public sealed override int GetHashCode() => GetType().GetHashCode(); } @@ -216,7 +216,7 @@ public sealed override int Compare(T x, T y) } // Equals method for the comparer itself. - public sealed override bool Equals(Object obj) => obj != null && GetType() == obj.GetType(); + public sealed override bool Equals(object obj) => obj != null && GetType() == obj.GetType(); public sealed override int GetHashCode() => GetType().GetHashCode(); } diff --git a/src/System.Private.CoreLib/src/Internal/IntrinsicSupport/EqualityComparerHelpers.cs b/src/System.Private.CoreLib/src/Internal/IntrinsicSupport/EqualityComparerHelpers.cs index 73ed2b25df8..2b230eed81c 100644 --- a/src/System.Private.CoreLib/src/Internal/IntrinsicSupport/EqualityComparerHelpers.cs +++ b/src/System.Private.CoreLib/src/Internal/IntrinsicSupport/EqualityComparerHelpers.cs @@ -239,7 +239,7 @@ public sealed override int GetHashCode(T obj) } // Equals method for the comparer itself. - public sealed override bool Equals(Object obj) => obj is GenericEqualityComparer; + public sealed override bool Equals(object obj) => obj is GenericEqualityComparer; public sealed override int GetHashCode() => typeof(GenericEqualityComparer).GetHashCode(); } @@ -270,7 +270,7 @@ public sealed override int GetHashCode(Nullable obj) // Equals method for the comparer itself. - public sealed override bool Equals(Object obj) => obj is NullableEqualityComparer; + public sealed override bool Equals(object obj) => obj is NullableEqualityComparer; public sealed override int GetHashCode() => typeof(NullableEqualityComparer).GetHashCode(); } @@ -303,7 +303,7 @@ public void GetObjectData(SerializationInfo info, StreamingContext context) } // Equals method for the comparer itself. - public override bool Equals(Object obj) => obj is EnumEqualityComparer; + public override bool Equals(object obj) => obj is EnumEqualityComparer; public override int GetHashCode() => typeof(EnumEqualityComparer).GetHashCode(); } @@ -335,7 +335,7 @@ public sealed override int GetHashCode(T obj) } // Equals method for the comparer itself. - public sealed override bool Equals(Object obj) + public sealed override bool Equals(object obj) { if(obj == null) { diff --git a/src/System.Private.CoreLib/src/Internal/Reflection/ExplicitScopeAttribute.cs b/src/System.Private.CoreLib/src/Internal/Reflection/ExplicitScopeAttribute.cs index fc309169b6e..ef0aa659754 100644 --- a/src/System.Private.CoreLib/src/Internal/Reflection/ExplicitScopeAttribute.cs +++ b/src/System.Private.CoreLib/src/Internal/Reflection/ExplicitScopeAttribute.cs @@ -21,7 +21,7 @@ namespace Internal.Reflection [AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Enum | AttributeTargets.Struct | AttributeTargets.Delegate, Inherited = false)] public sealed class ExplicitScopeAttribute : Attribute { - public ExplicitScopeAttribute(String assemblyIdentity) + public ExplicitScopeAttribute(string assemblyIdentity) { } } diff --git a/src/System.Private.CoreLib/src/Internal/Reflection/Extensions/NonPortable/CustomAttributeInstantiator.cs b/src/System.Private.CoreLib/src/Internal/Reflection/Extensions/NonPortable/CustomAttributeInstantiator.cs index 260166e554b..c19686db27f 100644 --- a/src/System.Private.CoreLib/src/Internal/Reflection/Extensions/NonPortable/CustomAttributeInstantiator.cs +++ b/src/System.Private.CoreLib/src/Internal/Reflection/Extensions/NonPortable/CustomAttributeInstantiator.cs @@ -48,7 +48,7 @@ public static Attribute Instantiate(this CustomAttributeData cad) { Type parameterType = parameters[i].ParameterType; if (!(parameterType.Equals(constructorArguments[i].ArgumentType) || - parameterType.Equals(typeof(Object)))) + parameterType.Equals(typeof(object)))) break; } if (i == parameters.Length) @@ -65,7 +65,7 @@ public static Attribute Instantiate(this CustomAttributeData cad) // Found the right constructor. Instantiate the Attribute. // int arity = matchingParameters.Length; - Object[] invokeArguments = new Object[arity]; + object[] invokeArguments = new object[arity]; for (int i = 0; i < arity; i++) { invokeArguments[i] = constructorArguments[i].Convert(); @@ -77,9 +77,9 @@ public static Attribute Instantiate(this CustomAttributeData cad) // foreach (CustomAttributeNamedArgument namedArgument in cad.NamedArguments) { - Object argumentValue = namedArgument.TypedValue.Convert(); + object argumentValue = namedArgument.TypedValue.Convert(); Type walk = attributeType; - String name = namedArgument.MemberName; + string name = namedArgument.MemberName; if (namedArgument.IsField) { // Field @@ -122,13 +122,13 @@ public static Attribute Instantiate(this CustomAttributeData cad) // // Convert the argument value reported by Reflection into an actual object. // - private static Object Convert(this CustomAttributeTypedArgument typedArgument) + private static object Convert(this CustomAttributeTypedArgument typedArgument) { Type argumentType = typedArgument.ArgumentType; if (!argumentType.IsArray) { bool isEnum = argumentType.IsEnum; - Object argumentValue = typedArgument.Value; + object argumentValue = typedArgument.Value; if (isEnum) argumentValue = Enum.ToObject(argumentType, argumentValue); return argumentValue; @@ -142,7 +142,7 @@ private static Object Convert(this CustomAttributeTypedArgument typedArgument) Array array = Array.CreateInstance(elementType, typedElements.Count); for (int i = 0; i < typedElements.Count; i++) { - Object elementValue = typedElements[i].Convert(); + object elementValue = typedElements[i].Convert(); array.SetValue(elementValue, i); } return array; diff --git a/src/System.Private.CoreLib/src/Internal/Runtime/Augments/ReflectionExecutionDomainCallbacks.cs b/src/System.Private.CoreLib/src/Internal/Runtime/Augments/ReflectionExecutionDomainCallbacks.cs index c37c0d064dd..bf19ab60832 100644 --- a/src/System.Private.CoreLib/src/Internal/Runtime/Augments/ReflectionExecutionDomainCallbacks.cs +++ b/src/System.Private.CoreLib/src/Internal/Runtime/Augments/ReflectionExecutionDomainCallbacks.cs @@ -47,7 +47,7 @@ public abstract class ReflectionExecutionDomainCallbacks // Flotsam and jetsam. public abstract Exception CreateMissingMetadataException(Type typeWithMissingMetadata); - public abstract String GetBetterDiagnosticInfoIfAvailable(RuntimeTypeHandle runtimeTypeHandle); + public abstract string GetBetterDiagnosticInfoIfAvailable(RuntimeTypeHandle runtimeTypeHandle); public abstract MethodBase GetMethodBaseFromStartAddressIfAvailable(IntPtr methodStartAddress); public abstract int ValueTypeGetHashCodeUsingReflection(object valueType); public abstract bool ValueTypeEqualsUsingReflection(object left, object right); diff --git a/src/System.Private.CoreLib/src/Internal/Runtime/Augments/RuntimeAugments.cs b/src/System.Private.CoreLib/src/Internal/Runtime/Augments/RuntimeAugments.cs index 0213e882102..23c22a9656f 100644 --- a/src/System.Private.CoreLib/src/Internal/Runtime/Augments/RuntimeAugments.cs +++ b/src/System.Private.CoreLib/src/Internal/Runtime/Augments/RuntimeAugments.cs @@ -87,11 +87,11 @@ public static void InitializeStackTraceMetadataSupport(StackTraceMetadataCallbac // // In these cases, this helper returns "null" and ConstructorInfo.Invoke() must deal with these specially. // - public static Object NewObject(RuntimeTypeHandle typeHandle) + public static object NewObject(RuntimeTypeHandle typeHandle) { EETypePtr eeType = typeHandle.ToEETypePtr(); if (eeType.IsNullable - || eeType == EETypePtr.EETypePtrOf() + || eeType == EETypePtr.EETypePtrOf() ) return null; return RuntimeImports.RhNewObject(eeType); @@ -102,7 +102,7 @@ public static Object NewObject(RuntimeTypeHandle typeHandle) // Unlike the NewObject API, this is the raw version that does not special case any EEType, and should be used with // caution for very specific scenarios. // - public static Object RawNewObject(RuntimeTypeHandle typeHandle) + public static object RawNewObject(RuntimeTypeHandle typeHandle) { return RuntimeImports.RhNewObject(typeHandle.ToEETypePtr()); } @@ -192,7 +192,7 @@ public static IntPtr GetFallbackDefaultConstructor() // // Helper to create a delegate on a runtime-supplied type. // - public static Delegate CreateDelegate(RuntimeTypeHandle typeHandleForDelegate, IntPtr ldftnResult, Object thisObject, bool isStatic, bool isOpen) + public static Delegate CreateDelegate(RuntimeTypeHandle typeHandleForDelegate, IntPtr ldftnResult, object thisObject, bool isStatic, bool isOpen) { return Delegate.CreateDelegate(typeHandleForDelegate.ToEETypePtr(), ldftnResult, thisObject, isStatic: isStatic, isOpen: isOpen); } @@ -248,7 +248,7 @@ public static unsafe IntPtr GetThreadStaticFieldAddress(RuntimeTypeHandle typeHa return new IntPtr(RuntimeImports.RhGetThreadStaticFieldAddress(typeHandle.ToEETypePtr(), threadStaticsBlockOffset, fieldOffset)); } - public static unsafe void StoreValueTypeField(IntPtr address, Object fieldValue, RuntimeTypeHandle fieldType) + public static unsafe void StoreValueTypeField(IntPtr address, object fieldValue, RuntimeTypeHandle fieldType) { RuntimeImports.RhUnbox(fieldValue, *(void**)&address, fieldType.ToEETypePtr()); } @@ -258,7 +258,7 @@ public static unsafe void StoreValueTypeField(IntPtr address, Object fieldValue, return ref obj.GetRawData(); } - public static unsafe Object LoadValueTypeField(IntPtr address, RuntimeTypeHandle fieldType) + public static unsafe object LoadValueTypeField(IntPtr address, RuntimeTypeHandle fieldType) { return RuntimeImports.RhBox(fieldType.ToEETypePtr(), *(void**)&address); } @@ -268,12 +268,12 @@ public static unsafe object LoadPointerTypeField(IntPtr address, RuntimeTypeHand return Pointer.Box(*(void**)address, Type.GetTypeFromHandle(fieldType)); } - public static unsafe void StoreValueTypeField(ref byte address, Object fieldValue, RuntimeTypeHandle fieldType) + public static unsafe void StoreValueTypeField(ref byte address, object fieldValue, RuntimeTypeHandle fieldType) { RuntimeImports.RhUnbox(fieldValue, ref address, fieldType.ToEETypePtr()); } - public static unsafe void StoreValueTypeField(Object obj, int fieldOffset, Object fieldValue, RuntimeTypeHandle fieldType) + public static unsafe void StoreValueTypeField(object obj, int fieldOffset, object fieldValue, RuntimeTypeHandle fieldType) { fixed (IntPtr* pObj = &obj.m_pEEType) { @@ -283,7 +283,7 @@ public static unsafe void StoreValueTypeField(Object obj, int fieldOffset, Objec } } - public static unsafe Object LoadValueTypeField(Object obj, int fieldOffset, RuntimeTypeHandle fieldType) + public static unsafe object LoadValueTypeField(object obj, int fieldOffset, RuntimeTypeHandle fieldType) { fixed (IntPtr* pObj = &obj.m_pEEType) { @@ -293,7 +293,7 @@ public static unsafe Object LoadValueTypeField(Object obj, int fieldOffset, Runt } } - public static unsafe Object LoadPointerTypeField(Object obj, int fieldOffset, RuntimeTypeHandle fieldType) + public static unsafe object LoadPointerTypeField(object obj, int fieldOffset, RuntimeTypeHandle fieldType) { fixed (IntPtr* pObj = &obj.m_pEEType) { @@ -303,17 +303,17 @@ public static unsafe Object LoadPointerTypeField(Object obj, int fieldOffset, Ru } } - public static unsafe void StoreReferenceTypeField(IntPtr address, Object fieldValue) + public static unsafe void StoreReferenceTypeField(IntPtr address, object fieldValue) { - Volatile.Write(ref Unsafe.As(ref *(IntPtr*)address), fieldValue); + Volatile.Write(ref Unsafe.As(ref *(IntPtr*)address), fieldValue); } - public static unsafe Object LoadReferenceTypeField(IntPtr address) + public static unsafe object LoadReferenceTypeField(IntPtr address) { - return Volatile.Read(ref Unsafe.As(ref *(IntPtr*)address)); + return Volatile.Read(ref Unsafe.As(ref *(IntPtr*)address)); } - public static unsafe void StoreReferenceTypeField(Object obj, int fieldOffset, Object fieldValue) + public static unsafe void StoreReferenceTypeField(object obj, int fieldOffset, object fieldValue) { fixed (IntPtr* pObj = &obj.m_pEEType) { @@ -323,7 +323,7 @@ public static unsafe void StoreReferenceTypeField(Object obj, int fieldOffset, O } } - public static unsafe Object LoadReferenceTypeField(Object obj, int fieldOffset) + public static unsafe object LoadReferenceTypeField(object obj, int fieldOffset) { fixed (IntPtr* pObj = &obj.m_pEEType) { @@ -473,7 +473,7 @@ public static RuntimeTypeHandle ProjectionTypeForArrays // Note that this is not versionable as it is exposed as a const (and needs to be a const so we can used as a custom attribute argument - which // is the other reason this string is not versionable.) // - public const String HiddenScopeAssemblyName = "HiddenScope, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; + public const string HiddenScopeAssemblyName = "HiddenScope, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; // // This implements the "IsAssignableFrom()" api for runtime-created types. By policy, we let the underlying runtime decide assignability. @@ -716,7 +716,7 @@ public static bool CanPrimitiveWiden(RuntimeTypeHandle srcType, RuntimeTypeHandl return true; } - public static Object CheckArgument(Object srcObject, RuntimeTypeHandle dstType, BinderBundle binderBundle) + public static object CheckArgument(object srcObject, RuntimeTypeHandle dstType, BinderBundle binderBundle) { return InvokeUtils.CheckArgument(srcObject, dstType, binderBundle); } @@ -728,7 +728,7 @@ public static object CheckArgumentForDirectFieldAccess(object srcObject, Runtime return InvokeUtils.CheckArgument(srcObject, dstType.ToEETypePtr(), InvokeUtils.CheckArgumentSemantics.SetFieldDirect, binderBundle: null); } - public static bool IsAssignable(Object srcObject, RuntimeTypeHandle dstType) + public static bool IsAssignable(object srcObject, RuntimeTypeHandle dstType) { EETypePtr srcEEType = srcObject.EETypePtr; return RuntimeImports.AreTypesAssignable(srcEEType, dstType.ToEETypePtr()); @@ -751,9 +751,9 @@ public static RuntimeTypeHandle GetNullableType(RuntimeTypeHandle nullableType) // // Useful helper for finding .pdb's. (This design is admittedly tied to the single-module design of Project N.) // - public static String TryGetFullPathToMainApplication() + public static string TryGetFullPathToMainApplication() { - Func delegateToAnythingInsideMergedApp = TryGetFullPathToMainApplication; + Func delegateToAnythingInsideMergedApp = TryGetFullPathToMainApplication; IntPtr ipToAnywhereInsideMergedApp = delegateToAnythingInsideMergedApp.GetFunctionPointer(out RuntimeTypeHandle _, out bool _, out bool _); IntPtr moduleBase = RuntimeImports.RhGetOSModuleFromPointer(ipToAnywhereInsideMergedApp); return TryGetFullPathToApplicationModule(moduleBase); @@ -763,7 +763,7 @@ public static String TryGetFullPathToMainApplication() /// Locate the file path for a given native application module. /// /// Module base address - public static unsafe String TryGetFullPathToApplicationModule(IntPtr moduleBase) + public static unsafe string TryGetFullPathToApplicationModule(IntPtr moduleBase) { #if PLATFORM_UNIX byte* pModuleNameUtf8; @@ -772,7 +772,7 @@ public static unsafe String TryGetFullPathToApplicationModule(IntPtr moduleBase) #else // PLATFORM_UNIX char* pModuleName; int numChars = RuntimeImports.RhGetModuleFileName(moduleBase, out pModuleName); - String modulePath = new String(pModuleName, 0, numChars); + string modulePath = new string(pModuleName, 0, numChars); #endif // PLATFORM_UNIX return modulePath; } @@ -1111,7 +1111,7 @@ public static unsafe object RhBoxAny(IntPtr pData, IntPtr pEEType) return RuntimeImports.RhBoxAny((void*)pData, new EETypePtr(pEEType)); } - public static IntPtr RhHandleAlloc(Object value, GCHandleType type) + public static IntPtr RhHandleAlloc(object value, GCHandleType type) { return RuntimeImports.RhHandleAlloc(value, type); } diff --git a/src/System.Private.CoreLib/src/Internal/Runtime/Augments/RuntimeThread.cs b/src/System.Private.CoreLib/src/Internal/Runtime/Augments/RuntimeThread.cs index fef6620ee44..3dfb5b07c03 100644 --- a/src/System.Private.CoreLib/src/Internal/Runtime/Augments/RuntimeThread.cs +++ b/src/System.Private.CoreLib/src/Internal/Runtime/Augments/RuntimeThread.cs @@ -516,8 +516,8 @@ private static int RefreshCurrentProcessorId() Debug.Assert(ProcessorIdRefreshRate <= ProcessorIdCacheCountDownMask); - // Mask with Int32.MaxValue to ensure the execution Id is not negative - t_currentProcessorIdCache = ((currentProcessorId << ProcessorIdCacheShift) & Int32.MaxValue) + ProcessorIdRefreshRate; + // Mask with int.MaxValue to ensure the execution Id is not negative + t_currentProcessorIdCache = ((currentProcessorId << ProcessorIdCacheShift) & int.MaxValue) + ProcessorIdRefreshRate; return currentProcessorId; } diff --git a/src/System.Private.CoreLib/src/Internal/Runtime/CompilerHelpers/InteropHelpers.cs b/src/System.Private.CoreLib/src/Internal/Runtime/CompilerHelpers/InteropHelpers.cs index 22af9cf0d14..dc598bbb763 100644 --- a/src/System.Private.CoreLib/src/Internal/Runtime/CompilerHelpers/InteropHelpers.cs +++ b/src/System.Private.CoreLib/src/Internal/Runtime/CompilerHelpers/InteropHelpers.cs @@ -16,7 +16,7 @@ namespace Internal.Runtime.CompilerHelpers /// internal static class InteropHelpers { - internal static unsafe byte* StringToAnsiString(String str, bool bestFit, bool throwOnUnmappableChar) + internal static unsafe byte* StringToAnsiString(string str, bool bestFit, bool throwOnUnmappableChar) { return PInvokeMarshal.StringToAnsiString(str, bestFit, throwOnUnmappableChar); } @@ -38,7 +38,7 @@ public static unsafe string ByValAnsiStringToString(byte* buffer, int length) return PInvokeMarshal.ByValAnsiStringToString(buffer, length); } - internal static unsafe void StringToUnicodeFixedArray(String str, UInt16* buffer, int length) + internal static unsafe void StringToUnicodeFixedArray(string str, ushort* buffer, int length) { if (buffer == null) return; @@ -59,16 +59,16 @@ internal static unsafe void StringToUnicodeFixedArray(String str, UInt16* buffer } } - internal static unsafe string UnicodeToStringFixedArray(UInt16* buffer, int length) + internal static unsafe string UnicodeToStringFixedArray(ushort* buffer, int length) { if (buffer == null) - return String.Empty; + return string.Empty; - string result = String.Empty; + string result = string.Empty; if (length > 0) { - result = new String(' ', length); + result = new string(' ', length); fixed (char* pTemp = result) { @@ -79,7 +79,7 @@ internal static unsafe string UnicodeToStringFixedArray(UInt16* buffer, int leng return result; } - internal static unsafe char* StringToUnicodeBuffer(String str) + internal static unsafe char* StringToUnicodeBuffer(string str) { if (str == null) return null; @@ -99,7 +99,7 @@ internal static unsafe string UnicodeToStringFixedArray(UInt16* buffer, int leng public static unsafe string UnicodeBufferToString(char* buffer) { - return new String(buffer); + return new string(buffer); } public static unsafe byte* AllocMemoryForAnsiStringBuilder(StringBuilder sb) diff --git a/src/System.Private.CoreLib/src/Internal/Runtime/CompilerHelpers/MathHelpers.cs b/src/System.Private.CoreLib/src/Internal/Runtime/CompilerHelpers/MathHelpers.cs index c31521d806b..6947cc9f303 100644 --- a/src/System.Private.CoreLib/src/Internal/Runtime/CompilerHelpers/MathHelpers.cs +++ b/src/System.Private.CoreLib/src/Internal/Runtime/CompilerHelpers/MathHelpers.cs @@ -24,64 +24,64 @@ public static class MathHelpers // Helper to multiply two 32-bit uints [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static UInt64 Mul32x32To64(UInt32 a, UInt32 b) + private static ulong Mul32x32To64(uint a, uint b) { - return a * (UInt64)b; + return a * (ulong)b; } // Helper to get high 32-bit of 64-bit int [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static UInt32 Hi32Bits(Int64 a) + private static uint Hi32Bits(long a) { - return (UInt32)(a >> 32); + return (uint)(a >> 32); } // Helper to get high 32-bit of 64-bit int [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static UInt32 Hi32Bits(UInt64 a) + private static uint Hi32Bits(ulong a) { - return (UInt32)(a >> 32); + return (uint)(a >> 32); } [RuntimeExport("LMulOvf")] - public static Int64 LMulOvf(Int64 i, Int64 j) + public static long LMulOvf(long i, long j) { - Int64 ret; + long ret; // Remember the sign of the result - Int32 sign = (Int32)(Hi32Bits(i) ^ Hi32Bits(j)); + int sign = (int)(Hi32Bits(i) ^ Hi32Bits(j)); // Convert to unsigned multiplication if (i < 0) i = -i; if (j < 0) j = -j; // Get the upper 32 bits of the numbers - UInt32 val1High = Hi32Bits(i); - UInt32 val2High = Hi32Bits(j); + uint val1High = Hi32Bits(i); + uint val2High = Hi32Bits(j); - UInt64 valMid; + ulong valMid; if (val1High == 0) { // Compute the 'middle' bits of the long multiplication - valMid = Mul32x32To64(val2High, (UInt32)i); + valMid = Mul32x32To64(val2High, (uint)i); } else { if (val2High != 0) goto ThrowExcep; // Compute the 'middle' bits of the long multiplication - valMid = Mul32x32To64(val1High, (UInt32)j); + valMid = Mul32x32To64(val1High, (uint)j); } // See if any bits after bit 32 are set if (Hi32Bits(valMid) != 0) goto ThrowExcep; - ret = (Int64)(Mul32x32To64((UInt32)i, (UInt32)j) + (valMid << 32)); + ret = (long)(Mul32x32To64((uint)i, (uint)j) + (valMid << 32)); // check for overflow - if (Hi32Bits(ret) < (UInt32)valMid) + if (Hi32Bits(ret) < (uint)valMid) goto ThrowExcep; if (sign >= 0) @@ -104,39 +104,39 @@ public static Int64 LMulOvf(Int64 i, Int64 j) } [RuntimeExport("ULMulOvf")] - public static UInt64 ULMulOvf(UInt64 i, UInt64 j) + public static ulong ULMulOvf(ulong i, ulong j) { - UInt64 ret; + ulong ret; // Get the upper 32 bits of the numbers - UInt32 val1High = Hi32Bits(i); - UInt32 val2High = Hi32Bits(j); + uint val1High = Hi32Bits(i); + uint val2High = Hi32Bits(j); - UInt64 valMid; + ulong valMid; if (val1High == 0) { if (val2High == 0) - return Mul32x32To64((UInt32)i, (UInt32)j); + return Mul32x32To64((uint)i, (uint)j); // Compute the 'middle' bits of the long multiplication - valMid = Mul32x32To64(val2High, (UInt32)i); + valMid = Mul32x32To64(val2High, (uint)i); } else { if (val2High != 0) goto ThrowExcep; // Compute the 'middle' bits of the long multiplication - valMid = Mul32x32To64(val1High, (UInt32)j); + valMid = Mul32x32To64(val1High, (uint)j); } // See if any bits after bit 32 are set if (Hi32Bits(valMid) != 0) goto ThrowExcep; - ret = Mul32x32To64((UInt32)i, (UInt32)j) + (valMid << 32); + ret = Mul32x32To64((uint)i, (uint)j) + (valMid << 32); // check for overflow - if (Hi32Bits(ret) < (UInt32)valMid) + if (Hi32Bits(ret) < (uint)valMid) goto ThrowExcep; return ret; @@ -212,7 +212,7 @@ public static long Flt2LngOvf(float val) // Note that this expression also works properly for val = NaN case // We need to compare with the very next double to two63. 0x402 is epsilon to get us there. if (val > -two63 - 0x402 && val < two63) - return ((Int64)val); + return ((long)val); return ThrowIntOvf(); } @@ -222,13 +222,13 @@ public static long Flt2LngOvf(float val) [RuntimeImport(RuntimeLibrary, "RhpIDiv")] [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern Int32 RhpIDiv(Int32 i, Int32 j); + private static extern int RhpIDiv(int i, int j); - public static int IDiv(Int32 i, Int32 j) + public static int IDiv(int i, int j) { if (j == 0) return ThrowIntDivByZero(); - else if (j == -1 && i == Int32.MinValue) + else if (j == -1 && i == int.MinValue) return ThrowIntArithExc(); else return RhpIDiv(i, j); @@ -236,9 +236,9 @@ public static int IDiv(Int32 i, Int32 j) [RuntimeImport(RuntimeLibrary, "RhpUDiv")] [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern UInt32 RhpUDiv(UInt32 i, UInt32 j); + private static extern uint RhpUDiv(uint i, uint j); - public static long UDiv(UInt32 i, UInt32 j) + public static long UDiv(uint i, uint j) { if (j == 0) return ThrowUIntDivByZero(); @@ -248,9 +248,9 @@ public static long UDiv(UInt32 i, UInt32 j) [RuntimeImport(RuntimeLibrary, "RhpULDiv")] [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern UInt64 RhpULDiv(UInt64 i, UInt64 j); + private static extern ulong RhpULDiv(ulong i, ulong j); - public static ulong ULDiv(UInt64 i, UInt64 j) + public static ulong ULDiv(ulong i, ulong j) { if (j == 0) return ThrowULngDivByZero(); @@ -260,13 +260,13 @@ public static ulong ULDiv(UInt64 i, UInt64 j) [RuntimeImport(RuntimeLibrary, "RhpLDiv")] [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern Int64 RhpLDiv(Int64 i, Int64 j); + private static extern long RhpLDiv(long i, long j); - public static long LDiv(Int64 i, Int64 j) + public static long LDiv(long i, long j) { if (j == 0) return ThrowLngDivByZero(); - else if (j == -1 && i == Int64.MinValue) + else if (j == -1 && i == long.MinValue) return ThrowLngArithExc(); else return RhpLDiv(i, j); @@ -274,9 +274,9 @@ public static long LDiv(Int64 i, Int64 j) [RuntimeImport(RuntimeLibrary, "RhpIMod")] [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern Int32 RhpIMod(Int32 i, Int32 j); + private static extern int RhpIMod(int i, int j); - public static int IMod(Int32 i, Int32 j) + public static int IMod(int i, int j) { if (j == 0) return ThrowIntDivByZero(); @@ -286,9 +286,9 @@ public static int IMod(Int32 i, Int32 j) [RuntimeImport(RuntimeLibrary, "RhpUMod")] [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern UInt32 RhpUMod(UInt32 i, UInt32 j); + private static extern uint RhpUMod(uint i, uint j); - public static long UMod(UInt32 i, UInt32 j) + public static long UMod(uint i, uint j) { if (j == 0) return ThrowUIntDivByZero(); @@ -298,9 +298,9 @@ public static long UMod(UInt32 i, UInt32 j) [RuntimeImport(RuntimeLibrary, "RhpULMod")] [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern UInt64 RhpULMod(UInt64 i, UInt64 j); + private static extern ulong RhpULMod(ulong i, ulong j); - public static ulong ULMod(UInt64 i, UInt64 j) + public static ulong ULMod(ulong i, ulong j) { if (j == 0) return ThrowULngDivByZero(); @@ -310,9 +310,9 @@ public static ulong ULMod(UInt64 i, UInt64 j) [RuntimeImport(RuntimeLibrary, "RhpLMod")] [MethodImplAttribute(MethodImplOptions.InternalCall)] - private static extern Int64 RhpLMod(Int64 i, Int64 j); + private static extern long RhpLMod(long i, long j); - public static long LMod(Int64 i, Int64 j) + public static long LMod(long i, long j) { if (j == 0) return ThrowLngDivByZero(); diff --git a/src/System.Private.CoreLib/src/Internal/Runtime/CompilerHelpers/SynchronizedMethodHelpers.cs b/src/System.Private.CoreLib/src/Internal/Runtime/CompilerHelpers/SynchronizedMethodHelpers.cs index 30694aeadb4..018c8005c3d 100644 --- a/src/System.Private.CoreLib/src/Internal/Runtime/CompilerHelpers/SynchronizedMethodHelpers.cs +++ b/src/System.Private.CoreLib/src/Internal/Runtime/CompilerHelpers/SynchronizedMethodHelpers.cs @@ -54,7 +54,7 @@ private static void MonitorExitStatic(IntPtr pEEType, ref bool lockTaken) lockTaken = false; } - private static Object GetStaticLockObject(IntPtr pEEType) + private static object GetStaticLockObject(IntPtr pEEType) { return Internal.Reflection.Core.NonPortable.RuntimeTypeUnifier.GetRuntimeTypeForEEType(new System.EETypePtr(pEEType)); } diff --git a/src/System.Private.CoreLib/src/Internal/Runtime/CompilerServices/RelocatedTypeAttribute.cs b/src/System.Private.CoreLib/src/Internal/Runtime/CompilerServices/RelocatedTypeAttribute.cs index a848f5a94a0..74363b72b91 100644 --- a/src/System.Private.CoreLib/src/Internal/Runtime/CompilerServices/RelocatedTypeAttribute.cs +++ b/src/System.Private.CoreLib/src/Internal/Runtime/CompilerServices/RelocatedTypeAttribute.cs @@ -19,7 +19,7 @@ public class RelocatedTypeAttribute : Attribute /// /// Simple name of the CoreFX assembly the type was relocated from. /// For example, System.Collections (with no version or public key token) - public RelocatedTypeAttribute(String originalAssemblySimpleName) + public RelocatedTypeAttribute(string originalAssemblySimpleName) { } } diff --git a/src/System.Private.CoreLib/src/Internal/Runtime/ThreadStatics.cs b/src/System.Private.CoreLib/src/Internal/Runtime/ThreadStatics.cs index db6977ee52c..fc8e142cdbf 100644 --- a/src/System.Private.CoreLib/src/Internal/Runtime/ThreadStatics.cs +++ b/src/System.Private.CoreLib/src/Internal/Runtime/ThreadStatics.cs @@ -18,10 +18,10 @@ internal static class ThreadStatics /// This method is called from a ReadyToRun helper to get base address of thread /// static storage for the given type. /// - internal static unsafe object GetThreadStaticBaseForType(TypeManagerSlot* pModuleData, Int32 typeTlsIndex) + internal static unsafe object GetThreadStaticBaseForType(TypeManagerSlot* pModuleData, int typeTlsIndex) { // Get the array that holds thread static memory blocks for each type in the given module - Int32 moduleIndex = pModuleData->ModuleIndex; + int moduleIndex = pModuleData->ModuleIndex; object[] storage = (object[])RuntimeImports.RhGetThreadStaticStorageForModule(moduleIndex); // Check whether thread static storage has already been allocated for this module and type. @@ -45,7 +45,7 @@ internal static unsafe object GetThreadStaticBaseForType(TypeManagerSlot* pModul /// if it is required, this method extends thread static storage of the given module /// to the specified size and then registers the memory with the runtime. /// - private static object[] EnsureThreadStaticStorage(Int32 moduleIndex, object[] existingStorage, Int32 requiredSize) + private static object[] EnsureThreadStaticStorage(int moduleIndex, object[] existingStorage, int requiredSize) { if ((existingStorage != null) && (requiredSize < existingStorage.Length)) { @@ -73,9 +73,9 @@ private static object[] EnsureThreadStaticStorage(Int32 moduleIndex, object[] ex /// This method allocates an object that represents a memory block for all thread static fields of the type /// that corresponds to the specified TLS index. /// - private static unsafe object AllocateThreadStaticStorageForType(TypeManagerHandle typeManager, Int32 typeTlsIndex) + private static unsafe object AllocateThreadStaticStorageForType(TypeManagerHandle typeManager, int typeTlsIndex) { - Int32 length; + int length; IntPtr* threadStaticRegion; // Get a pointer to the beginning of the module's Thread Static section. Then get a pointer diff --git a/src/System.Private.CoreLib/src/Internal/Threading/Tasks/AsyncCausalitySupport.cs b/src/System.Private.CoreLib/src/Internal/Threading/Tasks/AsyncCausalitySupport.cs index f9cd9d037dc..ef427a3ca6e 100644 --- a/src/System.Private.CoreLib/src/Internal/Threading/Tasks/AsyncCausalitySupport.cs +++ b/src/System.Private.CoreLib/src/Internal/Threading/Tasks/AsyncCausalitySupport.cs @@ -42,7 +42,7 @@ public static bool LoggingOn } [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void TraceOperationCreation(Task task, String operationName) + public static void TraceOperationCreation(Task task, string operationName) { DebuggerSupport.TraceOperationCreation(CausalityTraceLevel.Required, task, operationName, 0); } diff --git a/src/System.Private.CoreLib/src/Microsoft/Win32/RegistryKey.Windows.cs b/src/System.Private.CoreLib/src/Microsoft/Win32/RegistryKey.Windows.cs index 5076c4774cf..cd3237d24ee 100644 --- a/src/System.Private.CoreLib/src/Microsoft/Win32/RegistryKey.Windows.cs +++ b/src/System.Private.CoreLib/src/Microsoft/Win32/RegistryKey.Windows.cs @@ -397,15 +397,15 @@ private object InternalGetValueCore(string name, object defaultValue, bool doNot byte[] blob = new byte[size]; while (Interop.Errors.ERROR_MORE_DATA == (r = Interop.mincore.RegQueryValueEx(_hkey, name, null, ref type, blob, ref sizeInput))) { - if (size == Int32.MaxValue) + if (size == int.MaxValue) { - // ERROR_MORE_DATA was returned however we cannot increase the buffer size beyond Int32.MaxValue + // ERROR_MORE_DATA was returned however we cannot increase the buffer size beyond int.MaxValue Win32Error(r, name); } - else if (size > (Int32.MaxValue / 2)) + else if (size > (int.MaxValue / 2)) { // at this point in the loop "size * 2" would cause an overflow - size = Int32.MaxValue; + size = int.MaxValue; } else { diff --git a/src/System.Private.CoreLib/src/System/AppContext.cs b/src/System.Private.CoreLib/src/System/AppContext.cs index 6b316a4487c..0858f357aca 100644 --- a/src/System.Private.CoreLib/src/System/AppContext.cs +++ b/src/System.Private.CoreLib/src/System/AppContext.cs @@ -25,7 +25,7 @@ private enum SwitchValueState UnknownValue = 0x8 // Has no default and could not find an override } private static readonly Dictionary s_switchMap = new Dictionary(); - private static Dictionary s_localStore = new Dictionary(); + private static Dictionary s_localStore = new Dictionary(); private static string s_defaultBaseDirectory; // AppDomain lives in CoreFX, but some of this class's events need to pass in AppDomains, so people registering those // events need to first pass in an AppDomain that we stash here to pass back in the events. diff --git a/src/System.Private.CoreLib/src/System/AppContextDefaultValues.cs b/src/System.Private.CoreLib/src/System/AppContextDefaultValues.cs index a0093c94a3d..3dd5d55f575 100644 --- a/src/System.Private.CoreLib/src/System/AppContextDefaultValues.cs +++ b/src/System.Private.CoreLib/src/System/AppContextDefaultValues.cs @@ -32,14 +32,14 @@ public static void PopulateDefaultValues() // - The identifier and version is required, profile is optional // - Only three components are allowed. // - The version string must be in the System.Version format; an optional "v" or "V" prefix is allowed - private static bool TryParseFrameworkName(String frameworkName, out String identifier, out int version, out String profile) + private static bool TryParseFrameworkName(string frameworkName, out string identifier, out int version, out string profile) { // For parsing a target Framework moniker, from the FrameworkName class const char c_componentSeparator = ','; const char c_keyValueSeparator = '='; const char c_versionValuePrefix = 'v'; - const String c_versionKey = "Version"; - const String c_profileKey = "Profile"; + const string c_versionKey = "Version"; + const string c_profileKey = "Profile"; identifier = profile = string.Empty; version = 0; @@ -49,7 +49,7 @@ private static bool TryParseFrameworkName(String frameworkName, out String ident return false; } - String[] components = frameworkName.Split(c_componentSeparator); + string[] components = frameworkName.Split(c_componentSeparator); version = 0; // Identifer and Version are required, Profile is optional. @@ -113,7 +113,7 @@ private static bool TryParseFrameworkName(String frameworkName, out String ident // else if (key.Equals(c_profileKey, StringComparison.OrdinalIgnoreCase)) { - if (!String.IsNullOrEmpty(value)) + if (!string.IsNullOrEmpty(value)) { profile = value; } diff --git a/src/System.Private.CoreLib/src/System/Array.CoreRT.cs b/src/System.Private.CoreLib/src/System/Array.CoreRT.cs index 80c4d2bbf0c..f4c57285af8 100644 --- a/src/System.Private.CoreLib/src/System/Array.CoreRT.cs +++ b/src/System.Private.CoreLib/src/System/Array.CoreRT.cs @@ -445,7 +445,7 @@ private static unsafe void CopyImplValueTypeArrayToReferenceArray(Array sourceAr ref object refDestinationArray = ref Unsafe.As(ref destinationArray.GetRawArrayData()); for (int i = 0; i < length; i++) { - Object boxedValue = RuntimeImports.RhBox(sourceElementEEType, pElement); + object boxedValue = RuntimeImports.RhBox(sourceElementEEType, pElement); Unsafe.Add(ref refDestinationArray, destinationIndex + i) = boxedValue; pElement += sourceElementSize; } @@ -474,7 +474,7 @@ private static unsafe void CopyImplReferenceArrayToValueTypeArray(Array sourceAr for (int i = 0; i < length; i++) { - Object boxedValue = Unsafe.Add(ref refSourceArray, sourceIndex + i); + object boxedValue = Unsafe.Add(ref refSourceArray, sourceIndex + i); if (boxedValue == null) { if (!isNullable) @@ -918,7 +918,7 @@ internal static unsafe Array NewMultiDimArray(EETypePtr eeType, int* pLengths, i if (length > MaxArrayLength) maxArrayDimensionLengthOverflow = true; totalLength = totalLength * (ulong)length; - if (totalLength > Int32.MaxValue) + if (totalLength > int.MaxValue) throw new OutOfMemoryException(); // "Array dimensions exceeded supported range." } @@ -938,14 +938,14 @@ internal static unsafe Array NewMultiDimArray(EETypePtr eeType, int* pLengths, i } // Wraps an IComparer inside an IComparer. - private sealed class ComparerAsComparerT : IComparer + private sealed class ComparerAsComparerT : IComparer { public ComparerAsComparerT(IComparer comparer) { _comparer = (comparer == null) ? Comparer.Default : comparer; } - public int Compare(Object x, Object y) + public int Compare(object x, object y) { return _comparer.Compare(x, y); } @@ -999,7 +999,7 @@ public int GetUpperBound(int dimension) return Length - 1; } - public unsafe Object GetValue(int index) + public unsafe object GetValue(int index) { if (!IsSzArray) { @@ -1018,7 +1018,7 @@ public unsafe Object GetValue(int index) return GetValueWithFlattenedIndex_NoErrorCheck(index); } - public unsafe Object GetValue(int index1, int index2) + public unsafe object GetValue(int index1, int index2) { if (Rank != 2) throw new ArgumentException(SR.Arg_Need2DArray); @@ -1029,7 +1029,7 @@ public unsafe Object GetValue(int index1, int index2) return GetValue(pIndices, 2); } - public unsafe Object GetValue(int index1, int index2, int index3) + public unsafe object GetValue(int index1, int index2, int index3) { if (Rank != 3) throw new ArgumentException(SR.Arg_Need3DArray); @@ -1041,7 +1041,7 @@ public unsafe Object GetValue(int index1, int index2, int index3) return GetValue(pIndices, 3); } - public unsafe Object GetValue(params int[] indices) + public unsafe object GetValue(params int[] indices) { if (indices == null) throw new ArgumentNullException(nameof(indices)); @@ -1059,7 +1059,7 @@ public unsafe Object GetValue(params int[] indices) return GetValue(pIndices, length); } - private unsafe Object GetValue(int* pIndices, int rank) + private unsafe object GetValue(int* pIndices, int rank) { Debug.Assert(Rank == rank); Debug.Assert(!IsSzArray); @@ -1085,7 +1085,7 @@ private unsafe Object GetValue(int* pIndices, int rank) return GetValueWithFlattenedIndex_NoErrorCheck(flattenedIndex); } - private Object GetValueWithFlattenedIndex_NoErrorCheck(int flattenedIndex) + private object GetValueWithFlattenedIndex_NoErrorCheck(int flattenedIndex) { ref byte element = ref Unsafe.AddByteOffset(ref GetRawArrayData(), (nuint)flattenedIndex * ElementSize); @@ -1101,7 +1101,7 @@ private Object GetValueWithFlattenedIndex_NoErrorCheck(int flattenedIndex) } } - public unsafe void SetValue(Object value, int index) + public unsafe void SetValue(object value, int index) { if (!IsSzArray) { @@ -1146,7 +1146,7 @@ public unsafe void SetValue(Object value, int index) } } - public unsafe void SetValue(Object value, int index1, int index2) + public unsafe void SetValue(object value, int index1, int index2) { if (Rank != 2) throw new ArgumentException(SR.Arg_Need2DArray); @@ -1157,7 +1157,7 @@ public unsafe void SetValue(Object value, int index1, int index2) SetValue(value, pIndices, 2); } - 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) throw new ArgumentException(SR.Arg_Need3DArray); @@ -1169,7 +1169,7 @@ public unsafe void SetValue(Object value, int index1, int index2, int index3) SetValue(value, pIndices, 3); } - public unsafe void SetValue(Object value, params int[] indices) + public unsafe void SetValue(object value, params int[] indices) { if (indices == null) throw new ArgumentNullException(nameof(indices)); @@ -1193,7 +1193,7 @@ public unsafe void SetValue(Object value, params int[] indices) } } - private unsafe void SetValue(Object value, int* pIndices, int rank) + private unsafe void SetValue(object value, int* pIndices, int rank) { Debug.Assert(Rank == rank); Debug.Assert(!IsSzArray); @@ -1241,7 +1241,7 @@ private unsafe void SetValue(Object value, int* pIndices, int rank) { throw new InvalidCastException(SR.InvalidCast_StoreArrayElement); } - Unsafe.As(ref element) = value; + Unsafe.As(ref element) = value; } } @@ -1255,7 +1255,7 @@ internal EETypePtr ElementEEType private sealed partial class ArrayEnumerator : IEnumerator, ICloneable { - public Object Current + public object Current { get { @@ -1332,9 +1332,9 @@ private static int LastIndexOfImpl(T[] array, T value, int startIndex, int co static void SortImpl(Array keys, Array items, int index, int length, IComparer comparer) { - IComparer comparerT = new ComparerAsComparerT(comparer); - Object[] objKeys = keys as Object[]; - Object[] objItems = items as Object[]; + IComparer comparerT = new ComparerAsComparerT(comparer); + object[] objKeys = keys as object[]; + object[] objItems = items as object[]; // Unfortunately, on Project N, we don't have the ability to specialize ArraySortHelper<> on demand // for value types. Rather than incur a boxing cost on every compare and every swap (and maintain a separate introsort algorithm @@ -1343,12 +1343,12 @@ static void SortImpl(Array keys, Array items, int index, int length, IComparer c // Check if either of the arrays need to be copied. if (objKeys == null) { - objKeys = new Object[index + length]; + objKeys = new object[index + length]; Array.CopyImplValueTypeArrayToReferenceArray(keys, index, objKeys, index, length, reliable: false); } if (objItems == null && items != null) { - objItems = new Object[index + length]; + objItems = new object[index + length]; Array.CopyImplValueTypeArrayToReferenceArray(items, index, objItems, index, length, reliable: false); } diff --git a/src/System.Private.CoreLib/src/System/Array.cs b/src/System.Private.CoreLib/src/System/Array.cs index bebba4feec1..ecdbd4baf75 100644 --- a/src/System.Private.CoreLib/src/System/Array.cs +++ b/src/System.Private.CoreLib/src/System/Array.cs @@ -78,7 +78,7 @@ int ICollection.Count bool IList.IsReadOnly { get { return false; } } - Object IList.this[int index] + object IList.this[int index] { get { @@ -91,12 +91,12 @@ bool IList.IsReadOnly } } - int IList.Add(Object value) + int IList.Add(object value) { throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); } - bool IList.Contains(Object value) + bool IList.Contains(object value) { return Array.IndexOf(this, value) >= 0; } @@ -106,17 +106,17 @@ void IList.Clear() Array.Clear(this, GetLowerBound(0), this.Length); } - int IList.IndexOf(Object value) + int IList.IndexOf(object value) { return Array.IndexOf(this, value); } - void IList.Insert(int index, Object value) + void IList.Insert(int index, object value) { throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); } - void IList.Remove(Object value) + void IList.Remove(object value) { throw new NotSupportedException(SR.NotSupported_FixedSizeCollection); } @@ -144,12 +144,12 @@ public void CopyTo(Array array, int index) // Make a new array which is a deep copy of the original array. // - public Object Clone() + public object Clone() { return MemberwiseClone(); } - Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) + int IStructuralComparable.CompareTo(object other, IComparer comparer) { if (other == null) { @@ -178,14 +178,14 @@ Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) return c; } - Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) + bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) { if (other == null) { return false; } - if (Object.ReferenceEquals(this, other)) + if (object.ReferenceEquals(this, other)) { return true; } @@ -247,7 +247,7 @@ int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) // negative result to produce the index of the first element (if any) that // is larger than the given search value. // - public static int BinarySearch(Array array, Object value) + public static int BinarySearch(Array array, object value) { if (array == null) throw new ArgumentNullException(nameof(array)); @@ -272,7 +272,7 @@ public static int BinarySearch(Array array, Object value) public static void Copy(Array sourceArray, Array destinationArray, long length) { - if (length > Int32.MaxValue || length < Int32.MinValue) + if (length > int.MaxValue || length < int.MinValue) throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_HugeArrayNotSupported); Array.Copy(sourceArray, destinationArray, (int)length); @@ -280,11 +280,11 @@ public static void Copy(Array sourceArray, Array destinationArray, long length) public static void Copy(Array sourceArray, long sourceIndex, Array destinationArray, long destinationIndex, long length) { - if (sourceIndex > Int32.MaxValue || sourceIndex < Int32.MinValue) + if (sourceIndex > int.MaxValue || sourceIndex < int.MinValue) throw new ArgumentOutOfRangeException(nameof(sourceIndex), SR.ArgumentOutOfRange_HugeArrayNotSupported); - if (destinationIndex > Int32.MaxValue || destinationIndex < Int32.MinValue) + if (destinationIndex > int.MaxValue || destinationIndex < int.MinValue) throw new ArgumentOutOfRangeException(nameof(destinationIndex), SR.ArgumentOutOfRange_HugeArrayNotSupported); - if (length > Int32.MaxValue || length < Int32.MinValue) + if (length > int.MaxValue || length < int.MinValue) throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_HugeArrayNotSupported); Array.Copy(sourceArray, (int)sourceIndex, destinationArray, (int)destinationIndex, (int)length); @@ -292,7 +292,7 @@ public static void Copy(Array sourceArray, long sourceIndex, Array destinationAr public void CopyTo(Array array, long index) { - if (index > Int32.MaxValue || index < Int32.MinValue) + if (index > int.MaxValue || index < int.MinValue) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_HugeArrayNotSupported); this.CopyTo(array, (int)index); @@ -334,37 +334,37 @@ public long GetLongLength(int dimension) return GetLength(dimension); } - public Object GetValue(long index) + public object GetValue(long index) { - if (index > Int32.MaxValue || index < Int32.MinValue) + if (index > int.MaxValue || index < int.MinValue) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_HugeArrayNotSupported); return this.GetValue((int)index); } - public Object GetValue(long index1, long index2) + public object GetValue(long index1, long index2) { - if (index1 > Int32.MaxValue || index1 < Int32.MinValue) + if (index1 > int.MaxValue || index1 < int.MinValue) throw new ArgumentOutOfRangeException(nameof(index1), SR.ArgumentOutOfRange_HugeArrayNotSupported); - if (index2 > Int32.MaxValue || index2 < Int32.MinValue) + if (index2 > int.MaxValue || index2 < int.MinValue) throw new ArgumentOutOfRangeException(nameof(index2), SR.ArgumentOutOfRange_HugeArrayNotSupported); return this.GetValue((int)index1, (int)index2); } - public Object GetValue(long index1, long index2, long index3) + public object GetValue(long index1, long index2, long index3) { - if (index1 > Int32.MaxValue || index1 < Int32.MinValue) + if (index1 > int.MaxValue || index1 < int.MinValue) throw new ArgumentOutOfRangeException(nameof(index1), SR.ArgumentOutOfRange_HugeArrayNotSupported); - if (index2 > Int32.MaxValue || index2 < Int32.MinValue) + if (index2 > int.MaxValue || index2 < int.MinValue) throw new ArgumentOutOfRangeException(nameof(index2), SR.ArgumentOutOfRange_HugeArrayNotSupported); - if (index3 > Int32.MaxValue || index3 < Int32.MinValue) + if (index3 > int.MaxValue || index3 < int.MinValue) throw new ArgumentOutOfRangeException(nameof(index3), SR.ArgumentOutOfRange_HugeArrayNotSupported); return this.GetValue((int)index1, (int)index2, (int)index3); } - public Object GetValue(params long[] indices) + public object GetValue(params long[] indices) { if (indices == null) throw new ArgumentNullException(nameof(indices)); @@ -376,7 +376,7 @@ public Object GetValue(params long[] indices) for (int i = 0; i < indices.Length; ++i) { long index = indices[i]; - if (index > Int32.MaxValue || index < Int32.MinValue) + if (index > int.MaxValue || index < int.MinValue) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_HugeArrayNotSupported); intIndices[i] = (int)index; } @@ -396,7 +396,7 @@ public Object GetValue(params long[] indices) // Returns an object appropriate for synchronizing access to this // Array. - public Object SyncRoot { get { return this; } } + public object SyncRoot { get { return this; } } // 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 @@ -411,7 +411,7 @@ public Object GetValue(params long[] indices) // negative result to produce the index of the first element (if any) that // is larger than the given search value. // - 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); } @@ -430,7 +430,7 @@ public static int BinarySearch(Array array, int index, int length, Object value) // negative result to produce the index of the first element (if any) that // is larger than the given search value. // - public static int BinarySearch(Array array, Object value, IComparer comparer) + public static int BinarySearch(Array array, object value, IComparer comparer) { if (array == null) throw new ArgumentNullException(nameof(array)); @@ -452,7 +452,7 @@ public static int BinarySearch(Array array, Object value, IComparer comparer) // negative result to produce the index of the first element (if any) that // is larger than the given search value. // - public static int BinarySearch(Array array, int index, int length, Object value, IComparer comparer) + public static int BinarySearch(Array array, int index, int length, object value, IComparer comparer) { if (array == null) throw new ArgumentNullException(nameof(array)); @@ -468,7 +468,7 @@ public static int BinarySearch(Array array, int index, int length, Object value, int lo = index; int hi = index + length - 1; - Object[] objArray = array as Object[]; + object[] objArray = array as object[]; if (objArray != null) { while (lo <= hi) @@ -566,7 +566,7 @@ public static int BinarySearch(T[] array, int index, int length, T value, Sys // 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) + public static int IndexOf(Array array, object value) { if (array == null) { @@ -582,7 +582,7 @@ public static int IndexOf(Array array, Object value) // 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) + public static int IndexOf(Array array, object value, int startIndex) { if (array == null) { @@ -599,7 +599,7 @@ public static int IndexOf(Array array, Object value, int startIndex) // 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) + public static int IndexOf(Array array, object value, int startIndex, int count) { if (array == null) throw new ArgumentNullException(nameof(array)); @@ -611,7 +611,7 @@ public static int IndexOf(Array array, Object value, int startIndex, int count) if (count < 0 || count > array.Length - startIndex + lb) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count); - Object[] objArray = array as Object[]; + object[] objArray = array as object[]; int endIndex = startIndex + count; if (objArray != null) { @@ -626,7 +626,7 @@ public static int IndexOf(Array array, Object value, int startIndex, int count) { for (int i = startIndex; i < endIndex; i++) { - Object obj = objArray[i]; + object obj = objArray[i]; if (obj != null && obj.Equals(value)) return i; } } @@ -635,7 +635,7 @@ public static int IndexOf(Array array, Object value, int startIndex, int count) { for (int i = startIndex; i < endIndex; i++) { - Object obj = array.GetValue(i); + object obj = array.GetValue(i); if (obj == null) { if (value == null) return i; @@ -694,7 +694,7 @@ public static int IndexOf(T[] array, T value, int startIndex, int count) return IndexOfImpl(array, value, startIndex, count); } - public static int LastIndexOf(Array array, Object value) + public static int LastIndexOf(Array array, object value) { if (array == null) throw new ArgumentNullException(nameof(array)); @@ -707,7 +707,7 @@ public static int LastIndexOf(Array array, Object value) // 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) throw new ArgumentNullException(nameof(array)); @@ -721,7 +721,7 @@ public static int LastIndexOf(Array array, Object value, int startIndex) // 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) + public static int LastIndexOf(Array array, object value, int startIndex, int count) { if (array == null) throw new ArgumentNullException(nameof(array)); @@ -740,7 +740,7 @@ public static int LastIndexOf(Array array, Object value, int startIndex, int cou if (array.Rank != 1) throw new RankException(SR.Rank_MultiDimNotSupported); - Object[] objArray = array as Object[]; + object[] objArray = array as object[]; int endIndex = startIndex - count + 1; if (objArray != null) { @@ -755,7 +755,7 @@ public static int LastIndexOf(Array array, Object value, int startIndex, int cou { for (int i = startIndex; i >= endIndex; i--) { - Object obj = objArray[i]; + object obj = objArray[i]; if (obj != null && obj.Equals(value)) return i; } } @@ -764,7 +764,7 @@ public static int LastIndexOf(Array array, Object value, int startIndex, int cou { for (int i = startIndex; i >= endIndex; i--) { - Object obj = array.GetValue(i); + object obj = array.GetValue(i); if (obj == null) { if (value == null) return i; @@ -871,7 +871,7 @@ public static void Reverse(Array array, int index, int length) if (array.Rank != 1) throw new RankException(SR.Rank_MultiDimNotSupported); - Object[] objArray = array as Object[]; + object[] objArray = array as object[]; if (objArray != null) { Array.Reverse(objArray, index, length); @@ -882,7 +882,7 @@ public static void Reverse(Array array, int index, int length) int j = index + length - 1; while (i < j) { - Object temp = array.GetValue(i); + object temp = array.GetValue(i); array.SetValue(array.GetValue(j), i); array.SetValue(temp, j); i++; diff --git a/src/System.Private.CoreLib/src/System/Attribute.cs b/src/System.Private.CoreLib/src/System/Attribute.cs index 5f20722e2b4..8c48f16e300 100644 --- a/src/System.Private.CoreLib/src/System/Attribute.cs +++ b/src/System.Private.CoreLib/src/System/Attribute.cs @@ -20,7 +20,7 @@ public abstract partial class Attribute // // This implementation implements the .NET Core behavior. // - public override bool Equals(Object obj) + public override bool Equals(object obj) { if (obj == null) return false; @@ -28,14 +28,14 @@ public override bool Equals(Object obj) if (this.GetType() != obj.GetType()) return false; - Object[] thisFieldValues = this.ReadFields(); - Object[] thatfieldValues = ((Attribute)obj).ReadFields(); + object[] thisFieldValues = this.ReadFields(); + object[] thatfieldValues = ((Attribute)obj).ReadFields(); for (int i = 0; i < thisFieldValues.Length; i++) { // Visibility check and consistency check are not necessary. - Object thisResult = thisFieldValues[i]; - Object thatResult = thatfieldValues[i]; + object thisResult = thisFieldValues[i]; + object thatResult = thatfieldValues[i]; if (!AreFieldValuesEqual(thisResult, thatResult)) { @@ -47,7 +47,7 @@ public override bool Equals(Object obj) } // Compares values of custom-attribute fields. - private static bool AreFieldValuesEqual(Object thisValue, Object thatValue) + private static bool AreFieldValuesEqual(object thisValue, object thatValue) { if (thisValue == null && thatValue == null) return true; @@ -97,12 +97,12 @@ private static bool AreFieldValuesEqual(Object thisValue, Object thatValue) public override int GetHashCode() { - Object vThis = null; + object vThis = null; - Object[] fieldValues = this.ReadFields(); + object[] fieldValues = this.ReadFields(); for (int i = 0; i < fieldValues.Length; i++) { - Object fieldValue = fieldValues[i]; + object fieldValue = fieldValues[i]; // The hashcode of an array ignores the contents of the array, so it can produce // different hashcodes for arrays with the same contents. @@ -150,7 +150,7 @@ protected virtual int _ILT_GetNumFields() // offset inside a caller-supplied array. Attribute.ReadFields() calls _ILT_GetNumFields() to figure out how large an array is needed. // [CLSCompliant(false)] - protected virtual void _ILT_ReadFields(Object[] destination, int offset) + protected virtual void _ILT_ReadFields(object[] destination, int offset) { } @@ -158,10 +158,10 @@ protected virtual void _ILT_ReadFields(Object[] destination, int offset) // ProjectN: Unlike the desktop, low level code such as Attributes cannot go running off to Reflection to fetch the FieldInfo's. // Instead, we use the ILTransform to generate a method that returns the relevant field values, which we then compare as the desktop does. // - private Object[] ReadFields() + private object[] ReadFields() { int numFields = _ILT_GetNumFields(); - Object[] fieldValues = new Object[numFields]; + object[] fieldValues = new object[numFields]; _ILT_ReadFields(fieldValues, 0); return fieldValues; } diff --git a/src/System.Private.CoreLib/src/System/Collections/Generic/CompatibilityEqualityComparers.cs b/src/System.Private.CoreLib/src/System/Collections/Generic/CompatibilityEqualityComparers.cs index 33aef24b9c9..c22edd601be 100644 --- a/src/System.Private.CoreLib/src/System/Collections/Generic/CompatibilityEqualityComparers.cs +++ b/src/System.Private.CoreLib/src/System/Collections/Generic/CompatibilityEqualityComparers.cs @@ -24,7 +24,7 @@ public override int GetHashCode(byte obj) } // Equals method for the comparer itself. - public override bool Equals(Object obj) => obj != null && GetType() == obj.GetType(); + public override bool Equals(object obj) => obj != null && GetType() == obj.GetType(); public override int GetHashCode() => GetType().GetHashCode(); } diff --git a/src/System.Private.CoreLib/src/System/Collections/Generic/EqualOnlyComparer.cs b/src/System.Private.CoreLib/src/System/Collections/Generic/EqualOnlyComparer.cs index 8916147f7e7..cd52c6c3eee 100644 --- a/src/System.Private.CoreLib/src/System/Collections/Generic/EqualOnlyComparer.cs +++ b/src/System.Private.CoreLib/src/System/Collections/Generic/EqualOnlyComparer.cs @@ -9,42 +9,42 @@ namespace System.Collections.Generic { internal static class EqualOnlyComparerHelper { - public static bool Equals(SByte x, SByte y) + public static bool Equals(sbyte x, sbyte y) { return x == y; } - public static bool Equals(Byte x, Byte y) + public static bool Equals(byte x, byte y) { return x == y; } - public static bool Equals(Int16 x, Int16 y) + public static bool Equals(short x, short y) { return x == y; } - public static bool Equals(UInt16 x, UInt16 y) + public static bool Equals(ushort x, ushort y) { return x == y; } - public static bool Equals(Int32 x, Int32 y) + public static bool Equals(int x, int y) { return x == y; } - public static bool Equals(UInt32 x, UInt32 y) + public static bool Equals(uint x, uint y) { return x == y; } - public static bool Equals(Int64 x, Int64 y) + public static bool Equals(long x, long y) { return x == y; } - public static bool Equals(UInt64 x, UInt64 y) + public static bool Equals(ulong x, ulong y) { return x == y; } @@ -59,22 +59,22 @@ public static bool Equals(UIntPtr x, UIntPtr y) return x == y; } - public static bool Equals(Single x, Single y) + public static bool Equals(float x, float y) { return x == y; } - public static bool Equals(Double x, Double y) + public static bool Equals(double x, double y) { return x == y; } - public static bool Equals(Decimal x, Decimal y) + public static bool Equals(decimal x, decimal y) { return x == y; } - public static bool Equals(String x, String y) + public static bool Equals(string x, string y) { return x == y; } @@ -95,33 +95,33 @@ public static bool Equals(T x, T y) { // Specialized Comparers if (typeof(T) == typeof(System.SByte)) - return EqualOnlyComparerHelper.Equals(((System.SByte)(Object)(x)), ((System.SByte)(Object)(y))); + return EqualOnlyComparerHelper.Equals(((System.SByte)(object)(x)), ((System.SByte)(object)(y))); else if (typeof(T) == typeof(System.Byte)) - return EqualOnlyComparerHelper.Equals(((System.Byte)(Object)(x)), ((System.Byte)(Object)(y))); + return EqualOnlyComparerHelper.Equals(((System.Byte)(object)(x)), ((System.Byte)(object)(y))); else if (typeof(T) == typeof(System.Int16)) - return EqualOnlyComparerHelper.Equals(((System.Int16)(Object)(x)), ((System.Int16)(Object)(y))); + return EqualOnlyComparerHelper.Equals(((System.Int16)(object)(x)), ((System.Int16)(object)(y))); else if (typeof(T) == typeof(System.UInt16)) - return EqualOnlyComparerHelper.Equals(((System.UInt16)(Object)(x)), ((System.UInt16)(Object)(y))); + return EqualOnlyComparerHelper.Equals(((System.UInt16)(object)(x)), ((System.UInt16)(object)(y))); else if (typeof(T) == typeof(System.Int32)) - return EqualOnlyComparerHelper.Equals(((System.Int32)(Object)(x)), ((System.Int32)(Object)(y))); + return EqualOnlyComparerHelper.Equals(((System.Int32)(object)(x)), ((System.Int32)(object)(y))); else if (typeof(T) == typeof(System.UInt32)) - return EqualOnlyComparerHelper.Equals(((System.UInt32)(Object)(x)), ((System.UInt32)(Object)(y))); + return EqualOnlyComparerHelper.Equals(((System.UInt32)(object)(x)), ((System.UInt32)(object)(y))); else if (typeof(T) == typeof(System.Int64)) - return EqualOnlyComparerHelper.Equals(((System.Int64)(Object)(x)), ((System.Int64)(Object)(y))); + return EqualOnlyComparerHelper.Equals(((System.Int64)(object)(x)), ((System.Int64)(object)(y))); else if (typeof(T) == typeof(System.UInt64)) - return EqualOnlyComparerHelper.Equals(((System.UInt64)(Object)(x)), ((System.UInt64)(Object)(y))); + return EqualOnlyComparerHelper.Equals(((System.UInt64)(object)(x)), ((System.UInt64)(object)(y))); else if (typeof(T) == typeof(System.IntPtr)) - return EqualOnlyComparerHelper.Equals(((System.IntPtr)(Object)(x)), ((System.IntPtr)(Object)(y))); + return EqualOnlyComparerHelper.Equals(((System.IntPtr)(object)(x)), ((System.IntPtr)(object)(y))); else if (typeof(T) == typeof(System.UIntPtr)) - return EqualOnlyComparerHelper.Equals(((System.UIntPtr)(Object)(x)), ((System.UIntPtr)(Object)(y))); + return EqualOnlyComparerHelper.Equals(((System.UIntPtr)(object)(x)), ((System.UIntPtr)(object)(y))); else if (typeof(T) == typeof(System.Single)) - return EqualOnlyComparerHelper.Equals(((System.Single)(Object)(x)), ((System.Single)(Object)(y))); + return EqualOnlyComparerHelper.Equals(((System.Single)(object)(x)), ((System.Single)(object)(y))); else if (typeof(T) == typeof(System.Double)) - return EqualOnlyComparerHelper.Equals(((System.Double)(Object)(x)), ((System.Double)(Object)(y))); + return EqualOnlyComparerHelper.Equals(((System.Double)(object)(x)), ((System.Double)(object)(y))); else if (typeof(T) == typeof(System.Decimal)) - return EqualOnlyComparerHelper.Equals(((System.Decimal)(Object)(x)), ((System.Decimal)(Object)(y))); + return EqualOnlyComparerHelper.Equals(((System.Decimal)(object)(x)), ((System.Decimal)(object)(y))); else if (typeof(T) == typeof(System.String)) - return EqualOnlyComparerHelper.Equals(((System.String)(Object)(x)), ((System.String)(Object)(y))); + return EqualOnlyComparerHelper.Equals(((System.String)(object)(x)), ((System.String)(object)(y))); // Default Comparer diff --git a/src/System.Private.CoreLib/src/System/Decimal.DecCalc.cs b/src/System.Private.CoreLib/src/System/Decimal.DecCalc.cs index e65be90ec95..c2540415d51 100644 --- a/src/System.Private.CoreLib/src/System/Decimal.DecCalc.cs +++ b/src/System.Private.CoreLib/src/System/Decimal.DecCalc.cs @@ -55,17 +55,17 @@ private ulong Low64 #region APIs need by number formatting. - internal static uint DecDivMod1E9(ref Decimal value) + internal static uint DecDivMod1E9(ref decimal value) { return DecCalc.DecDivMod1E9(ref value); } - internal static void DecAddInt32(ref Decimal value, uint i) + internal static void DecAddInt32(ref decimal value, uint i) { DecCalc.DecAddInt32(ref value, i); } - internal static void DecMul10(ref Decimal value) + internal static void DecMul10(ref decimal value) { DecCalc.DecMul10(ref value); } @@ -83,12 +83,12 @@ private static class DecCalc private const ulong TenToPowerEighteen = 1000000000000000000; // The maximum power of 10 that a 32 bit integer can store - private const Int32 MaxInt32Scale = 9; + private const int MaxInt32Scale = 9; // The maximum power of 10 that a 64 bit integer can store - private const Int32 MaxInt64Scale = 19; + private const int MaxInt64Scale = 19; // Fast access for 10^n where n is 0-9 - private static readonly UInt32[] s_powers10 = new UInt32[] { + private static readonly uint[] s_powers10 = new uint[] { 1, 10, 100, @@ -922,7 +922,7 @@ private static bool Add32To96(ref Buf12 bufNum, uint ulValue) // DecAddSub adds or subtracts two decimal values. On return, d1 contains the result // of the operation. Passing in true for bSign means subtract and false means add. - private static unsafe void DecAddSub(ref Decimal d1, ref Decimal d2, bool bSign) + private static unsafe void DecAddSub(ref decimal d1, ref decimal d2, bool bSign) { ulong low64 = d1.Low64; uint high = d1.High, flags = d1.uflags, d2flags = d2.uflags; @@ -1244,7 +1244,7 @@ private static unsafe void DecAddSub(ref Decimal d1, ref Decimal d2, bool bSign) //********************************************************************** // VarCyFromDec - Convert Currency to Decimal (similar to OleAut32 api.) //********************************************************************** - internal static long VarCyFromDec(ref Decimal pdecIn) + internal static long VarCyFromDec(ref decimal pdecIn) { long value; @@ -1289,7 +1289,7 @@ internal static long VarCyFromDec(ref Decimal pdecIn) //********************************************************************** // VarDecCmp - Decimal Compare updated to return values similar to ICompareTo //********************************************************************** - internal static int VarDecCmp(ref Decimal pdecL, ref Decimal pdecR) + internal static int VarDecCmp(ref decimal pdecL, ref decimal pdecR) { if ((pdecR.Low | pdecR.Mid | pdecR.High) == 0) { @@ -1306,7 +1306,7 @@ internal static int VarDecCmp(ref Decimal pdecL, ref Decimal pdecR) return VarDecCmpSub(ref pdecL, ref pdecR); } - private static int VarDecCmpSub(ref Decimal d1, ref Decimal d2) + private static int VarDecCmpSub(ref decimal d1, ref decimal d2) { int flags = d2.flags; int sign = (flags >> 31) | 1; @@ -1377,7 +1377,7 @@ private static int VarDecCmpSub(ref Decimal d1, ref Decimal d2) //********************************************************************** // VarDecMul - Decimal Multiply //********************************************************************** - internal static unsafe void VarDecMul(ref Decimal pdecL, ref Decimal pdecR) + internal static unsafe void VarDecMul(ref decimal pdecL, ref decimal pdecR) { int iScale = (byte)(pdecL.uflags + pdecR.uflags >> ScaleShift); @@ -1523,15 +1523,15 @@ internal static unsafe void VarDecMul(ref Decimal pdecL, ref Decimal pdecR) return; ReturnZero: - pdecL = default(Decimal); + pdecL = default(decimal); } //********************************************************************** // VarDecFromR4 - Convert float to Decimal //********************************************************************** - internal static void VarDecFromR4(float input, out Decimal pdecOut) + internal static void VarDecFromR4(float input, out decimal pdecOut) { - pdecOut = new Decimal(); + pdecOut = new decimal(); // The most we can scale by is 10^28, which is just slightly more // than 2^93. So a float with an exponent of -94 could just @@ -1705,9 +1705,9 @@ internal static void VarDecFromR4(float input, out Decimal pdecOut) //********************************************************************** // VarDecFromR8 - Convert double to Decimal //********************************************************************** - internal static void VarDecFromR8(double input, out Decimal pdecOut) + internal static void VarDecFromR8(double input, out decimal pdecOut) { - pdecOut = new Decimal(); + pdecOut = new decimal(); // The most we can scale by is 10^28, which is just slightly more // than 2^93. So a float with an exponent of -94 could just @@ -1886,7 +1886,7 @@ internal static void VarDecFromR8(double input, out Decimal pdecOut) //********************************************************************** // VarR4ToDec - Convert Decimal to float //********************************************************************** - internal static float VarR4FromDec(ref Decimal pdecIn) + internal static float VarR4FromDec(ref decimal pdecIn) { return (float)VarR8FromDec(ref pdecIn); } @@ -1894,7 +1894,7 @@ internal static float VarR4FromDec(ref Decimal pdecIn) //********************************************************************** // VarR8ToDec - Convert Decimal to double //********************************************************************** - internal static double VarR8FromDec(ref Decimal pdecIn) + internal static double VarR8FromDec(ref decimal pdecIn) { // Value taken via reverse engineering the double that corresponds to 2^64. (oleaut32 has ds2to64 = DEFDS(0, 0, DBLBIAS + 65, 0)) const double ds2to64 = 1.8446744073709552e+019; @@ -1929,21 +1929,21 @@ internal static int GetHashCode(ref decimal d) // VarDecAdd divides two decimal values. On return, d1 contains the result // of the operation - internal static void VarDecAdd(ref Decimal d1, ref Decimal d2) + internal static void VarDecAdd(ref decimal d1, ref decimal d2) { DecAddSub(ref d1, ref d2, false); } // VarDecSub divides two decimal values. On return, d1 contains the result // of the operation. - internal static void VarDecSub(ref Decimal d1, ref Decimal d2) + internal static void VarDecSub(ref decimal d1, ref decimal d2) { DecAddSub(ref d1, ref d2, true); } // VarDecDiv divides two decimal values. On return, d1 contains the result // of the operation. - internal static unsafe void VarDecDiv(ref Decimal d1, ref Decimal d2) + internal static unsafe void VarDecDiv(ref decimal d1, ref decimal d2) { Buf12 bufQuo, bufDivisor; _ = &bufQuo; // workaround for CS0165 @@ -2217,7 +2217,7 @@ internal static unsafe void VarDecDiv(ref Decimal d1, ref Decimal d2) //********************************************************************** // VarDecMod - Computes the remainder between two decimals //********************************************************************** - internal static void VarDecMod(ref Decimal d1, ref Decimal d2) + internal static void VarDecMod(ref decimal d1, ref decimal d2) { if ((d2.lo | d2.mid | d2.hi) == 0) throw new DivideByZeroException(); @@ -2244,7 +2244,7 @@ internal static void VarDecMod(ref Decimal d1, ref Decimal d2) // 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. - Decimal tmp = d2; + decimal tmp = d2; DecAddSub(ref d1, ref tmp, true); // Formula: d1 - (RoundTowardsZero(d1 / d2) * d2) @@ -2283,7 +2283,7 @@ internal enum RoundingMode } // Does an in-place round by the specified scale - internal static void InternalRound(ref Decimal d, uint scale, RoundingMode mode) + internal static void InternalRound(ref decimal d, uint scale, RoundingMode mode) { // the scale becomes the desired decimal count d.uflags -= scale << ScaleShift; @@ -2412,7 +2412,7 @@ private static uint D32DivMod1E9(uint hi32, ref uint lo32) return (uint)(n % 1000000000); } - internal static uint DecDivMod1E9(ref Decimal value) + internal static uint DecDivMod1E9(ref decimal value) { return D32DivMod1E9(D32DivMod1E9(D32DivMod1E9(0, ref value.uhi), @@ -2420,7 +2420,7 @@ internal static uint DecDivMod1E9(ref Decimal value) ref value.ulo); } - internal static void DecAddInt32(ref Decimal value, uint i) + internal static void DecAddInt32(ref decimal value, uint i) { if (D32AddCarry(ref value.ulo, i)) { @@ -2437,16 +2437,16 @@ private static bool D32AddCarry(ref uint value, uint i) return (sum < v) || (sum < i); } - internal static void DecMul10(ref Decimal value) + internal static void DecMul10(ref decimal value) { - Decimal d = value; + decimal d = value; DecShiftLeft(ref value); DecShiftLeft(ref value); DecAdd(ref value, d); DecShiftLeft(ref value); } - private static void DecShiftLeft(ref Decimal value) + private static void DecShiftLeft(ref decimal value) { uint c0 = (value.Low & 0x80000000) != 0 ? 1u : 0u; uint c1 = (value.Mid & 0x80000000) != 0 ? 1u : 0u; @@ -2455,7 +2455,7 @@ private static void DecShiftLeft(ref Decimal value) value.High = (value.High << 1) | c1; } - private static void DecAdd(ref Decimal value, Decimal d) + private static void DecAdd(ref decimal value, decimal d) { if (D32AddCarry(ref value.ulo, d.Low)) { diff --git a/src/System.Private.CoreLib/src/System/Decimal.cs b/src/System.Private.CoreLib/src/System/Decimal.cs index 50f3975ad50..0a7a6e6972d 100644 --- a/src/System.Private.CoreLib/src/System/Decimal.cs +++ b/src/System.Private.CoreLib/src/System/Decimal.cs @@ -55,7 +55,7 @@ namespace System [Serializable] [StructLayout(LayoutKind.Explicit)] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] - public partial struct Decimal : IFormattable, IComparable, IConvertible, IComparable, IEquatable, IDeserializationCallback, ISpanFormattable + public partial struct Decimal : IFormattable, IComparable, IConvertible, IComparable, IEquatable, IDeserializationCallback, ISpanFormattable { // 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 @@ -74,21 +74,21 @@ public partial struct Decimal : IFormattable, IComparable, IConvertible, ICompar private const int ScaleShift = 16; // Constant representing the Decimal value 0. - public const Decimal Zero = 0m; + public const decimal Zero = 0m; // Constant representing the Decimal value 1. - public const Decimal One = 1m; + public const decimal One = 1m; // Constant representing the Decimal value -1. - public const Decimal MinusOne = -1m; + 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; + 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; + public const decimal MinValue = -79228162514264337593543950335m; private const int CurrencyScale = 4; // Divide the "Int64" representation by 1E4 to get the "true" value of the Currency. @@ -212,9 +212,9 @@ public Decimal(double value) // is the currency value multiplied by 10,000. For example, a currency value of $12.99 would be represented by the Int64 value 129,900. // - public static Decimal FromOACurrency(long cy) + public static decimal FromOACurrency(long cy) { - Decimal d = default(Decimal); + decimal d = default(decimal); ulong absoluteCy; // has to be ulong to accommodate the case where cy == long.MinValue. if (cy < 0) @@ -246,7 +246,7 @@ public static Decimal FromOACurrency(long cy) return d; } - public static long ToOACurrency(Decimal value) + public static long ToOACurrency(decimal value) { return DecCalc.VarCyFromDec(ref value); } @@ -305,7 +305,7 @@ public Decimal(int lo, int mid, int hi, bool isNegative, byte scale) uflags |= SignMask; } - 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. @@ -325,15 +325,15 @@ private Decimal(ulong ulomidLE, uint hi, uint flags) // positive, the result is d. If d is negative, the result // is -d. // - internal static Decimal Abs(ref Decimal d) + internal static decimal Abs(ref decimal d) { - return new Decimal(d.ulomidLE, d.uhi, d.uflags & ~SignMask); + return new decimal(d.ulomidLE, d.uhi, d.uflags & ~SignMask); } // Adds two Decimal values. // - public static Decimal Add(Decimal d1, Decimal d2) + public static decimal Add(decimal d1, decimal d2) { DecCalc.VarDecAdd(ref d1, ref d2); return d1; @@ -342,7 +342,7 @@ public static Decimal Add(Decimal d1, Decimal d2) // 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) { uint flags = d.uflags; if ((flags & ScaleMask) != 0) @@ -353,7 +353,7 @@ public static Decimal Ceiling(Decimal 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 DecCalc.VarDecCmp(ref d1, ref d2); } @@ -364,25 +364,25 @@ public static int Compare(Decimal d1, Decimal d2) // null is considered to be less than any instance. // If object is not of type Decimal, this method throws an ArgumentException. // - public int CompareTo(Object value) + public int CompareTo(object value) { if (value == null) return 1; - if (!(value is Decimal)) + if (!(value is decimal)) throw new ArgumentException(SR.Arg_MustBeDecimal); - Decimal other = (Decimal)value; + decimal other = (decimal)value; return DecCalc.VarDecCmp(ref this, ref other); } - public int CompareTo(Decimal value) + public int CompareTo(decimal value) { return DecCalc.VarDecCmp(ref this, ref value); } // Divides two Decimal values. // - public static Decimal Divide(Decimal d1, Decimal d2) + public static decimal Divide(decimal d1, decimal d2) { DecCalc.VarDecDiv(ref d1, ref d2); return d1; @@ -392,17 +392,17 @@ public static Decimal Divide(Decimal d1, Decimal d2) // 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) + public override bool Equals(object value) { - if (value is Decimal) + if (value is decimal) { - Decimal other = (Decimal)value; + decimal other = (decimal)value; return DecCalc.VarDecCmp(ref this, ref other) == 0; } return false; } - public bool Equals(Decimal value) + public bool Equals(decimal value) { return DecCalc.VarDecCmp(ref this, ref value) == 0; } @@ -414,7 +414,7 @@ public bool Equals(Decimal value) // 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 DecCalc.VarDecCmp(ref d1, ref d2) == 0; } @@ -422,7 +422,7 @@ public static bool Equals(Decimal d1, Decimal d2) // Rounds a Decimal to an integer value. The Decimal argument is rounded // towards negative infinity. // - public static Decimal Floor(Decimal d) + public static decimal Floor(decimal d) { uint flags = d.uflags; if ((flags & ScaleMask) != 0) @@ -435,22 +435,22 @@ public static Decimal Floor(Decimal d) // optionally followed by a decimal point (".") and another sequence of // digits. // - public override String ToString() + public override string ToString() { return Number.FormatDecimal(this, null, NumberFormatInfo.CurrentInfo); } - public String ToString(String format) + public string ToString(string format) { return Number.FormatDecimal(this, format, NumberFormatInfo.CurrentInfo); } - public String ToString(IFormatProvider provider) + public string ToString(IFormatProvider provider) { return Number.FormatDecimal(this, null, NumberFormatInfo.GetInstance(provider)); } - public String ToString(String format, IFormatProvider provider) + public string ToString(string format, IFormatProvider provider) { return Number.FormatDecimal(this, format, NumberFormatInfo.GetInstance(provider)); } @@ -468,7 +468,7 @@ public bool TryFormat(Span destination, out int charsWritten, ReadOnlySpan // 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) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseDecimal(s, NumberStyles.Number, NumberFormatInfo.CurrentInfo); @@ -493,33 +493,33 @@ internal static void ValidateParseStyleFloatingPoint(NumberStyles style) } } - public static Decimal Parse(String s, NumberStyles style) + public static decimal Parse(string s, NumberStyles style) { ValidateParseStyleFloatingPoint(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseDecimal(s, style, NumberFormatInfo.CurrentInfo); } - public static Decimal Parse(String s, IFormatProvider provider) + public static decimal Parse(string s, IFormatProvider provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseDecimal(s, NumberStyles.Number, NumberFormatInfo.GetInstance(provider)); } - public static Decimal Parse(String s, NumberStyles style, IFormatProvider provider) + public static decimal Parse(string s, NumberStyles style, IFormatProvider provider) { ValidateParseStyleFloatingPoint(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseDecimal(s, style, NumberFormatInfo.GetInstance(provider)); } - public static Decimal Parse(ReadOnlySpan s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) + public static decimal Parse(ReadOnlySpan s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) { ValidateParseStyleFloatingPoint(style); return Number.ParseDecimal(s, style, NumberFormatInfo.GetInstance(provider)); } - public static Boolean TryParse(String s, out Decimal result) + public static bool TryParse(string s, out decimal result) { if (s == null) { @@ -535,7 +535,7 @@ public static bool TryParse(ReadOnlySpan 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 bool TryParse(string s, NumberStyles style, IFormatProvider provider, out decimal result) { ValidateParseStyleFloatingPoint(style); if (s == null) @@ -562,12 +562,12 @@ public static bool TryParse(ReadOnlySpan s, NumberStyles style, IFormatPro // indicates the sign of the Decimal value, 0 meaning positive and 1 // meaning negative. // - public static int[] GetBits(Decimal d) + 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) { Debug.Assert((buffer != null && buffer.Length >= 16), "[GetBytes]buffer != null && buffer.Length >= 16"); buffer[0] = (byte)d.lo; @@ -593,19 +593,19 @@ internal static void GetBytes(Decimal d, byte[] buffer) // Returns the larger of two Decimal values. // - internal static ref Decimal Max(ref Decimal d1, ref Decimal d2) + internal static ref decimal Max(ref decimal d1, ref decimal d2) { return ref DecCalc.VarDecCmp(ref d1, ref d2) >= 0 ? ref d1 : ref d2; } // Returns the smaller of two Decimal values. // - internal static ref Decimal Min(ref Decimal d1, ref Decimal d2) + internal static ref decimal Min(ref decimal d1, ref decimal d2) { return ref DecCalc.VarDecCmp(ref d1, ref d2) < 0 ? ref d1 : ref d2; } - public static Decimal Remainder(Decimal d1, Decimal d2) + public static decimal Remainder(decimal d1, decimal d2) { DecCalc.VarDecMod(ref d1, ref d2); return d1; @@ -613,7 +613,7 @@ public static Decimal Remainder(Decimal d1, Decimal d2) // Multiplies two Decimal values. // - public static Decimal Multiply(Decimal d1, Decimal d2) + public static decimal Multiply(decimal d1, decimal d2) { DecCalc.VarDecMul(ref d1, ref d2); return d1; @@ -622,9 +622,9 @@ public static Decimal Multiply(Decimal d1, 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.ulomidLE, d.uhi, d.uflags ^ SignMask); + return new decimal(d.ulomidLE, d.uhi, d.uflags ^ SignMask); } // Rounds a Decimal value to a given number of decimal places. The value @@ -635,12 +635,12 @@ public static Decimal Negate(Decimal d) // 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) => Round(ref d, 0, MidpointRounding.ToEven); - public static Decimal Round(Decimal d, int decimals) => Round(ref d, decimals, MidpointRounding.ToEven); - public static Decimal Round(Decimal d, MidpointRounding mode) => Round(ref d, 0, mode); - public static Decimal Round(Decimal d, int decimals, MidpointRounding mode) => Round(ref d, decimals, mode); + public static decimal Round(decimal d) => Round(ref d, 0, MidpointRounding.ToEven); + public static decimal Round(decimal d, int decimals) => Round(ref d, decimals, MidpointRounding.ToEven); + public static decimal Round(decimal d, MidpointRounding mode) => Round(ref d, 0, mode); + public static decimal Round(decimal d, int decimals, MidpointRounding mode) => Round(ref d, decimals, mode); - private static Decimal Round(ref Decimal d, int decimals, MidpointRounding mode) + private static decimal Round(ref decimal d, int decimals, MidpointRounding mode) { if ((uint)decimals > 28) throw new ArgumentOutOfRangeException(nameof(decimals), SR.ArgumentOutOfRange_DecimalRound); @@ -657,7 +657,7 @@ private static Decimal Round(ref Decimal d, int decimals, MidpointRounding mode) // Subtracts two Decimal values. // - public static Decimal Subtract(Decimal d1, Decimal d2) + public static decimal Subtract(decimal d1, decimal d2) { DecCalc.VarDecSub(ref d1, ref d2); return d1; @@ -667,7 +667,7 @@ public static Decimal Subtract(Decimal d1, Decimal d2) // 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 @@ -687,7 +687,7 @@ public static byte ToByte(Decimal value) // operation is returned as a byte. // [CLSCompliant(false)] - public static sbyte ToSByte(Decimal value) + public static sbyte ToSByte(decimal value) { int temp; try @@ -706,7 +706,7 @@ public static sbyte ToSByte(Decimal value) // 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 @@ -724,7 +724,7 @@ public static short ToInt16(Decimal value) // Converts a Decimal to a double. Since a double has fewer significant // digits than a Decimal, this operation may produce round-off errors. // - public static double ToDouble(Decimal d) + public static double ToDouble(decimal d) { return DecCalc.VarR8FromDec(ref d); } @@ -733,7 +733,7 @@ public static double ToDouble(Decimal d) // zero to the nearest integer value, and the result of this operation is // returned as an integer. // - public static int ToInt32(Decimal d) + public static int ToInt32(decimal d) { Truncate(ref d); if ((d.hi | d.mid) == 0) @@ -756,7 +756,7 @@ public static int ToInt32(Decimal d) // to the nearest integer value, and the result of this operation is // returned as a long. // - public static long ToInt64(Decimal d) + public static long ToInt64(decimal d) { Truncate(ref d); if (d.uhi == 0) @@ -780,7 +780,7 @@ public static long ToInt64(Decimal d) // result of this operation is returned as an ushort. // [CLSCompliant(false)] - public static ushort ToUInt16(Decimal value) + public static ushort ToUInt16(decimal value) { uint temp; try @@ -800,7 +800,7 @@ public static ushort ToUInt16(Decimal value) // result of this operation is returned as an unsigned integer. // [CLSCompliant(false)] - public static uint ToUInt32(Decimal d) + public static uint ToUInt32(decimal d) { Truncate(ref d); if ((d.uhi | d.umid) == 0) @@ -817,7 +817,7 @@ public static uint ToUInt32(Decimal d) // result of this operation is returned as a long. // [CLSCompliant(false)] - public static ulong ToUInt64(Decimal d) + public static ulong ToUInt64(decimal d) { Truncate(ref d); if (d.uhi == 0) @@ -832,7 +832,7 @@ public static ulong ToUInt64(Decimal d) // Converts a Decimal to a float. Since a float has fewer significant // digits than a Decimal, this operation may produce round-off errors. // - public static float ToSingle(Decimal d) + public static float ToSingle(decimal d) { return DecCalc.VarR4FromDec(ref d); } @@ -841,94 +841,94 @@ public static float ToSingle(Decimal d) // towards zero to the nearest integer value, corresponding to removing all // digits after the decimal point. // - public static Decimal Truncate(Decimal d) + public static decimal Truncate(decimal d) { Truncate(ref d); return d; } [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static void Truncate(ref Decimal d) + private static void Truncate(ref decimal d) { uint flags = d.uflags; if ((flags & ScaleMask) != 0) DecCalc.InternalRound(ref d, (byte)(flags >> ScaleShift), DecCalc.RoundingMode.Truncate); } - public static implicit operator Decimal(byte value) + public static implicit operator decimal(byte value) { - return new Decimal(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); + return new decimal(value); } - public static implicit operator Decimal(short value) + public static implicit operator decimal(short value) { - return new Decimal(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); + return new decimal(value); } - public static implicit operator Decimal(char value) + public static implicit operator decimal(char value) { - return new Decimal(value); + return new decimal(value); } - public static implicit operator Decimal(int value) + public static implicit operator decimal(int value) { - return new Decimal(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); + return new decimal(value); } - public static implicit operator Decimal(long value) + public static implicit operator decimal(long value) { - return new Decimal(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); + return new decimal(value); } - public static explicit operator Decimal(float value) + public static explicit operator decimal(float value) { - return new Decimal(value); + return new decimal(value); } - public static explicit operator Decimal(double value) + public static explicit operator decimal(double value) { - return new Decimal(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; + ushort temp; try { temp = ToUInt16(value); @@ -940,120 +940,120 @@ private static void Truncate(ref Decimal d) 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) { return Add(d1, d2); } - public static Decimal operator -(Decimal d1, Decimal d2) + public static decimal operator -(decimal d1, decimal d2) { return Subtract(d1, d2); } - public static Decimal operator *(Decimal d1, Decimal d2) + public static decimal operator *(decimal d1, decimal d2) { return Multiply(d1, d2); } - public static Decimal operator /(Decimal d1, Decimal d2) + public static decimal operator /(decimal d1, decimal d2) { return Divide(d1, d2); } - 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 DecCalc.VarDecCmp(ref d1, ref d2) == 0; } - public static bool operator !=(Decimal d1, Decimal d2) + public static bool operator !=(decimal d1, decimal d2) { return DecCalc.VarDecCmp(ref d1, ref d2) != 0; } - public static bool operator <(Decimal d1, Decimal d2) + public static bool operator <(decimal d1, decimal d2) { return DecCalc.VarDecCmp(ref d1, ref d2) < 0; } - public static bool operator <=(Decimal d1, Decimal d2) + public static bool operator <=(decimal d1, decimal d2) { return DecCalc.VarDecCmp(ref d1, ref d2) <= 0; } - public static bool operator >(Decimal d1, Decimal d2) + public static bool operator >(decimal d1, decimal d2) { return DecCalc.VarDecCmp(ref d1, ref d2) > 0; } - public static bool operator >=(Decimal d1, Decimal d2) + public static bool operator >=(decimal d1, decimal d2) { return DecCalc.VarDecCmp(ref d1, ref d2) >= 0; } @@ -1075,7 +1075,7 @@ bool IConvertible.ToBoolean(IFormatProvider provider) char IConvertible.ToChar(IFormatProvider provider) { - throw new InvalidCastException(String.Format(SR.InvalidCast_FromTo, "Decimal", "Char")); + throw new InvalidCastException(string.Format(SR.InvalidCast_FromTo, "Decimal", "Char")); } sbyte IConvertible.ToSByte(IFormatProvider provider) @@ -1128,17 +1128,17 @@ float IConvertible.ToSingle(IFormatProvider provider) return Convert.ToDouble(this); } - Decimal IConvertible.ToDecimal(IFormatProvider provider) + decimal IConvertible.ToDecimal(IFormatProvider provider) { return this; } DateTime IConvertible.ToDateTime(IFormatProvider provider) { - throw new InvalidCastException(String.Format(SR.InvalidCast_FromTo, "Decimal", "DateTime")); + throw new InvalidCastException(string.Format(SR.InvalidCast_FromTo, "Decimal", "DateTime")); } - 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/System.Private.CoreLib/src/System/DefaultBinder.CanConvert.cs b/src/System.Private.CoreLib/src/System/DefaultBinder.CanConvert.cs index 593deba6fb7..d0e4886a573 100644 --- a/src/System.Private.CoreLib/src/System/DefaultBinder.CanConvert.cs +++ b/src/System.Private.CoreLib/src/System/DefaultBinder.CanConvert.cs @@ -16,7 +16,7 @@ private static bool CanChangePrimitive(Type source, Type target) } // CanChangePrimitiveObjectToType - private static bool CanChangePrimitiveObjectToType(Object source, Type type) + private static bool CanChangePrimitiveObjectToType(object source, Type type) { return CanPrimitiveWiden(source.GetType(), type); } diff --git a/src/System.Private.CoreLib/src/System/Delegate.DefaultParameters.cs b/src/System.Private.CoreLib/src/System/Delegate.DefaultParameters.cs index 1820f68f1a5..8460fb8fade 100644 --- a/src/System.Private.CoreLib/src/System/Delegate.DefaultParameters.cs +++ b/src/System.Private.CoreLib/src/System/Delegate.DefaultParameters.cs @@ -52,7 +52,7 @@ public long GetLong() // Special encoding for MinInt is 0x0001 (which would normally mean -0). if (curVal == 0x0001) { - return Int64.MinValue; + return long.MinValue; } // High bit is used to indicate an extended value @@ -248,7 +248,7 @@ internal bool TryGetDefaultParameterValue(RuntimeTypeHandle thType, int argIndex decimalBits[1] = dataParser.GetInt(); decimalBits[2] = dataParser.GetInt(); decimalBits[3] = dataParser.GetInt(); - defaultValue = new Decimal(decimalBits); + defaultValue = new decimal(decimalBits); return true; case DefaultParamTypeDateTime: defaultValue = new DateTime(dataParser.GetLong()); diff --git a/src/System.Private.CoreLib/src/System/Delegate.cs b/src/System.Private.CoreLib/src/System/Delegate.cs index 9f8808fddad..d44045b6fc8 100644 --- a/src/System.Private.CoreLib/src/System/Delegate.cs +++ b/src/System.Private.CoreLib/src/System/Delegate.cs @@ -31,7 +31,7 @@ internal Delegate() } // V1 API: Create closed instance delegates. Method name matching is case sensitive. - protected Delegate(Object target, String method) + protected Delegate(object target, string method) { // This constructor cannot be used by application code. To create a delegate by specifying the name of a method, an // overload of the public static CreateDelegate method is used. This will eventually end up calling into the internal @@ -41,7 +41,7 @@ protected Delegate(Object target, String method) } // V1 API: Create open static delegates. Method name matching is case insensitive. - protected Delegate(Type target, String method) + protected Delegate(Type target, string method) { // This constructor cannot be used by application code. To create a delegate by specifying the name of a method, an // overload of the public static CreateDelegate method is used. This will eventually end up calling into the internal @@ -494,8 +494,8 @@ private bool TrySetSlot(Delegate[] a, int index, Delegate o) MulticastDelegate d = (MulticastDelegate)o; MulticastDelegate dd = (MulticastDelegate)a[index]; - if (Object.ReferenceEquals(dd.m_firstParameter, d.m_firstParameter) && - Object.ReferenceEquals(dd.m_helperObject, d.m_helperObject) && + if (object.ReferenceEquals(dd.m_firstParameter, d.m_firstParameter) && + object.ReferenceEquals(dd.m_helperObject, d.m_helperObject) && dd.m_extraFunctionPointerOrData == d.m_extraFunctionPointerOrData && dd.m_functionPointer == d.m_functionPointer) { @@ -510,7 +510,7 @@ private bool TrySetSlot(Delegate[] a, int index, Delegate o) // to form a new delegate. protected virtual Delegate CombineImpl(Delegate d) { - if ((Object)d == null) // cast to object for a more efficient test + if ((object)d == null) // cast to object for a more efficient test return this; // Verify that the types are the same... @@ -739,7 +739,7 @@ protected virtual MethodInfo GetMethodImpl() return RuntimeAugments.Callbacks.GetDelegateMethod(this); } - public override bool Equals(Object obj) + public override bool Equals(object obj) { // It is expected that all real uses of the Equals method will hit the MulticastDelegate.Equals logic instead of this // therefore, instead of duplicating the desktop behavior where direct calls to this Equals function do not behave @@ -749,21 +749,21 @@ public override bool Equals(Object obj) public static bool operator ==(Delegate d1, Delegate d2) { - if ((Object)d1 == null) - return (Object)d2 == null; + if ((object)d1 == null) + return (object)d2 == null; return d1.Equals(d2); } public static bool operator !=(Delegate d1, Delegate d2) { - if ((Object)d1 == null) - return (Object)d2 != null; + if ((object)d1 == null) + return (object)d2 != null; return !d1.Equals(d2); } - public Object Target + public object Target { get { @@ -782,7 +782,7 @@ public Object Target return m_helperObject; // Other non-closed thunks can be identified as the m_firstParameter field points at this. - if (Object.ReferenceEquals(m_firstParameter, this)) + if (object.ReferenceEquals(m_firstParameter, this)) { return null; } @@ -868,7 +868,7 @@ internal static Delegate CreateObjectArrayDelegate(Type t, Func(bool condition, String userMessage) where TException : Exception + public static void Requires(bool condition, string userMessage) where TException : Exception { AssertMustUseRewriter(ContractFailureKind.Precondition, "Requires"); } @@ -461,7 +461,7 @@ public static void Ensures(bool condition) #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif - public static void Ensures(bool condition, String userMessage) + public static void Ensures(bool condition, string userMessage) { AssertMustUseRewriter(ContractFailureKind.Postcondition, "Ensures"); } @@ -504,7 +504,7 @@ public static void Ensures(bool condition, String userMessage) #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif - public static void EnsuresOnThrow(bool condition, String userMessage) where TException : Exception + public static void EnsuresOnThrow(bool condition, string userMessage) where TException : Exception { AssertMustUseRewriter(ContractFailureKind.PostconditionOnException, "EnsuresOnThrow"); } @@ -598,7 +598,7 @@ public static void Invariant(bool condition) #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif - public static void Invariant(bool condition, String userMessage) + public static void Invariant(bool condition, string userMessage) { AssertMustUseRewriter(ContractFailureKind.Invariant, "Invariant"); } @@ -733,7 +733,7 @@ public static bool Exists(IEnumerable collection, Predicate predicate) /// The runtime value is 2^64 - 1 or 2^32 - 1. /// [SuppressMessage("Microsoft.Performance", "CA1802", Justification = "FxCop is confused")] - static readonly ulong MaxWritableExtent = (UIntPtr.Size == 4) ? UInt32.MaxValue : UInt64.MaxValue; + static readonly ulong MaxWritableExtent = (UIntPtr.Size == 4) ? uint.MaxValue : ulong.MaxValue; /// /// Allows specifying a writable extent for a UIntPtr, similar to SAL's writable extent. @@ -851,13 +851,13 @@ public static bool Exists(IEnumerable collection, Predicate predicate) /// System.Runtime.CompilerServices.ContractHelper.RaiseContractFailedEvent, followed by /// System.Runtime.CompilerServices.ContractHelper.TriggerFailure. /// - static partial void ReportFailure(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException); + static partial void ReportFailure(ContractFailureKind failureKind, string userMessage, string conditionText, Exception innerException); /// /// This method is used internally to trigger a failure indicating to the "programmer" that he is using the interface incorrectly. /// It is NEVER used to indicate failure of actual contracts at runtime. /// - static partial void AssertMustUseRewriter(ContractFailureKind kind, String contractKind); + static partial void AssertMustUseRewriter(ContractFailureKind kind, string contractKind); #endregion } @@ -936,9 +936,9 @@ public static partial class ContractHelper #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif - public static string RaiseContractFailedEvent(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException) + public static string RaiseContractFailedEvent(ContractFailureKind failureKind, string userMessage, string conditionText, Exception innerException) { - String resultFailureMessage = "Contract failed"; // default in case implementation does not assign anything. + string resultFailureMessage = "Contract failed"; // default in case implementation does not assign anything. RaiseContractFailedEventImplementation(failureKind, userMessage, conditionText, innerException, ref resultFailureMessage); return resultFailureMessage; } @@ -951,7 +951,7 @@ public static string RaiseContractFailedEvent(ContractFailureKind failureKind, S #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #endif - public static void TriggerFailure(ContractFailureKind kind, String displayMessage, String userMessage, String conditionText, Exception innerException) + public static void TriggerFailure(ContractFailureKind kind, string displayMessage, string userMessage, string conditionText, Exception innerException) { TriggerFailureImplementation(kind, displayMessage, userMessage, conditionText, innerException); } @@ -971,12 +971,12 @@ public static void TriggerFailure(ContractFailureKind kind, String displayMessag /// Should really be out (or the return value), but partial methods are not flexible enough. /// On exit: null if the event was handled and should not trigger a failure. /// Otherwise, returns the localized failure message - static partial void RaiseContractFailedEventImplementation(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException, ref string resultFailureMessage); + static partial void RaiseContractFailedEventImplementation(ContractFailureKind failureKind, string userMessage, string conditionText, Exception innerException, ref string resultFailureMessage); /// /// Implements the default failure behavior of the platform. Under the BCL, it triggers an Assert box. /// - static partial void TriggerFailureImplementation(ContractFailureKind kind, String displayMessage, String userMessage, String conditionText, Exception innerException); + static partial void TriggerFailureImplementation(ContractFailureKind kind, string displayMessage, string userMessage, string conditionText, Exception innerException); #endregion Implementation Stubs } } // namespace System.Runtime.CompilerServices diff --git a/src/System.Private.CoreLib/src/System/Diagnostics/Contracts/ContractsBCL.cs b/src/System.Private.CoreLib/src/System/Diagnostics/Contracts/ContractsBCL.cs index 56626bb8f9e..38b080bcb53 100644 --- a/src/System.Private.CoreLib/src/System/Diagnostics/Contracts/ContractsBCL.cs +++ b/src/System.Private.CoreLib/src/System/Diagnostics/Contracts/ContractsBCL.cs @@ -36,7 +36,7 @@ public static partial class Contract /// #if FEATURE_UNTRUSTED_CALLERS #endif - static partial void AssertMustUseRewriter(ContractFailureKind kind, String contractKind) + static partial void AssertMustUseRewriter(ContractFailureKind kind, string contractKind) { //TODO: Implement CodeContract failure mechanics including enabling CCIRewrite @@ -65,7 +65,7 @@ public static partial class Contract //if (probablyNotRewritten == null) // probablyNotRewritten = thisAssembly; //String simpleName = probablyNotRewritten.GetName().Name; - String simpleName = "System.Private.CoreLib"; + string simpleName = "System.Private.CoreLib"; System.Runtime.CompilerServices.ContractHelper.TriggerFailure(kind, SR.Format(SR.MustUseCCRewrite, contractKind, simpleName), null, null, null); t_assertingMustUseRewriter = false; @@ -85,14 +85,14 @@ public static partial class Contract #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif - static partial void ReportFailure(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException) + static partial void ReportFailure(ContractFailureKind failureKind, string userMessage, string conditionText, Exception innerException) { if (failureKind < ContractFailureKind.Precondition || failureKind > ContractFailureKind.Assume) throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, failureKind), nameof(failureKind)); Contract.EndContractBlock(); // displayMessage == null means: yes we handled it. Otherwise it is the localized failure message - String displayMessage = System.Runtime.CompilerServices.ContractHelper.RaiseContractFailedEvent(failureKind, userMessage, conditionText, innerException); + string displayMessage = System.Runtime.CompilerServices.ContractHelper.RaiseContractFailedEvent(failureKind, userMessage, conditionText, innerException); if (displayMessage == null) return; @@ -139,8 +139,8 @@ public static partial class Contract public sealed class ContractFailedEventArgs : EventArgs { private ContractFailureKind _failureKind; - private String _message; - private String _condition; + private string _message; + private string _condition; private Exception _originalException; private bool _handled; private bool _unwind; @@ -150,7 +150,7 @@ public sealed class ContractFailedEventArgs : EventArgs #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif - public ContractFailedEventArgs(ContractFailureKind failureKind, String message, String condition, Exception originalException) + public ContractFailedEventArgs(ContractFailureKind failureKind, string message, string condition, Exception originalException) { Contract.Requires(originalException == null || failureKind == ContractFailureKind.PostconditionOnException); _failureKind = failureKind; @@ -159,8 +159,8 @@ public ContractFailedEventArgs(ContractFailureKind failureKind, String message, _originalException = originalException; } - public String Message { get { return _message; } } - public String Condition { get { return _condition; } } + public string Message { get { return _message; } } + public string Condition { get { return _condition; } } public ContractFailureKind FailureKind { get { return _failureKind; } } public Exception OriginalException { get { return _originalException; } } @@ -257,7 +257,7 @@ public static partial class ContractHelper #if !FEATURE_CORECLR private static volatile EventHandler s_contractFailedEvent; - private static readonly Object s_lockObject = new Object(); + private static readonly object s_lockObject = new object(); #endif // !FEATURE_CORECLR internal const int COR_E_CODECONTRACTFAILED = unchecked((int)0x80131542); @@ -321,14 +321,14 @@ public static partial class ContractHelper [System.Diagnostics.DebuggerNonUserCode] #if FEATURE_RELIABILITY_CONTRACTS #endif - static partial void RaiseContractFailedEventImplementation(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException, ref string resultFailureMessage) + static partial void RaiseContractFailedEventImplementation(ContractFailureKind failureKind, string userMessage, string conditionText, Exception innerException, ref string resultFailureMessage) { if (failureKind < ContractFailureKind.Precondition || failureKind > ContractFailureKind.Assume) throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, failureKind), nameof(failureKind)); Contract.EndContractBlock(); string returnValue; - String displayMessage = "contract failed."; // Incomplete, but in case of OOM during resource lookup... + string displayMessage = "contract failed."; // Incomplete, but in case of OOM during resource lookup... #if !FEATURE_CORECLR ContractFailedEventArgs eventArgs = null; // In case of OOM. #endif // !FEATURE_CORECLR @@ -392,7 +392,7 @@ public static partial class ContractHelper [System.Diagnostics.DebuggerNonUserCode] #if FEATURE_UNTRUSTED_CALLERS && !FEATURE_CORECLR #endif - static partial void TriggerFailureImplementation(ContractFailureKind kind, String displayMessage, String userMessage, String conditionText, Exception innerException) + static partial void TriggerFailureImplementation(ContractFailureKind kind, string displayMessage, string userMessage, string conditionText, Exception innerException) { // If we're here, our intent is to pop up a dialog box (if we can). For developers // interacting live with a debugger, this is a good experience. For Silverlight @@ -414,7 +414,7 @@ public static partial class ContractHelper //TODO: Implement CodeContract failure mechanics including enabling CCIRewrite - String stackTrace = null; //@todo: Any reasonable way to get a stack trace here? + string stackTrace = null; //@todo: Any reasonable way to get a stack trace here? bool userSelectedIgnore = DeveloperExperience.Default.OnContractFailure(stackTrace, kind, displayMessage, userMessage, conditionText, innerException); if (userSelectedIgnore) return; @@ -431,9 +431,9 @@ public static partial class ContractHelper // If we got here, the user selected Ignore. Continue. } - private static String GetFailureMessage(ContractFailureKind failureKind, String conditionText) + private static string GetFailureMessage(ContractFailureKind failureKind, string conditionText) { - bool hasConditionText = !String.IsNullOrEmpty(conditionText); + bool hasConditionText = !string.IsNullOrEmpty(conditionText); switch (failureKind) { case ContractFailureKind.Assert: @@ -463,7 +463,7 @@ private static String GetFailureMessage(ContractFailureKind failureKind, String #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif - private static String GetDisplayMessage(ContractFailureKind failureKind, String userMessage, String conditionText) + private static string GetDisplayMessage(ContractFailureKind failureKind, string userMessage, string conditionText) { // Well-formatted English messages will take one of four forms. A sentence ending in // either a period or a colon, the condition string, then the message tacked @@ -471,9 +471,9 @@ private static String GetDisplayMessage(ContractFailureKind failureKind, String // Note that both the conditionText and userMessage may be null. Also, // 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 = GetFailureMessage(failureKind, conditionText); + string failureMessage = GetFailureMessage(failureKind, conditionText); // Now add in the user message, if present. - if (!String.IsNullOrEmpty(userMessage)) + if (!string.IsNullOrEmpty(userMessage)) { return failureMessage + " " + userMessage; } diff --git a/src/System.Private.CoreLib/src/System/Diagnostics/Debug.Windows.cs b/src/System.Private.CoreLib/src/System/Diagnostics/Debug.Windows.cs index 9493cadef8a..9cd935feb0f 100644 --- a/src/System.Private.CoreLib/src/System/Diagnostics/Debug.Windows.cs +++ b/src/System.Private.CoreLib/src/System/Diagnostics/Debug.Windows.cs @@ -22,7 +22,7 @@ private static void ShowDialog(string stackTrace, string message, string detailM } } - private static readonly object s_ForLock = new Object(); + private static readonly object s_ForLock = new object(); private static void WriteCore(string message) { diff --git a/src/System.Private.CoreLib/src/System/Diagnostics/Debugger.cs b/src/System.Private.CoreLib/src/System/Diagnostics/Debugger.cs index 10298ebd5c1..4c47bd66b45 100644 --- a/src/System.Private.CoreLib/src/System/Diagnostics/Debugger.cs +++ b/src/System.Private.CoreLib/src/System/Diagnostics/Debugger.cs @@ -49,14 +49,14 @@ public static void NotifyOfCrossThreadDependency() /// desired events are actually reported to the debugger. /// Constant representing the default category /// - public static readonly String DefaultCategory = null; + public static readonly string DefaultCategory = null; /// /// Posts a message for the attached debugger. If there is no /// debugger attached, has no effect. The debugger may or may not /// report the message depending on its settings. /// - public static void Log(int level, String category, String message) + public static void Log(int level, string category, string message) { if (IsLogging()) { diff --git a/src/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventSource_CoreRT.cs b/src/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventSource_CoreRT.cs index 87a5d0fc12e..72ce7c99fa6 100644 --- a/src/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventSource_CoreRT.cs +++ b/src/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventSource_CoreRT.cs @@ -341,10 +341,10 @@ internal static string GetResourceString(string key, params object[] args) if (fmt != null) return string.Format(fmt, args); - string sargs = String.Empty; + string sargs = string.Empty; foreach(var arg in args) { - if (sargs != String.Empty) + if (sargs != string.Empty) sargs += ", "; sargs += arg.ToString(); } diff --git a/src/System.Private.CoreLib/src/System/Diagnostics/Tracing/UnsafeNativeMethods.cs b/src/System.Private.CoreLib/src/System/Diagnostics/Tracing/UnsafeNativeMethods.cs index 3d2e41eba6b..c070027e7db 100644 --- a/src/System.Private.CoreLib/src/System/Diagnostics/Tracing/UnsafeNativeMethods.cs +++ b/src/System.Private.CoreLib/src/System/Diagnostics/Tracing/UnsafeNativeMethods.cs @@ -235,7 +235,7 @@ internal static class Win32Native [System.Security.SecuritySafeCritical] // Gets an error message for a Win32 error code. - internal static String GetMessage(int errorCode) + internal static string GetMessage(int errorCode) { #if FEATURE_MANAGED_ETW return Interop.Kernel32.GetMessage(errorCode); diff --git a/src/System.Private.CoreLib/src/System/EETypePtr.cs b/src/System.Private.CoreLib/src/System/EETypePtr.cs index fa5abb6b09d..2dd495043f0 100644 --- a/src/System.Private.CoreLib/src/System/EETypePtr.cs +++ b/src/System.Private.CoreLib/src/System/EETypePtr.cs @@ -41,7 +41,7 @@ internal EETypePtr(EEType* value) return _value; } - public override bool Equals(Object obj) + public override bool Equals(object obj) { if (obj is EETypePtr) { diff --git a/src/System.Private.CoreLib/src/System/Enum.cs b/src/System.Private.CoreLib/src/System/Enum.cs index 35d8ae49d96..578c8f9950f 100644 --- a/src/System.Private.CoreLib/src/System/Enum.cs +++ b/src/System.Private.CoreLib/src/System/Enum.cs @@ -19,7 +19,7 @@ namespace System [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public abstract class Enum : ValueType, IComparable, IFormattable, IConvertible { - public int CompareTo(Object target) + public int CompareTo(object target) { if (target == null) return 1; @@ -77,7 +77,7 @@ public int CompareTo(Object target) } } - public override bool Equals(Object obj) + public override bool Equals(object obj) { if (obj == null) return false; @@ -137,7 +137,7 @@ public override int GetHashCode() } } - public static String Format(Type enumType, Object value, String format) + public static string Format(Type enumType, object value, string format) { if (enumType == null) throw new ArgumentNullException(nameof(enumType)); @@ -170,7 +170,7 @@ public static String Format(Type enumType, Object value, String format) return Format(enumInfo, value, format); } - private static String Format(EnumInfo enumInfo, Object value, String format) + private static string Format(EnumInfo enumInfo, object value, string format) { ulong rawValue; if (!TryGetUnboxedValueOfEnumOrInteger(value, out rawValue)) @@ -213,20 +213,20 @@ private static String Format(EnumInfo enumInfo, Object value, String format) // // Helper for Enum.Format(,,"d") // - private static String DoFormatD(ulong rawValue, RuntimeImports.RhCorElementType corElementType) + private static string DoFormatD(ulong rawValue, RuntimeImports.RhCorElementType corElementType) { switch (corElementType) { case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I1: { - SByte result = (SByte)rawValue; + sbyte result = (sbyte)rawValue; return result.ToString(); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U1: { - Byte result = (Byte)rawValue; + byte result = (byte)rawValue; return result.ToString(); } @@ -240,49 +240,49 @@ private static String DoFormatD(ulong rawValue, RuntimeImports.RhCorElementType case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I2: { - Int16 result = (Int16)rawValue; + short result = (short)rawValue; return result.ToString(); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U2: { - UInt16 result = (UInt16)rawValue; + ushort result = (ushort)rawValue; return result.ToString(); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR: { - Char result = (Char)rawValue; + char result = (char)rawValue; return result.ToString(); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U4: { - UInt32 result = (UInt32)rawValue; + uint result = (uint)rawValue; return result.ToString(); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I4: { - Int32 result = (Int32)rawValue; + int result = (int)rawValue; return result.ToString(); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U8: { - UInt64 result = (UInt64)rawValue; + ulong result = (ulong)rawValue; return result.ToString(); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8: { - Int64 result = (Int64)rawValue; + long result = (long)rawValue; return result.ToString(); } @@ -297,20 +297,20 @@ private static String DoFormatD(ulong rawValue, RuntimeImports.RhCorElementType // // Helper for Enum.Format(,,"x") // - private static String DoFormatX(ulong rawValue, RuntimeImports.RhCorElementType corElementType) + private static string DoFormatX(ulong rawValue, RuntimeImports.RhCorElementType corElementType) { switch (corElementType) { case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I1: { - Byte result = (byte)(sbyte)rawValue; + byte result = (byte)(sbyte)rawValue; return result.ToString("X2", null); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U1: { - Byte result = (byte)rawValue; + byte result = (byte)rawValue; return result.ToString("X2", null); } @@ -318,56 +318,56 @@ private static String DoFormatX(ulong rawValue, RuntimeImports.RhCorElementType case RuntimeImports.RhCorElementType.ELEMENT_TYPE_BOOLEAN: { // direct cast from bool to byte is not allowed - Byte result = (byte)rawValue; + byte result = (byte)rawValue; return result.ToString("X2", null); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I2: { - UInt16 result = (UInt16)(Int16)rawValue; + ushort result = (ushort)(short)rawValue; return result.ToString("X4", null); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U2: { - UInt16 result = (UInt16)rawValue; + ushort result = (ushort)rawValue; return result.ToString("X4", null); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR: { - UInt16 result = (UInt16)(Char)rawValue; + ushort result = (ushort)(char)rawValue; return result.ToString("X4", null); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U4: { - UInt32 result = (UInt32)rawValue; + uint result = (uint)rawValue; return result.ToString("X8", null); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I4: { - UInt32 result = (UInt32)(int)rawValue; + uint result = (uint)(int)rawValue; return result.ToString("X8", null); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U8: { - UInt64 result = (UInt64)rawValue; + ulong result = (ulong)rawValue; return result.ToString("X16", null); } case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8: { - UInt64 result = (UInt64)(Int64)rawValue; + ulong result = (ulong)(long)rawValue; return result.ToString("X16", null); } @@ -381,13 +381,13 @@ private static String DoFormatX(ulong rawValue, RuntimeImports.RhCorElementType // // Helper for Enum.Format(,,"g") // - private static String DoFormatG(EnumInfo enumInfo, ulong rawValue) + private static string DoFormatG(EnumInfo enumInfo, ulong rawValue) { Debug.Assert(enumInfo != null); if (!enumInfo.HasFlagsAttribute) // Not marked with Flags attribute { // Try to see if its one of the enum values, then we return a String back else the value - String name = GetNameIfAny(enumInfo, rawValue); + string name = GetNameIfAny(enumInfo, rawValue); if (name == null) return DoFormatD(rawValue, enumInfo.UnderlyingType.TypeHandle.ToEETypePtr().CorElementType); else @@ -402,12 +402,12 @@ private static String DoFormatG(EnumInfo enumInfo, ulong rawValue) // // Helper for Enum.Format(,,"f") // - private static String DoFormatF(EnumInfo enumInfo, ulong rawValue) + private static string DoFormatF(EnumInfo enumInfo, ulong rawValue) { Debug.Assert(enumInfo != null); // These values are sorted by value. Don't change this - KeyValuePair[] namesAndValues = enumInfo.NamesAndValues; + KeyValuePair[] namesAndValues = enumInfo.NamesAndValues; int index = namesAndValues.Length - 1; StringBuilder retval = new StringBuilder(); @@ -451,7 +451,7 @@ private static String DoFormatF(EnumInfo enumInfo, ulong rawValue) return retval.ToString(); // Built a list of matching names. Return it. } - internal Object GetValue() + internal object GetValue() { ref byte pValue = ref this.GetRawData(); @@ -483,7 +483,7 @@ internal Object GetValue() } } - public static String GetName(Type enumType, Object value) + public static string GetName(Type enumType, object value) { if (enumType == null) throw new ArgumentNullException(nameof(enumType)); @@ -502,11 +502,11 @@ public static String GetName(Type enumType, Object value) throw new ArgumentException(SR.Arg_MustBeEnum); EnumInfo enumInfo = GetEnumInfo(enumType); - String nameOrNull = GetNameIfAny(enumInfo, rawValue); + string nameOrNull = GetNameIfAny(enumInfo, rawValue); return nameOrNull; } - public static String[] GetNames(Type enumType) + public static string[] GetNames(Type enumType) { if (enumType == null) throw new ArgumentNullException(nameof(enumType)); @@ -517,8 +517,8 @@ public static String[] GetNames(Type enumType) if (!enumType.IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum); - KeyValuePair[] namesAndValues = GetEnumInfo(enumType).NamesAndValues; - String[] names = new String[namesAndValues.Length]; + KeyValuePair[] namesAndValues = GetEnumInfo(enumType).NamesAndValues; + string[] names = new string[namesAndValues.Length]; for (int i = 0; i < namesAndValues.Length; i++) names[i] = namesAndValues[i].Key; return names; @@ -568,7 +568,7 @@ public static Array GetValues(Type enumType) } [Intrinsic] - public Boolean HasFlag(Enum flag) + public bool HasFlag(Enum flag) { if (flag == null) throw new ArgumentNullException(nameof(flag)); @@ -595,7 +595,7 @@ public Boolean HasFlag(Enum flag) } } - public static bool IsDefined(Type enumType, Object value) + public static bool IsDefined(Type enumType, object value) { if (enumType == null) throw new ArgumentNullException(nameof(enumType)); @@ -612,7 +612,7 @@ public static bool IsDefined(Type enumType, Object value) throw new ArgumentException(SR.Arg_MustBeEnum); EnumInfo enumInfo = GetEnumInfo(enumType); - foreach (KeyValuePair kv in enumInfo.NamesAndValues) + foreach (KeyValuePair kv in enumInfo.NamesAndValues) { if (value.Equals(kv.Key)) return true; @@ -652,33 +652,33 @@ public static bool IsDefined(Type enumType, Object value) throw new ArgumentException(SR.Arg_MustBeEnum); enumInfo = GetEnumInfo(enumType); } - String nameOrNull = GetNameIfAny(enumInfo, rawValue); + string nameOrNull = GetNameIfAny(enumInfo, rawValue); return nameOrNull != null; } } - public static Object Parse(Type enumType, String value) + public static object Parse(Type enumType, string value) { return Parse(enumType, value, ignoreCase: false); } - public static Object Parse(Type enumType, String value, bool ignoreCase) + public static object Parse(Type enumType, string value, bool ignoreCase) { - Object result; + object result; Exception exception; if (!TryParseEnum(enumType, value, ignoreCase, out result, out exception)) throw exception; return result; } - public static TEnum Parse(String value) where TEnum : struct + public static TEnum Parse(string value) where TEnum : struct { return Parse(value, ignoreCase: false); } - public static TEnum Parse(String value, bool ignoreCase) where TEnum : struct + public static TEnum Parse(string value, bool ignoreCase) where TEnum : struct { - Object result; + object result; Exception exception; if (!TryParseEnum(typeof(TEnum), value, ignoreCase, out result, out exception)) throw exception; @@ -739,7 +739,7 @@ internal unsafe static object ToObject(EETypePtr enumEEType, long value) return RuntimeImports.RhBox(enumEEType, pValue); } - public static Object ToObject(Type enumType, Object value) + public static object ToObject(Type enumType, object value) { if (value == null) throw new ArgumentNullException(nameof(value)); @@ -785,22 +785,22 @@ public static Object ToObject(Type enumType, Object value) } } - public static bool TryParse(Type enumType, String value, bool ignoreCase, out Object result) + public static bool TryParse(Type enumType, string value, bool ignoreCase, out object result) { Exception exception; return TryParseEnum(enumType, value, ignoreCase, out result, out exception); } - public static bool TryParse(Type enumType, String value, out Object result) + public static bool TryParse(Type enumType, string value, out object result) { Exception exception; return TryParseEnum(enumType, value, false, out result, out exception); } - public static bool TryParse(String value, bool ignoreCase, out TEnum result) where TEnum : struct + public static bool TryParse(string value, bool ignoreCase, out TEnum result) where TEnum : struct { Exception exception; - Object tempResult; + object tempResult; if (!TryParseEnum(typeof(TEnum), value, ignoreCase, out tempResult, out exception)) { result = default(TEnum); @@ -810,12 +810,12 @@ public static bool TryParse(Type enumType, String value, out Object result) return true; } - public static bool TryParse(String value, out TEnum result) where TEnum : struct + public static bool TryParse(string value, out TEnum result) where TEnum : struct { return TryParse(value, false, out result); } - public override String ToString() + public override string ToString() { try { @@ -827,7 +827,7 @@ public override String ToString() } } - public String ToString(String format) + public string ToString(string format) { if (format == null || format.Length == 0) format = "G"; @@ -845,13 +845,13 @@ public String ToString(String format) } [Obsolete("The provider argument is not used. Please use ToString().")] - public String ToString(String format, IFormatProvider provider) + public string ToString(string format, IFormatProvider provider) { return ToString(format); } [Obsolete("The provider argument is not used. Please use ToString().")] - public String ToString(IFormatProvider provider) + public string ToString(IFormatProvider provider) { return ToString(); } @@ -868,7 +868,7 @@ private static EnumInfo GetEnumInfo(Type enumType) // // Checks if value.GetType() matches enumType exactly. // - private static bool ValueTypeMatchesEnumType(Type enumType, Object value) + private static bool ValueTypeMatchesEnumType(Type enumType, object value) { EETypePtr enumEEType; if (!enumType.TryGetEEType(out enumEEType)) @@ -896,7 +896,7 @@ internal static ulong ToUInt64(object value) // // The return value is "bool" if "value" is not an enum or an "integer type" as defined by the BCL Enum apis. // - private static bool TryGetUnboxedValueOfEnumOrInteger(Object value, out ulong result) + private static bool TryGetUnboxedValueOfEnumOrInteger(object value, out ulong result) { EETypePtr eeType = value.EETypePtr; // For now, this check is required to flush out pointers. @@ -960,10 +960,10 @@ private static bool TryGetUnboxedValueOfEnumOrInteger(Object value, out ulong re // // Look up a name for rawValue if a matching one exists. Returns null if no matching name exists. // - private static String GetNameIfAny(EnumInfo enumInfo, ulong rawValue) + private static string GetNameIfAny(EnumInfo enumInfo, ulong rawValue) { - KeyValuePair[] namesAndValues = enumInfo.NamesAndValues; - KeyValuePair searchKey = new KeyValuePair(null, rawValue); + KeyValuePair[] namesAndValues = enumInfo.NamesAndValues; + KeyValuePair searchKey = new KeyValuePair(null, rawValue); int index = Array.BinarySearch>(namesAndValues, searchKey, s_nameAndValueComparer); if (index < 0) return null; @@ -973,7 +973,7 @@ private static String GetNameIfAny(EnumInfo enumInfo, ulong rawValue) // // Common funnel for Enum.Parse methods. // - private static bool TryParseEnum(Type enumType, String value, bool ignoreCase, out Object result, out Exception exception) + private static bool TryParseEnum(Type enumType, string value, bool ignoreCase, out object result, out Exception exception) { exception = null; result = null; @@ -1032,7 +1032,7 @@ private static bool TryParseEnum(Type enumType, String value, bool ignoreCase, o StringComparison comparison = ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; - KeyValuePair[] actualNamesAndValues = enumInfo.NamesAndValues; + KeyValuePair[] actualNamesAndValues = enumInfo.NamesAndValues; int valueIndex = firstNonWhitespaceIndex; while (valueIndex <= value.Length) // '=' is to handle invalid case of an ending comma { @@ -1051,11 +1051,11 @@ private static bool TryParseEnum(Type enumType, String value, bool ignoreCase, o // Try to match this substring against each enum name bool foundMatch = false; - foreach (KeyValuePair kv in actualNamesAndValues) + foreach (KeyValuePair kv in actualNamesAndValues) { - String actualName = kv.Key; + string actualName = kv.Key; if (actualName.Length == valueSubstringLength && - String.Compare(actualName, 0, value, valueIndex, valueSubstringLength, comparison) == 0) + string.Compare(actualName, 0, value, valueIndex, valueSubstringLength, comparison) == 0) { v |= kv.Value; foundMatch = true; @@ -1078,7 +1078,7 @@ private static bool TryParseEnum(Type enumType, String value, bool ignoreCase, o return true; } - private static bool TryParseAsInteger(EETypePtr enumEEType, String value, int valueOffset, out Object result) + private static bool TryParseAsInteger(EETypePtr enumEEType, string value, int valueOffset, out object result) { Debug.Assert(value != null, "Expected non-null value"); Debug.Assert(value.Length > 0, "Expected non-empty value"); @@ -1087,7 +1087,7 @@ private static bool TryParseAsInteger(EETypePtr enumEEType, String value, int va result = null; char firstNonWhitespaceChar = value[valueOffset]; - if (!(Char.IsDigit(firstNonWhitespaceChar) || firstNonWhitespaceChar == '+' || firstNonWhitespaceChar == '-')) + if (!(char.IsDigit(firstNonWhitespaceChar) || firstNonWhitespaceChar == '+' || firstNonWhitespaceChar == '-')) return false; RuntimeImports.RhCorElementType corElementType = enumEEType.CorElementType; @@ -1098,8 +1098,8 @@ private static bool TryParseAsInteger(EETypePtr enumEEType, String value, int va { case RuntimeImports.RhCorElementType.ELEMENT_TYPE_BOOLEAN: { - Boolean v; - if (!Boolean.TryParse(value, out v)) + bool v; + if (!bool.TryParse(value, out v)) return false; result = RuntimeImports.RhBox(enumEEType, &v); return true; @@ -1107,8 +1107,8 @@ private static bool TryParseAsInteger(EETypePtr enumEEType, String value, int va case RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR: { - Char v; - if (!Char.TryParse(value, out v)) + char v; + if (!char.TryParse(value, out v)) return false; result = RuntimeImports.RhBox(enumEEType, &v); return true; @@ -1116,8 +1116,8 @@ private static bool TryParseAsInteger(EETypePtr enumEEType, String value, int va case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I1: { - SByte v; - if (!SByte.TryParse(value, out v)) + sbyte v; + if (!sbyte.TryParse(value, out v)) return false; result = RuntimeImports.RhBox(enumEEType, &v); return true; @@ -1125,8 +1125,8 @@ private static bool TryParseAsInteger(EETypePtr enumEEType, String value, int va case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U1: { - Byte v; - if (!Byte.TryParse(value, out v)) + byte v; + if (!byte.TryParse(value, out v)) return false; result = RuntimeImports.RhBox(enumEEType, &v); return true; @@ -1134,8 +1134,8 @@ private static bool TryParseAsInteger(EETypePtr enumEEType, String value, int va case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I2: { - Int16 v; - if (!Int16.TryParse(value, out v)) + short v; + if (!short.TryParse(value, out v)) return false; result = RuntimeImports.RhBox(enumEEType, &v); return true; @@ -1143,8 +1143,8 @@ private static bool TryParseAsInteger(EETypePtr enumEEType, String value, int va case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U2: { - UInt16 v; - if (!UInt16.TryParse(value, out v)) + ushort v; + if (!ushort.TryParse(value, out v)) return false; result = RuntimeImports.RhBox(enumEEType, &v); return true; @@ -1152,8 +1152,8 @@ private static bool TryParseAsInteger(EETypePtr enumEEType, String value, int va case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I4: { - Int32 v; - if (!Int32.TryParse(value, out v)) + int v; + if (!int.TryParse(value, out v)) return false; result = RuntimeImports.RhBox(enumEEType, &v); return true; @@ -1161,8 +1161,8 @@ private static bool TryParseAsInteger(EETypePtr enumEEType, String value, int va case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U4: { - UInt32 v; - if (!UInt32.TryParse(value, out v)) + uint v; + if (!uint.TryParse(value, out v)) return false; result = RuntimeImports.RhBox(enumEEType, &v); return true; @@ -1170,8 +1170,8 @@ private static bool TryParseAsInteger(EETypePtr enumEEType, String value, int va case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8: { - Int64 v; - if (!Int64.TryParse(value, out v)) + long v; + if (!long.TryParse(value, out v)) return false; result = RuntimeImports.RhBox(enumEEType, &v); return true; @@ -1179,8 +1179,8 @@ private static bool TryParseAsInteger(EETypePtr enumEEType, String value, int va case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U8: { - UInt64 v; - if (!UInt64.TryParse(value, out v)) + ulong v; + if (!ulong.TryParse(value, out v)) return false; result = RuntimeImports.RhBox(enumEEType, &v); return true; @@ -1192,7 +1192,7 @@ private static bool TryParseAsInteger(EETypePtr enumEEType, String value, int va } } - private static bool StillLooksLikeInteger(String value, int index) + private static bool StillLooksLikeInteger(string value, int index) { if (index != value.Length && (value[index] == '-' || value[index] == '+')) { @@ -1254,9 +1254,9 @@ private static unsafe void AdjustForEndianness(ref byte* pValue, EETypePtr enumE // // Sort comparer for NamesAndValues // - private class NamesAndValueComparer : IComparer> + private class NamesAndValueComparer : IComparer> { - public int Compare(KeyValuePair kv1, KeyValuePair kv2) + public int Compare(KeyValuePair kv1, KeyValuePair kv2) { ulong x = kv1.Value; ulong y = kv2.Value; @@ -1271,11 +1271,11 @@ public int Compare(KeyValuePair kv1, KeyValuePair private static NamesAndValueComparer s_nameAndValueComparer = new NamesAndValueComparer(); - private String LastResortToString + private string LastResortToString { get { - return String.Format("{0}", GetValue()); + return string.Format("{0}", GetValue()); } } @@ -1372,17 +1372,17 @@ float IConvertible.ToSingle(IFormatProvider provider) return Convert.ToDouble(GetValue(), CultureInfo.CurrentCulture); } - Decimal IConvertible.ToDecimal(IFormatProvider provider) + decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(GetValue(), CultureInfo.CurrentCulture); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { - throw new InvalidCastException(String.Format(SR.InvalidCast_FromTo, "Enum", "DateTime")); + throw new InvalidCastException(string.Format(SR.InvalidCast_FromTo, "Enum", "DateTime")); } - 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/System.Private.CoreLib/src/System/Environment.cs b/src/System.Private.CoreLib/src/System/Environment.cs index 7dc4ff71545..015c68bf9fd 100644 --- a/src/System.Private.CoreLib/src/System/Environment.cs +++ b/src/System.Private.CoreLib/src/System/Environment.cs @@ -50,17 +50,17 @@ public static int TickCount //// another managed helper method, unless you consult with some CLR Watson experts. - public static void FailFast(String message) + public static void FailFast(string message) { RuntimeExceptionHelpers.FailFast(message); } - public static void FailFast(String message, Exception exception) + public static void FailFast(string message, Exception exception) { RuntimeExceptionHelpers.FailFast(message, exception); } - internal static void FailFast(String message, Exception exception, String errorSource) + internal static void FailFast(string message, Exception exception, string errorSource) { // TODO: errorSource originates from CoreCLR (See: https://github.com/dotnet/coreclr/pull/15895) // For now, we ignore errorSource on CoreRT but we should distinguish the way FailFast prints exception message using errorSource @@ -98,7 +98,7 @@ public static bool HasShutdownStarted **Arguments: None. **Exceptions: None. ==============================================================================*/ - public static String NewLine + public static string NewLine { get { @@ -110,7 +110,7 @@ public static String NewLine } } - public static String StackTrace + public static string StackTrace { // Disable inlining to have predictable stack frame that EnvironmentAugments can skip [MethodImpl(MethodImplOptions.NoInlining)] diff --git a/src/System.Private.CoreLib/src/System/Exception.cs b/src/System.Private.CoreLib/src/System/Exception.cs index 0212f28d30f..0e3dbf7bd69 100644 --- a/src/System.Private.CoreLib/src/System/Exception.cs +++ b/src/System.Private.CoreLib/src/System/Exception.cs @@ -29,7 +29,7 @@ public Exception() Init(); } - public Exception(String message) + public Exception(string message) { Init(); _message = message; @@ -40,7 +40,7 @@ public Exception(String message) // 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; @@ -63,13 +63,13 @@ protected Exception(SerializationInfo info, StreamingContext context) _source = info.GetString("Source"); // Do not rename (binary serialization) } - public virtual String Message + public virtual string Message { get { if (_message == null) { - String className = GetClassName(); + string className = GetClassName(); return SR.Format(SR.Exception_WasThrown, className); } else @@ -232,18 +232,18 @@ public virtual void GetObjectData(SerializationInfo info, StreamingContext conte _message = Message; // Set the Message information correctly before serialization } - info.AddValue("ClassName", GetClassName(), typeof(String)); // Do not rename (binary serialization) - info.AddValue("Message", _message, typeof(String)); // Do not rename (binary serialization) + info.AddValue("ClassName", GetClassName(), typeof(string)); // Do not rename (binary serialization) + info.AddValue("Message", _message, typeof(string)); // Do not rename (binary serialization) info.AddValue("Data", _data, typeof(IDictionary)); // Do not rename (binary serialization) info.AddValue("InnerException", _innerException, typeof(Exception)); // Do not rename (binary serialization) - info.AddValue("HelpURL", _helpURL, typeof(String)); // Do not rename (binary serialization) - info.AddValue("StackTraceString", StackTrace, typeof(String)); // Do not rename (binary serialization) - info.AddValue("RemoteStackTraceString", null, typeof(String)); // Do not rename (binary serialization) - info.AddValue("RemoteStackIndex", 0, typeof(Int32)); // Do not rename (binary serialization) - info.AddValue("ExceptionMethod", null, typeof(String)); // Do not rename (binary serialization) + info.AddValue("HelpURL", _helpURL, typeof(string)); // Do not rename (binary serialization) + info.AddValue("StackTraceString", StackTrace, typeof(string)); // Do not rename (binary serialization) + info.AddValue("RemoteStackTraceString", null, typeof(string)); // Do not rename (binary serialization) + info.AddValue("RemoteStackIndex", 0, typeof(int)); // Do not rename (binary serialization) + info.AddValue("ExceptionMethod", null, typeof(string)); // Do not rename (binary serialization) info.AddValue("HResult", HResult); // Do not rename (binary serialization) - info.AddValue("Source", _source, typeof(String)); // Do not rename (binary serialization) - info.AddValue("WatsonBuckets", null, typeof(String)); // Do not rename (binary serialization) + info.AddValue("Source", _source, typeof(string)); // Do not rename (binary serialization) + info.AddValue("WatsonBuckets", null, typeof(string)); // Do not rename (binary serialization) } private string GetStackTrace(bool needFileInfo) @@ -251,7 +251,7 @@ private string GetStackTrace(bool needFileInfo) return this.StackTrace; } - public virtual String HelpLink + public virtual string HelpLink { get { @@ -264,7 +264,7 @@ public virtual String HelpLink } } - public virtual String Source + public virtual string Source { get { @@ -280,15 +280,15 @@ public virtual String Source } } - public override String ToString() + public override string ToString() { 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; + string message = (needMessage ? Message : null); + string s; if (message == null || message.Length <= 0) { @@ -318,16 +318,16 @@ private String ToString(bool needFileLineInfo, bool needMessage) // See https://github.com/dotnet/corert/blob/master/Documentation/design-docs/diagnostics/diagnostics-tools-contract.md for more details. // Please do not change the type, the name, or the semantic usage of this member without understanding the implication for tools. // Get in touch with the diagnostics team if you have questions. - internal String _message; + internal string _message; private IDictionary _data; private Exception _innerException; - private String _helpURL; - private String _source; // Mainly used by VB. + private string _helpURL; + private string _source; // Mainly used by VB. private int _HResult; // HResult // To maintain compatibility across runtimes, if this object was deserialized, it will store its stack trace as a string - private String _stackTrace; + private string _stackTrace; public int HResult { @@ -337,7 +337,7 @@ public int HResult // Returns the stack trace as a string. If no stack trace is // available, null is returned. - public virtual String StackTrace + public virtual string StackTrace { get { @@ -516,7 +516,7 @@ internal struct EdiCaptureState // for a small duration but that sounds reasonable considering // such scenarios are going to be extremely rare, where timing // matches precisely. - private static Object s_EDILock = new Object(); + private static object s_EDILock = new object(); /// /// This is the binary format for serialized exceptions that get saved into a special buffer that is @@ -528,8 +528,8 @@ internal struct EdiCaptureState private struct SERIALIZED_EXCEPTION_HEADER { internal IntPtr ExceptionEEType; - internal Int32 HResult; - internal Int32 StackTraceElementCount; + internal int HResult; + internal int StackTraceElementCount; // IntPtr * N : StackTrace elements } internal const int CurrentSerializationSignature = 0x31305845; // 'EX01' diff --git a/src/System.Private.CoreLib/src/System/GC.cs b/src/System.Private.CoreLib/src/System/GC.cs index 3c135842bc7..1fc2846a659 100644 --- a/src/System.Private.CoreLib/src/System/GC.cs +++ b/src/System.Private.CoreLib/src/System/GC.cs @@ -61,7 +61,7 @@ internal enum EndNoGCRegionStatus public static class GC { - public static int GetGeneration(Object obj) + public static int GetGeneration(object obj) { if (obj == null) { @@ -84,7 +84,7 @@ public static int GetGeneration(WeakReference wo) { // note - this throws an NRE if given a null weak reference. This isn't // documented, but it's the behavior of Desktop and CoreCLR. - Object handleRef = RuntimeImports.RhHandleGet(wo.m_handle); + object handleRef = RuntimeImports.RhHandleGet(wo.m_handle); if (handleRef == null) { throw new ArgumentNullException(nameof(wo)); @@ -170,14 +170,14 @@ public static void RegisterForFullGCNotification(int maxGenerationThreshold, int { throw new ArgumentOutOfRangeException( nameof(maxGenerationThreshold), - String.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, 1, 99)); + string.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, 1, 99)); } if (largeObjectHeapThreshold < 1 || largeObjectHeapThreshold > 99) { throw new ArgumentOutOfRangeException( nameof(largeObjectHeapThreshold), - String.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, 1, 99)); + string.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, 1, 99)); } // This is not documented on MSDN, but CoreCLR throws when the GC's @@ -394,7 +394,7 @@ public static void WaitForPendingFinalizers() RuntimeImports.RhWaitForPendingFinalizers(RuntimeThread.ReentrantWaitsEnabled); } - public static void SuppressFinalize(Object obj) + public static void SuppressFinalize(object obj) { if (obj == null) { @@ -404,7 +404,7 @@ public static void SuppressFinalize(Object obj) RuntimeImports.RhSuppressFinalize(obj); } - public static void ReRegisterForFinalize(Object obj) + public static void ReRegisterForFinalize(object obj) { if (obj == null) throw new ArgumentNullException(nameof(obj)); @@ -414,7 +414,7 @@ public static void ReRegisterForFinalize(Object obj) [Intrinsic] [MethodImplAttribute(MethodImplOptions.NoInlining)] // disable optimizations - public static void KeepAlive(Object obj) + public static void KeepAlive(object obj) { } @@ -516,7 +516,7 @@ public static void AddMemoryPressure(long bytesAllocated) } #if !BIT64 - if (bytesAllocated > Int32.MaxValue) + if (bytesAllocated > int.MaxValue) { throw new ArgumentOutOfRangeException(nameof(bytesAllocated), SR.ArgumentOutOfRange_MustBeNonNegInt32); @@ -585,7 +585,7 @@ public static void RemoveMemoryPressure(long bytesAllocated) } #if !BIT64 - if (bytesAllocated > Int32.MaxValue) + if (bytesAllocated > int.MaxValue) { throw new ArgumentOutOfRangeException(nameof(bytesAllocated), SR.ArgumentOutOfRange_MustBeNonNegInt32); diff --git a/src/System.Private.CoreLib/src/System/Globalization/CultureInfo.Windows.cs b/src/System.Private.CoreLib/src/System/Globalization/CultureInfo.Windows.cs index df13759f743..151bb0d633b 100644 --- a/src/System.Private.CoreLib/src/System/Globalization/CultureInfo.Windows.cs +++ b/src/System.Private.CoreLib/src/System/Globalization/CultureInfo.Windows.cs @@ -78,7 +78,7 @@ private static CultureInfo GetUserDefaultUICulture() index++; } - CultureInfo temp = GetCultureByName(new String(languages, 0, index), true); + CultureInfo temp = GetCultureByName(new string(languages, 0, index), true); temp._isReadOnly = true; return temp; } diff --git a/src/System.Private.CoreLib/src/System/Globalization/CultureInfo.cs b/src/System.Private.CoreLib/src/System/Globalization/CultureInfo.cs index 08be455f979..cfc1016abcb 100644 --- a/src/System.Private.CoreLib/src/System/Globalization/CultureInfo.cs +++ b/src/System.Private.CoreLib/src/System/Globalization/CultureInfo.cs @@ -155,12 +155,12 @@ private static CultureInfo InitializeUserDefaultUICulture() //////////////////////////////////////////////////////////////////////// - public CultureInfo(String name) + public CultureInfo(string name) : this(name, true) { } - public CultureInfo(String name, bool useUserOverride) + public CultureInfo(string name, bool useUserOverride) { if (name == null) { @@ -238,7 +238,7 @@ public CultureInfo(int culture, bool useUserOverride) // Note that we really cannot use an LCID version of this override as the cached // name we create for it has to include both names, and the logic for this is in // the GetCultureInfo override *only*. - internal CultureInfo(String cultureName, String textAndCompareCultureName) + internal CultureInfo(string cultureName, string textAndCompareCultureName) { if (cultureName == null) { @@ -261,7 +261,7 @@ internal CultureInfo(String cultureName, String textAndCompareCultureName) // // TODO: It would appear that this is only ever called with userOveride = true // and this method only has one caller. Can we fold it into the caller? - private static CultureInfo GetCultureByName(String name, bool userOverride) + private static CultureInfo GetCultureByName(string name, bool userOverride) { CultureInfo ci = null; // Try to get our culture @@ -289,7 +289,7 @@ private static CultureInfo GetCultureByName(String name, bool userOverride) // 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) { CultureInfo culture; @@ -339,7 +339,7 @@ public static CultureInfo CreateSpecificCulture(String name) return (new CultureInfo(culture._cultureData.SSPECIFICCULTURE)); } - internal static bool VerifyCultureName(String cultureName, bool throwException) + internal static bool VerifyCultureName(string cultureName, bool throwException) { // This function is used by ResourceManager.GetResourceFileName(). // ResourceManager searches for resource using CultureInfo.Name, @@ -349,7 +349,7 @@ internal static bool VerifyCultureName(String cultureName, bool throwException) { char c = cultureName[i]; // TODO: Names can only be RFC4646 names (ie: a-zA-Z0-9) while this allows any unicode letter/digit - if (Char.IsLetterOrDigit(c) || c == '-' || c == '_') + if (char.IsLetterOrDigit(c) || c == '-' || c == '_') { continue; } @@ -567,7 +567,7 @@ public virtual CultureInfo Parent CultureInfo culture = null; string parentName = _cultureData.SPARENT; - if (String.IsNullOrEmpty(parentName)) + if (string.IsNullOrEmpty(parentName)) { culture = InvariantCulture; } @@ -624,7 +624,7 @@ public static CultureInfo[] GetCultures(CultureTypes types) // "en-US" This version does NOT include sort information in the name. // //////////////////////////////////////////////////////////////////////// - public virtual String Name + public virtual string Name { get { @@ -634,7 +634,7 @@ public virtual String Name _nonSortName = _cultureData.SNAME; if (_nonSortName == null) { - _nonSortName = String.Empty; + _nonSortName = string.Empty; } } return _nonSortName; @@ -642,7 +642,7 @@ public virtual String Name } // This one has the sort information (ie: de-DE_phoneb) - internal String SortName + internal string SortName { get { @@ -681,7 +681,7 @@ public string IetfLanguageTag // US English, "Ingles (Estados Unidos)" will be returned. // //////////////////////////////////////////////////////////////////////// - public virtual String DisplayName + public virtual string DisplayName { get { @@ -700,7 +700,7 @@ public virtual String DisplayName // (United States)" will be returned. // //////////////////////////////////////////////////////////////////////// - public virtual String NativeName + public virtual string NativeName { get { @@ -717,7 +717,7 @@ public virtual String NativeName // (United States)" will be returned. // //////////////////////////////////////////////////////////////////////// - public virtual String EnglishName + public virtual string EnglishName { get { @@ -726,7 +726,7 @@ public virtual String EnglishName } // ie: en - public virtual String TwoLetterISOLanguageName + public virtual string TwoLetterISOLanguageName { get { @@ -735,7 +735,7 @@ public virtual String TwoLetterISOLanguageName } // ie: eng - public virtual String ThreeLetterISOLanguageName + public virtual string ThreeLetterISOLanguageName { get { @@ -751,7 +751,7 @@ public virtual String ThreeLetterISOLanguageName // The ISO names are much preferred // //////////////////////////////////////////////////////////////////////// - public virtual String ThreeLetterWindowsLanguageName + public virtual string ThreeLetterWindowsLanguageName { get { @@ -838,9 +838,9 @@ public virtual TextInfo TextInfo //////////////////////////////////////////////////////////////////////// - public override bool Equals(Object value) + public override bool Equals(object value) { - if (Object.ReferenceEquals(this, value)) + if (object.ReferenceEquals(this, value)) return true; CultureInfo that = value as CultureInfo; @@ -883,13 +883,13 @@ public override int GetHashCode() //////////////////////////////////////////////////////////////////////// - public override String ToString() + public override string ToString() { return _name; } - public virtual Object GetFormat(Type formatType) + public virtual object GetFormat(Type formatType) { if (formatType == typeof(NumberFormatInfo)) return (NumberFormat); @@ -1127,7 +1127,7 @@ public CultureInfo GetConsoleFallbackUICulture() return (temp); } - public virtual Object Clone() + public virtual object Clone() { CultureInfo ci = (CultureInfo)MemberwiseClone(); ci._isReadOnly = false; diff --git a/src/System.Private.CoreLib/src/System/InvokeUtils.cs b/src/System.Private.CoreLib/src/System/InvokeUtils.cs index c08e5a9fc29..865f80fe091 100644 --- a/src/System.Private.CoreLib/src/System/InvokeUtils.cs +++ b/src/System.Private.CoreLib/src/System/InvokeUtils.cs @@ -39,7 +39,7 @@ public static class InvokeUtils // This method is targeted by the Delegate ILTransformer. // // - public static Object CheckArgument(Object srcObject, RuntimeTypeHandle dstType, BinderBundle binderBundle) + public static object CheckArgument(object srcObject, RuntimeTypeHandle dstType, BinderBundle binderBundle) { EETypePtr dstEEType = dstType.ToEETypePtr(); return CheckArgument(srcObject, dstEEType, CheckArgumentSemantics.DynamicInvoke, binderBundle, getExactTypeForCustomBinder: null); @@ -53,7 +53,7 @@ internal enum CheckArgumentSemantics SetFieldDirect, // Throws ArgumentException - other than that, like DynamicInvoke except that enums and integers cannot be intermingled, and null cannot substitute for default(valuetype). } - internal static Object CheckArgument(Object srcObject, EETypePtr dstEEType, CheckArgumentSemantics semantics, BinderBundle binderBundle, Func getExactTypeForCustomBinder = null) + internal static object CheckArgument(object srcObject, EETypePtr dstEEType, CheckArgumentSemantics semantics, BinderBundle binderBundle, Func getExactTypeForCustomBinder = null) { if (srcObject == null) { @@ -803,7 +803,7 @@ public static object DynamicInvokeParamHelperCore(RuntimeTypeHandle type, out Dy incomingParam = InvokeUtils.CheckArgument(incomingParam, type.ToEETypePtr(), InvokeUtils.CheckArgumentSemantics.DynamicInvoke, s_binderBundle, s_getExactTypeForCustomBinder); if (s_binderBundle == null) { - System.Diagnostics.Debug.Assert(s_parameters[index] == null || Object.ReferenceEquals(incomingParam, s_parameters[index])); + System.Diagnostics.Debug.Assert(s_parameters[index] == null || object.ReferenceEquals(incomingParam, s_parameters[index])); } return DynamicInvokeBoxedValuetypeReturn(out paramLookupType, incomingParam, index, type, paramType); } @@ -818,7 +818,7 @@ public static object DynamicInvokeParamHelperCore(RuntimeTypeHandle type, out Dy paramLookupType = DynamicInvokeParamLookupType.IndexIntoObjectArrayReturned; if (s_binderBundle == null) { - System.Diagnostics.Debug.Assert(Object.ReferenceEquals(incomingParam, s_parameters[index])); + System.Diagnostics.Debug.Assert(object.ReferenceEquals(incomingParam, s_parameters[index])); return s_parameters; } else diff --git a/src/System.Private.CoreLib/src/System/MulticastDelegate.cs b/src/System.Private.CoreLib/src/System/MulticastDelegate.cs index a3a23e67a07..6ab87642153 100644 --- a/src/System.Private.CoreLib/src/System/MulticastDelegate.cs +++ b/src/System.Private.CoreLib/src/System/MulticastDelegate.cs @@ -18,7 +18,7 @@ public abstract class MulticastDelegate : Delegate, ISerializable internal MulticastDelegate() { } // V1 API: Create closed instance delegates. Method name matching is case sensitive. - protected MulticastDelegate(Object target, String method) + protected MulticastDelegate(object target, string method) { // This constructor cannot be used by application code. To create a delegate by specifying the name of a method, an // overload of the public static CreateDelegate method is used. This will eventually end up calling into the internal @@ -28,7 +28,7 @@ protected MulticastDelegate(Object target, String method) } // V1 API: Create open static delegates. Method name matching is case insensitive. - protected MulticastDelegate(Type target, String method) + protected MulticastDelegate(Type target, string method) { // This constructor cannot be used by application code. To create a delegate by specifying the name of a method, an // overload of the public static CreateDelegate method is used. This will eventually end up calling into the internal @@ -54,7 +54,7 @@ private bool InvocationListEquals(MulticastDelegate d) return true; } - public override sealed bool Equals(Object obj) + public override sealed bool Equals(object obj) { if (obj == null) return false; @@ -79,7 +79,7 @@ public override sealed bool Equals(Object obj) } else { - if (!Object.ReferenceEquals(m_helperObject, d.m_helperObject) || + if (!object.ReferenceEquals(m_helperObject, d.m_helperObject) || (!FunctionPointerOps.Compare(m_extraFunctionPointerOrData, d.m_extraFunctionPointerOrData)) || (!FunctionPointerOps.Compare(m_functionPointer, d.m_functionPointer))) { @@ -88,12 +88,12 @@ public override sealed bool Equals(Object obj) // Those delegate kinds with thunks put themselves into the m_firstParamter, so we can't // blindly compare the m_firstParameter fields for equality. - if (Object.ReferenceEquals(m_firstParameter, this)) + if (object.ReferenceEquals(m_firstParameter, this)) { - return Object.ReferenceEquals(d.m_firstParameter, d); + return object.ReferenceEquals(d.m_firstParameter, d); } - return Object.ReferenceEquals(m_firstParameter, d.m_firstParameter); + return object.ReferenceEquals(m_firstParameter, d.m_firstParameter); } } diff --git a/src/System.Private.CoreLib/src/System/Number.CoreRT.cs b/src/System.Private.CoreLib/src/System/Number.CoreRT.cs index 1c7fdadce10..172e22283e0 100644 --- a/src/System.Private.CoreLib/src/System/Number.CoreRT.cs +++ b/src/System.Private.CoreLib/src/System/Number.CoreRT.cs @@ -302,9 +302,9 @@ public static bool IsNaNSymbol(string s, IFormatProvider provider) } #region Decimal Number Formatting Helpers - private static unsafe bool NumberBufferToDecimal(ref Number.NumberBuffer number, ref Decimal value) + private static unsafe bool NumberBufferToDecimal(ref Number.NumberBuffer number, ref decimal value) { - Decimal d = new Decimal(); + decimal d = new decimal(); char* p = number.digits; int e = number.scale; @@ -328,9 +328,9 @@ private static unsafe bool NumberBufferToDecimal(ref Number.NumberBuffer number, ((d.Low < 0x99999999) || ((d.Low == 0x99999999) && (*p <= '5')))))))) { - Decimal.DecMul10(ref d); + decimal.DecMul10(ref d); if (*p != 0) - Decimal.DecAddInt32(ref d, (uint)(*p++ - '0')); + decimal.DecAddInt32(ref d, (uint)(*p++ - '0')); e--; } @@ -353,7 +353,7 @@ private static unsafe bool NumberBufferToDecimal(ref Number.NumberBuffer number, if (round) { - Decimal.DecAddInt32(ref d, 1); + decimal.DecAddInt32(ref d, 1); if ((d.High | d.Mid | d.Low) == 0) { d.High = 0x19999999; diff --git a/src/System.Private.CoreLib/src/System/Object.cs b/src/System.Private.CoreLib/src/System/Object.cs index 17a2f99cf85..ffe36ea8836 100644 --- a/src/System.Private.CoreLib/src/System/Object.cs +++ b/src/System.Private.CoreLib/src/System/Object.cs @@ -80,7 +80,7 @@ public Type GetType() return RuntimeTypeUnifier.GetRuntimeTypeForEEType(EETypePtr); } - public virtual String ToString() + public virtual string ToString() { return GetType().ToString(); } @@ -90,7 +90,7 @@ public virtual String ToString() // For Value Types, the toolchain (will) generate a ValueType.Equals override method, // and will not be using this routine. - public virtual bool Equals(Object obj) + public virtual bool Equals(object obj) { if (this == obj) return true; @@ -102,7 +102,7 @@ public virtual bool Equals(Object obj) return false; } - public static bool Equals(Object objA, Object objB) + public static bool Equals(object objA, object objB) { if (objA == objB) { @@ -116,7 +116,7 @@ public static bool Equals(Object objA, Object objB) } //[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] - public static bool ReferenceEquals(Object objA, Object objB) + public static bool ReferenceEquals(object objA, object objB) { return objA == objB; } diff --git a/src/System.Private.CoreLib/src/System/Reflection/AssemblyNameLexer.cs b/src/System.Private.CoreLib/src/System/Reflection/AssemblyNameLexer.cs index 4838e5d5d6c..9b457149304 100644 --- a/src/System.Private.CoreLib/src/System/Reflection/AssemblyNameLexer.cs +++ b/src/System.Private.CoreLib/src/System/Reflection/AssemblyNameLexer.cs @@ -16,7 +16,7 @@ namespace System.Reflection // internal struct AssemblyNameLexer { - internal AssemblyNameLexer(String s) + internal AssemblyNameLexer(string s) { // Convert string to char[] with NUL terminator. (An actual NUL terminator in the input string will be treated // as an actual end of string: this is compatible with desktop behavior.) @@ -32,7 +32,7 @@ internal AssemblyNameLexer(String s) // internal Token GetNext() { - String ignore; + string ignore; return GetNext(out ignore); } @@ -40,10 +40,10 @@ internal Token GetNext() // Return the next token in assembly name. If the result is DisplayNameToken.String, // sets "tokenString" to the tokenized string. // - internal Token GetNext(out String tokenString) + internal Token GetNext(out string tokenString) { tokenString = null; - while (Char.IsWhiteSpace(_chars[_index])) + while (char.IsWhiteSpace(_chars[_index])) _index++; char c = _chars[_index++]; @@ -87,7 +87,7 @@ internal Token GetNext(out String tokenString) { c = _chars[_index++]; bool matched = false; - foreach (KeyValuePair kv in AssemblyNameFormatter.EscapeSequences) + foreach (KeyValuePair kv in AssemblyNameFormatter.EscapeSequences) { if (c == kv.Key) { diff --git a/src/System.Private.CoreLib/src/System/Reflection/AssemblyNameParser.cs b/src/System.Private.CoreLib/src/System/Reflection/AssemblyNameParser.cs index f963e0323c4..8ace065fc7a 100644 --- a/src/System.Private.CoreLib/src/System/Reflection/AssemblyNameParser.cs +++ b/src/System.Private.CoreLib/src/System/Reflection/AssemblyNameParser.cs @@ -18,7 +18,7 @@ namespace System.Reflection [System.Runtime.CompilerServices.ReflectionBlocked] public static class AssemblyNameParser { - public static void Parse(AssemblyName blank, String s) + public static void Parse(AssemblyName blank, string s) { if (s == null) throw new ArgumentNullException(nameof(s)); @@ -26,7 +26,7 @@ public static void Parse(AssemblyName blank, String s) runtimeAssemblyName.CopyToAssemblyName(blank); } - public static RuntimeAssemblyName Parse(String s) + public static RuntimeAssemblyName Parse(string s) { Debug.Assert(s != null); @@ -39,26 +39,26 @@ public static RuntimeAssemblyName Parse(String s) AssemblyNameLexer lexer = new AssemblyNameLexer(s); // Name must come first. - String name; + string name; AssemblyNameLexer.Token token = lexer.GetNext(out name); if (token != AssemblyNameLexer.Token.String) throw new FileLoadException(SR.InvalidAssemblyName); - if (name == String.Empty || name.IndexOfAny(s_illegalCharactersInSimpleName) != -1) + if (name == string.Empty || name.IndexOfAny(s_illegalCharactersInSimpleName) != -1) throw new FileLoadException(SR.InvalidAssemblyName); Version version = null; - String cultureName = null; + string cultureName = null; byte[] pkt = null; AssemblyNameFlags flags = 0; - LowLevelList alreadySeen = new LowLevelList(); + LowLevelList alreadySeen = new LowLevelList(); token = lexer.GetNext(); while (token != AssemblyNameLexer.Token.End) { if (token != AssemblyNameLexer.Token.Comma) throw new FileLoadException(SR.InvalidAssemblyName); - String attributeName; + string attributeName; token = lexer.GetNext(out attributeName); if (token != AssemblyNameLexer.Token.String) @@ -73,12 +73,12 @@ public static RuntimeAssemblyName Parse(String s) if (token != AssemblyNameLexer.Token.Equals) throw new FileLoadException(SR.InvalidAssemblyName); - String attributeValue; + string attributeValue; token = lexer.GetNext(out attributeValue); if (token != AssemblyNameLexer.Token.String) throw new FileLoadException(SR.InvalidAssemblyName); - if (attributeName == String.Empty) + if (attributeName == string.Empty) throw new FileLoadException(SR.InvalidAssemblyName); for (int i = 0; i < alreadySeen.Count; i++) @@ -134,9 +134,9 @@ public static RuntimeAssemblyName Parse(String s) return new RuntimeAssemblyName(name, version, cultureName, flags, pkt); } - private static Version ParseVersion(String attributeValue) + private static Version ParseVersion(string attributeValue) { - String[] parts = attributeValue.Split('.'); + string[] parts = attributeValue.Split('.'); if (parts.Length > 4) throw new FileLoadException(SR.InvalidAssemblyName); ushort[] versionNumbers = new ushort[4]; @@ -149,7 +149,7 @@ private static Version ParseVersion(String attributeValue) // Desktop compat: TryParse is a little more forgiving than Fusion. for (int j = 0; j < parts[i].Length; j++) { - if (!Char.IsDigit(parts[i][j])) + if (!char.IsDigit(parts[i][j])) throw new FileLoadException(SR.InvalidAssemblyName); } if (!(ushort.TryParse(parts[i], out versionNumbers[i]))) @@ -168,7 +168,7 @@ private static Version ParseVersion(String attributeValue) return new Version(versionNumbers[0], versionNumbers[1], versionNumbers[2], versionNumbers[3]); } - private static String ParseCulture(String attributeValue) + private static string ParseCulture(string attributeValue) { if (attributeValue.Equals("Neutral", StringComparison.OrdinalIgnoreCase)) { @@ -181,9 +181,9 @@ private static String ParseCulture(String attributeValue) } } - private static byte[] ParsePKT(String attributeValue) + private static byte[] ParsePKT(string attributeValue) { - if (attributeValue.Equals("null", StringComparison.OrdinalIgnoreCase) || attributeValue == String.Empty) + if (attributeValue.Equals("null", StringComparison.OrdinalIgnoreCase) || attributeValue == string.Empty) return Array.Empty(); if (attributeValue.Length != 8 * 2) @@ -200,7 +200,7 @@ private static byte[] ParsePKT(String attributeValue) return pkt; } - private static ProcessorArchitecture ParseProcessorArchitecture(String attributeValue) + private static ProcessorArchitecture ParseProcessorArchitecture(string attributeValue) { if (attributeValue.Equals("msil", StringComparison.OrdinalIgnoreCase)) return ProcessorArchitecture.MSIL; diff --git a/src/System.Private.CoreLib/src/System/Reflection/RuntimeAssemblyName.cs b/src/System.Private.CoreLib/src/System/Reflection/RuntimeAssemblyName.cs index 0e8d7a33ff7..4faa7e25809 100644 --- a/src/System.Private.CoreLib/src/System/Reflection/RuntimeAssemblyName.cs +++ b/src/System.Private.CoreLib/src/System/Reflection/RuntimeAssemblyName.cs @@ -17,7 +17,7 @@ namespace System.Reflection // public sealed class RuntimeAssemblyName : IEquatable { - public RuntimeAssemblyName(String name, Version version, String cultureName, AssemblyNameFlags flags, byte[] publicKeyOrToken) + public RuntimeAssemblyName(string name, Version version, string cultureName, AssemblyNameFlags flags, byte[] publicKeyOrToken) { Debug.Assert(name != null); this.Name = name; @@ -36,13 +36,13 @@ public RuntimeAssemblyName(String name, Version version, String cultureName, Ass } // Simple name. - public String Name { get; } + public string Name { get; } // Optional version. public Version Version { get; } // Optional culture name. - public String CultureName { get; } + public string CultureName { get; } // Optional flags (this is actually an OR of the classic flags and the ContentType.) public AssemblyNameFlags Flags { get; } @@ -69,7 +69,7 @@ public bool Equals(RuntimeAssemblyName other) if (!this.Version.Equals(other.Version)) return false; } - if (!String.Equals(this.CultureName, other.CultureName)) + if (!string.Equals(this.CultureName, other.CultureName)) return false; if (this.Flags != other.Flags) return false; @@ -101,7 +101,7 @@ public bool Equals(RuntimeAssemblyName other) return true; } - public sealed override bool Equals(Object obj) + public sealed override bool Equals(object obj) { RuntimeAssemblyName other = obj as RuntimeAssemblyName; if (other == null) @@ -157,7 +157,7 @@ public void CopyToAssemblyName(AssemblyName blank) return; } - public String FullName + public string FullName { get { diff --git a/src/System.Private.CoreLib/src/System/Resources/FileBasedResourceGroveler.cs b/src/System.Private.CoreLib/src/System/Resources/FileBasedResourceGroveler.cs index f432333124e..92b6da39756 100644 --- a/src/System.Private.CoreLib/src/System/Resources/FileBasedResourceGroveler.cs +++ b/src/System.Private.CoreLib/src/System/Resources/FileBasedResourceGroveler.cs @@ -34,16 +34,16 @@ public FileBasedResourceGroveler(ResourceManager.ResourceManagerMediator mediato // 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 localResourceSets, bool tryParents, bool createIfNotExists) + public ResourceSet GrovelForResourceSet(CultureInfo culture, Dictionary localResourceSets, bool tryParents, bool createIfNotExists) { Debug.Assert(culture != null, "culture shouldn't be null; check caller"); - String fileName = null; + string fileName = null; ResourceSet rs = null; // Don't use Assembly manifest, but grovel on disk for a file. // Create new ResourceSet, if a file exists on disk for it. - String tempFileName = _mediator.GetResourceFileName(culture); + string tempFileName = _mediator.GetResourceFileName(culture); fileName = FindResourceFile(culture, tempFileName); if (fileName == null) { @@ -73,7 +73,7 @@ public ResourceSet GrovelForResourceSet(CultureInfo culture, Dictionary localResourceSets, bool tryParents, + ResourceSet GrovelForResourceSet(CultureInfo culture, Dictionary localResourceSets, bool tryParents, bool createIfNotExists); } } \ No newline at end of file diff --git a/src/System.Private.CoreLib/src/System/Resources/ManifestBasedResourceGroveler.cs b/src/System.Private.CoreLib/src/System/Resources/ManifestBasedResourceGroveler.cs index 5ae2bb72dbe..449fa4e5b73 100644 --- a/src/System.Private.CoreLib/src/System/Resources/ManifestBasedResourceGroveler.cs +++ b/src/System.Private.CoreLib/src/System/Resources/ManifestBasedResourceGroveler.cs @@ -179,7 +179,7 @@ internal static CultureInfo GetNeutralResourcesLanguage(Assembly a, ref Ultimate // Note we could go into infinite loops if mscorlib's // NeutralResourcesLanguageAttribute is mangled. If this assert // fires, please fix the build process for the BCL directory. - if (a == typeof(Object).GetTypeInfo().Assembly) + if (a == typeof(object).GetTypeInfo().Assembly) { Debug.Fail(a.GetName().Name + "'s NeutralResourcesLanguageAttribute is a malformed culture name! name: \"" + cultureName + "\" Exception: " + e); return CultureInfo.InvariantCulture; @@ -207,7 +207,7 @@ internal ResourceSet CreateResourceSet(Stream store, Assembly assembly) // not disposing because we want to leave stream open BinaryReader br = new BinaryReader(store); - // Look for our magic number as a little endian Int32. + // Look for our magic number as a little endian int. int bytes = br.ReadInt32(); if (bytes == ResourceManager.MagicNumber) { @@ -256,11 +256,11 @@ internal ResourceSet CreateResourceSet(Stream store, Assembly assembly) { // we do not want to use partial binding here. Type readerType = Type.GetType(readerTypeName, true); - Object[] args = new Object[1]; + object[] args = new object[1]; args[0] = store; IResourceReader reader = (IResourceReader)Activator.CreateInstance(readerType, args); - Object[] resourceSetArgs = new Object[1]; + object[] resourceSetArgs = new object[1]; resourceSetArgs[0] = reader; Type resSetType; if (_mediator.UserResourceSet == null) @@ -294,7 +294,7 @@ internal ResourceSet CreateResourceSet(Stream store, Assembly assembly) } else { - Object[] args = new Object[2]; + object[] args = new object[2]; args[0] = store; args[1] = assembly; try @@ -308,7 +308,7 @@ internal ResourceSet CreateResourceSet(Stream store, Assembly assembly) } catch (MissingMethodException) { } - args = new Object[1]; + args = new object[1]; args[0] = store; rs = (ResourceSet)Activator.CreateInstance(_mediator.UserResourceSet, args); return rs; @@ -491,7 +491,7 @@ private void HandleSatelliteMissing() private void HandleResourceStreamMissing(string fileName) { // Keep people from bothering me about resources problems - if (_mediator.MainAssembly == typeof(Object).GetTypeInfo().Assembly && _mediator.BaseName.Equals(System.CoreLib.Name)) + if (_mediator.MainAssembly == typeof(object).GetTypeInfo().Assembly && _mediator.BaseName.Equals(System.CoreLib.Name)) { // This would break CultureInfo & all our exceptions. Debug.Fail("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."); diff --git a/src/System.Private.CoreLib/src/System/Resources/ResourceManager.cs b/src/System.Private.CoreLib/src/System/Resources/ResourceManager.cs index d9507837574..e219dc7d178 100644 --- a/src/System.Private.CoreLib/src/System/Resources/ResourceManager.cs +++ b/src/System.Private.CoreLib/src/System/Resources/ResourceManager.cs @@ -519,7 +519,7 @@ protected virtual string GetResourceFileName(CultureInfo culture) char c = cultureName[i]; // TODO: NLS Arrowhead - This is broken, names can only be RFC4646 names (ie: a-zA-Z0-9). // TODO: NLS Arrowhead - This allows any unicode letter/digit - if (Char.IsLetterOrDigit(c) || c == '-' || c == '_') + if (char.IsLetterOrDigit(c) || c == '-' || c == '_') { continue; } @@ -702,7 +702,7 @@ private static void AddResourceSet(Dictionary localResource ResourceSet lostRace; if (localResourceSets.TryGetValue(cultureName, out lostRace)) { - if (!Object.ReferenceEquals(lostRace, rs)) + 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 @@ -753,7 +753,7 @@ protected static Version GetSatelliteContractVersion(Assembly a) // SatelliteContractVersionAttribute contains bogus values. // If this assert fires, please fix the build process for the // BCL directory. - if (a == typeof(Object).GetTypeInfo().Assembly) + if (a == typeof(object).GetTypeInfo().Assembly) { Debug.Fail(System.CoreLib.Name + "'s SatelliteContractVersionAttribute is a malformed version string!"); return null; @@ -793,7 +793,7 @@ protected static CultureInfo GetNeutralResourcesLanguage(Assembly a) // 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)); @@ -1051,7 +1051,7 @@ public virtual string GetString(string name, CultureInfo culture) // 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)) + if (object.ReferenceEquals(culture, CultureInfo.CurrentUICulture)) { culture = null; } @@ -1139,7 +1139,7 @@ public virtual string GetString(string name, CultureInfo culture) // 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); } @@ -1147,12 +1147,12 @@ public virtual Object GetObject(string name) // 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) + private object GetObject(string name, CultureInfo culture, bool wrapUnmanagedMemStream) { if (null == name) throw new ArgumentNullException(nameof(name)); @@ -1163,7 +1163,7 @@ private Object GetObject(string name, CultureInfo culture, bool wrapUnmanagedMem // 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)) + if (object.ReferenceEquals(culture, CultureInfo.CurrentUICulture)) { culture = null; } @@ -1180,7 +1180,7 @@ private Object GetObject(string name, CultureInfo culture, bool wrapUnmanagedMem ResourceSet last = GetFirstResourceSet(culture); if (last != null) { - Object value = last.GetObject(name, _ignoreCase); + object value = last.GetObject(name, _ignoreCase); if (value != null) { @@ -1205,7 +1205,7 @@ private Object GetObject(string name, CultureInfo culture, bool wrapUnmanagedMem if (rs != last) { - Object value = rs.GetObject(name, _ignoreCase); + object value = rs.GetObject(name, _ignoreCase); if (value != null) { // update the last used ResourceSet @@ -1239,7 +1239,7 @@ public UnmanagedMemoryStream GetStream(string name) public UnmanagedMemoryStream GetStream(string name, CultureInfo culture) { - Object obj = GetObject(name, culture, false); + object obj = GetObject(name, culture, false); UnmanagedMemoryStream ums = obj as UnmanagedMemoryStream; if (ums == null && obj != null) throw new InvalidOperationException(SR.Format(SR.InvalidOperation_ResourceNotStream_Name, name)); diff --git a/src/System.Private.CoreLib/src/System/Resources/ResourceReader.cs b/src/System.Private.CoreLib/src/System/Resources/ResourceReader.cs index a75a1656291..1f661ac9a91 100644 --- a/src/System.Private.CoreLib/src/System/Resources/ResourceReader.cs +++ b/src/System.Private.CoreLib/src/System/Resources/ResourceReader.cs @@ -37,10 +37,10 @@ namespace System.Resources internal struct ResourceLocator { - internal Object _value; // Can be null. Consider WeakReference instead? + internal object _value; // Can be null. Consider WeakReference instead? internal int _dataPos; - internal ResourceLocator(int dataPos, Object value) + internal ResourceLocator(int dataPos, object value) { _dataPos = dataPos; _value = value; @@ -54,7 +54,7 @@ internal int DataPosition // 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; } @@ -464,7 +464,7 @@ private unsafe string AllocateStringForNameIndex(int index, out int dataOffset) // This is used in the enumerator. The enumerator iterates from 0 to n // of our resources and this returns the resource value for a particular // index. The parameter is NOT a virtual offset. - private Object GetValueForNameIndex(int index) + private object GetValueForNameIndex(int index) { Debug.Assert(_store != null, "ResourceReader is closed!"); long nameVA = GetNamePosition(index); @@ -523,7 +523,7 @@ internal string LoadString(int pos) } // Called from RuntimeResourceSet - internal Object LoadObject(int pos) + internal object LoadObject(int pos) { if (_version == 1) return LoadObjectV1(pos); @@ -531,11 +531,11 @@ internal Object LoadObject(int pos) return LoadObjectV2(pos, out typeCode); } - internal Object LoadObject(int pos, out ResourceTypeCode typeCode) + internal object LoadObject(int pos, out ResourceTypeCode typeCode) { if (_version == 1) { - Object o = LoadObjectV1(pos); + object o = LoadObjectV1(pos); typeCode = (o is string) ? ResourceTypeCode.String : ResourceTypeCode.StartOfUserTypes; return o; } @@ -546,7 +546,7 @@ internal Object LoadObject(int pos, out ResourceTypeCode typeCode) // from that location. // Anyone who calls LoadObject should make sure they take a lock so // no one can cause us to do a seek in here. - internal Object LoadObjectV1(int pos) + internal object LoadObjectV1(int pos) { Debug.Assert(_store != null, "ResourceReader is closed!"); Debug.Assert(_version == 1, ".resources file was not a V1 .resources file!"); @@ -567,7 +567,7 @@ internal Object LoadObjectV1(int pos) } } - private Object _LoadObjectV1(int pos) + private object _LoadObjectV1(int pos) { _store.BaseStream.Seek(_dataSectionOffset + pos, SeekOrigin.Begin); int typeIndex = Read7BitEncodedInt(); @@ -580,25 +580,25 @@ private Object _LoadObjectV1(int pos) if (type == typeof(string)) return _store.ReadString(); - else if (type == typeof(Int32)) + else if (type == typeof(int)) return _store.ReadInt32(); - else if (type == typeof(Byte)) + else if (type == typeof(byte)) return _store.ReadByte(); - else if (type == typeof(SByte)) + else if (type == typeof(sbyte)) return _store.ReadSByte(); - else if (type == typeof(Int16)) + else if (type == typeof(short)) return _store.ReadInt16(); - else if (type == typeof(Int64)) + else if (type == typeof(long)) return _store.ReadInt64(); - else if (type == typeof(UInt16)) + else if (type == typeof(ushort)) return _store.ReadUInt16(); - else if (type == typeof(UInt32)) + else if (type == typeof(uint)) return _store.ReadUInt32(); - else if (type == typeof(UInt64)) + else if (type == typeof(ulong)) return _store.ReadUInt64(); - else if (type == typeof(Single)) + else if (type == typeof(float)) return _store.ReadSingle(); - else if (type == typeof(Double)) + else if (type == typeof(double)) return _store.ReadDouble(); else if (type == typeof(DateTime)) { @@ -608,12 +608,12 @@ private Object _LoadObjectV1(int pos) } 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++) bits[i] = _store.ReadInt32(); - return new Decimal(bits); + return new decimal(bits); } else { @@ -621,7 +621,7 @@ private Object _LoadObjectV1(int pos) } } - internal Object LoadObjectV2(int pos, out ResourceTypeCode typeCode) + internal object LoadObjectV2(int pos, out ResourceTypeCode typeCode) { Debug.Assert(_store != null, "ResourceReader is closed!"); Debug.Assert(_version >= 2, ".resources file was not a V2 (or higher) .resources file!"); @@ -642,7 +642,7 @@ internal Object LoadObjectV2(int pos, out ResourceTypeCode typeCode) } } - private Object _LoadObjectV2(int pos, out ResourceTypeCode typeCode) + private object _LoadObjectV2(int pos, out ResourceTypeCode typeCode) { _store.BaseStream.Seek(_dataSectionOffset + pos, SeekOrigin.Begin); typeCode = (ResourceTypeCode)Read7BitEncodedInt(); @@ -696,11 +696,11 @@ private Object _LoadObjectV2(int pos, out ResourceTypeCode typeCode) case ResourceTypeCode.DateTime: // Use DateTime's ToBinary & FromBinary. - Int64 data = _store.ReadInt64(); + long data = _store.ReadInt64(); return DateTime.FromBinary(data); case ResourceTypeCode.TimeSpan: - Int64 ticks = _store.ReadInt64(); + long ticks = _store.ReadInt64(); return new TimeSpan(ticks); // Special types @@ -1088,7 +1088,7 @@ private string TypeNameFromTypeCode(ResourceTypeCode typeCode) internal sealed class ResourceEnumerator : IDictionaryEnumerator { - private const int ENUM_DONE = Int32.MinValue; + private const int ENUM_DONE = int.MinValue; private const int ENUM_NOT_STARTED = -1; private ResourceReader _reader; @@ -1116,7 +1116,7 @@ public bool MoveNext() return true; } - public Object Key + public object Key { get { @@ -1128,7 +1128,7 @@ public Object Key } } - public Object Current + public object Current { get { @@ -1154,7 +1154,7 @@ public DictionaryEntry Entry if (_reader._resCache == null) throw new InvalidOperationException(SR.ResourceReaderIsClosed); string key; - Object value = null; + object value = null; lock (_reader) { // locks should be taken in the same order as in RuntimeResourceSet.GetObject to avoid deadlock lock (_reader._resCache) @@ -1183,7 +1183,7 @@ public DictionaryEntry Entry } } - public Object Value + public object Value { get { diff --git a/src/System.Private.CoreLib/src/System/Resources/ResourceSet.cs b/src/System.Private.CoreLib/src/System/Resources/ResourceSet.cs index 5b1fd99a7ac..a6763c4a855 100644 --- a/src/System.Private.CoreLib/src/System/Resources/ResourceSet.cs +++ b/src/System.Private.CoreLib/src/System/Resources/ResourceSet.cs @@ -56,7 +56,7 @@ internal ResourceSet(bool junk) // implementation. Use this constructor to open & read from a file // on disk. // - public ResourceSet(String fileName) + public ResourceSet(string fileName) { Reader = new ResourceReader(fileName); CommonInit(); @@ -154,12 +154,12 @@ private IDictionaryEnumerator GetEnumeratorHelper() // Look up a string value for a resource given its name. // - public virtual String GetString(String name) + public virtual string GetString(string name) { - Object obj = GetObjectInternal(name); + object obj = GetObjectInternal(name); try { - return (String)obj; + return (string)obj; } catch (InvalidCastException) { @@ -167,16 +167,16 @@ public virtual String GetString(String name) } } - public virtual String GetString(String name, bool ignoreCase) + public virtual string GetString(string name, bool ignoreCase) { - Object obj; - String s; + object obj; + string s; // Case-sensitive lookup obj = GetObjectInternal(name); try { - s = (String)obj; + s = (string)obj; } catch (InvalidCastException) { @@ -193,7 +193,7 @@ public virtual String GetString(String name, bool ignoreCase) obj = GetCaseInsensitiveObjectInternal(name); try { - return (String)obj; + return (string)obj; } catch (InvalidCastException) { @@ -203,14 +203,14 @@ public virtual String GetString(String name, bool ignoreCase) // Look up an object value for a resource given its name. // - public virtual Object GetObject(String name) + public virtual object GetObject(string name) { return GetObjectInternal(name); } - public virtual Object GetObject(String name, bool ignoreCase) + public virtual object GetObject(string name, bool ignoreCase) { - Object obj = GetObjectInternal(name); + object obj = GetObjectInternal(name); if (obj != null || !ignoreCase) return obj; @@ -223,14 +223,14 @@ protected virtual void ReadResources() IDictionaryEnumerator en = Reader.GetEnumerator(); while (en.MoveNext()) { - Object value = en.Value; + object value = en.Value; _table.Add(en.Key, value); } // While technically possible to close the Reader here, don't close it // to help with some WinRes lifetime issues. } - private Object GetObjectInternal(String name) + private object GetObjectInternal(string name) { if (name == null) throw new ArgumentNullException("name"); @@ -244,7 +244,7 @@ private Object GetObjectInternal(String name) return value; } - private Object GetCaseInsensitiveObjectInternal(String name) + private object GetCaseInsensitiveObjectInternal(string name) { Dictionary copyOfTable = _table; // Avoid a race with Dispose diff --git a/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs b/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs index 5601bae5a95..3e038d998c5 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs @@ -949,7 +949,7 @@ internal static void ThrowAsync(Exception exception, SynchronizationContext targ [DependencyReductionRoot] internal static Action TryGetStateMachineForDebugger(Action action) { - Object target = action.Target; + object target = action.Target; MoveNextRunner runner = target as MoveNextRunner; if (runner != null) return runner.m_stateMachine.MoveNext; diff --git a/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/ClassConstructorRunner.cs b/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/ClassConstructorRunner.cs index 39708d993e2..d8a418e15e9 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/ClassConstructorRunner.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/ClassConstructorRunner.cs @@ -50,7 +50,7 @@ private static unsafe IntPtr CheckStaticClassConstructionReturnNonGCStaticBase(S return nonGcStaticBase; } - private unsafe static object CheckStaticClassConstructionReturnThreadStaticBase(TypeManagerSlot* pModuleData, Int32 typeTlsIndex, StaticClassConstructionContext* context) + private unsafe static object CheckStaticClassConstructionReturnThreadStaticBase(TypeManagerSlot* pModuleData, int typeTlsIndex, StaticClassConstructionContext* context) { object threadStaticBase = ThreadStatics.GetThreadStaticBaseForType(pModuleData, typeTlsIndex); EnsureClassConstructorRun(context); @@ -555,7 +555,7 @@ public static unsafe string ToHexStringUnsignedLong(ulong u, bool zeroPrepad, in string str; fixed (char* p = &chars[i]) { - str = new String(p, 0, numChars - i); + str = new string(p, 0, numChars - i); } return str; } diff --git a/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/ConditionalWeakTable.cs b/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/ConditionalWeakTable.cs index 115310e225b..5d9b51bcce0 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/ConditionalWeakTable.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/ConditionalWeakTable.cs @@ -409,7 +409,7 @@ private void CreateEntry(TKey key, TValue value) // // - Used with live key (linked into a bucket list where _buckets[hashCode & (_buckets.Length - 1)] points to first entry) // depHnd.IsAllocated == true, depHnd.GetPrimary() != null - // hashCode == RuntimeHelpers.GetHashCode(depHnd.GetPrimary()) & Int32.MaxValue + // hashCode == RuntimeHelpers.GetHashCode(depHnd.GetPrimary()) & int.MaxValue // next links to next Entry in bucket. // // - Used with dead key (linked into a bucket list where _buckets[hashCode & (_buckets.Length - 1)] points to first entry) diff --git a/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs b/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs index f126f4f8123..15412878bd3 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs @@ -53,7 +53,7 @@ public static void RunModuleConstructor(ModuleHandle module) ReflectionAugments.ReflectionCoreCallbacks.RunModuleConstructor(module.AssociatedModule); } - public static Object GetObjectValue(Object obj) + public static object GetObjectValue(object obj) { if (obj == null) return null; @@ -65,7 +65,7 @@ public static Object GetObjectValue(Object obj) return RuntimeImports.RhMemberwiseClone(obj); } - public new static bool Equals(Object o1, Object o2) + public new static bool Equals(object o1, object o2) { if (o1 == o2) return true; @@ -102,7 +102,7 @@ internal static int GetNewHashCode() return t_hashSeed; } - public static unsafe int GetHashCode(Object o) + public static unsafe int GetHashCode(object o) { #if FEATURE_SYNCTABLE return ObjectHeader.GetHashCode(o); @@ -162,7 +162,7 @@ public static int OffsetToStringData // Number of bytes from the address pointed to by a reference to // a String to the first 16-bit character in the String. // This property allows C#'s fixed statement to work on Strings. - return String.FIRST_CHAR_OFFSET; + return string.FIRST_CHAR_OFFSET; } } @@ -239,7 +239,7 @@ public static void PrepareDelegate(Delegate d) throw new ArgumentNullException(nameof(d)); } - public static void ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData) + public static void ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, object userData) { if (code == null) throw new ArgumentNullException(nameof(code)); @@ -263,8 +263,8 @@ public static void ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode ba } } - public delegate void TryCode(Object userData); - public delegate void CleanupCode(Object userData, bool exceptionThrown); + public delegate void TryCode(object userData); + public delegate void CleanupCode(object userData, bool exceptionThrown); public static object GetUninitializedObject(Type type) { diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/GCHandle.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/GCHandle.cs index 5bae816fb4b..53a51ae19d2 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/GCHandle.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/GCHandle.cs @@ -31,7 +31,7 @@ public struct GCHandle private const GCHandleType MaxHandleType = GCHandleType.Pinned; // Allocate a handle storing the object and the type. - internal GCHandle(Object value, GCHandleType type) + internal GCHandle(object value, GCHandleType type) { // Make sure the type parameter is within the valid range for the enum. if ((uint)type > (uint)MaxHandleType) @@ -61,12 +61,12 @@ internal GCHandle(IntPtr handle) // type - The type of GC handle to create. // // returns a new GC handle that protects the object. - public static GCHandle Alloc(Object value) + public static GCHandle Alloc(object value) { return new GCHandle(value, GCHandleType.Normal); } - public static GCHandle Alloc(Object value, GCHandleType type) + public static GCHandle Alloc(object value, GCHandleType type) { return new GCHandle(value, type); } @@ -95,7 +95,7 @@ public void Free() } // Target property - allows getting / updating of the handle's referent. - public Object Target + public object Target { get { @@ -145,12 +145,12 @@ public IntPtr AddrOfPinnedObject() // Get the address of the pinned object. // The layout of String and Array is different from Object - Object target = this.Target; + object target = this.Target; if (target == null) return default(IntPtr); - if (target is String targetAsString) + if (target is string targetAsString) { return (IntPtr)Unsafe.AsPointer(ref targetAsString.GetRawStringData()); } @@ -206,7 +206,7 @@ public override int GetHashCode() return _handle.GetHashCode(); } - public override bool Equals(Object o) + public override bool Equals(object o) { GCHandle hnd; @@ -256,7 +256,7 @@ internal void SetIsPinned() #endif } - private static void GCHandleValidatePinnedObject(Object obj) + private static void GCHandleValidatePinnedObject(object obj) { if (obj != null && !obj.IsBlittable()) throw new ArgumentException(SR.Argument_NotIsomorphic); diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/InteropExtensions.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/InteropExtensions.cs index e6bd2f27c3e..2ff4feb48ac 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/InteropExtensions.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/InteropExtensions.cs @@ -43,7 +43,7 @@ public static void InitializeHandle(SafeHandle safeHandle, IntPtr win32Handle) } // Used for methods in System.Private.Interop.dll that need to work from offsets on boxed structs - public static unsafe void PinObjectAndCall(Object obj, Action del) + public static unsafe void PinObjectAndCall(object obj, Action del) { fixed (IntPtr* pEEType = &obj.m_pEEType) { @@ -70,7 +70,7 @@ public static bool IsBlittable(this RuntimeTypeHandle handle) return handle.ToEETypePtr().MightBeBlittable(); } - public static bool IsBlittable(this Object obj) + public static bool IsBlittable(this object obj) { return obj.EETypePtr.MightBeBlittable(); } @@ -130,7 +130,7 @@ public static IntPtr GetRawValue(this RuntimeTypeHandle handle) /// /// Comparing RuntimeTypeHandle with an object's RuntimeTypeHandle, avoiding going through expensive Object.GetType().TypeHandle path /// - public static bool IsOfType(this Object obj, RuntimeTypeHandle handle) + public static bool IsOfType(this object obj, RuntimeTypeHandle handle) { RuntimeTypeHandle objType = new RuntimeTypeHandle(obj.EETypePtr); @@ -228,12 +228,12 @@ public static void RuntimeUnregisterRefCountedHandleCallback(IntPtr pCalloutMeth /// weak handle if the callback returns false, which is perfect for controlling lifetime of a CCW /// internal const int RefCountedHandleType = 5; - public static IntPtr RuntimeHandleAllocRefCounted(Object value) + public static IntPtr RuntimeHandleAllocRefCounted(object value) { return RuntimeImports.RhHandleAlloc(value, (GCHandleType)RefCountedHandleType); } - public static void RuntimeHandleSet(IntPtr handle, Object value) + public static void RuntimeHandleSet(IntPtr handle, object value) { RuntimeImports.RhHandleSet(handle, value); } @@ -253,7 +253,7 @@ public static bool RuntimeIsPromoted(object obj) return RuntimeImports.RhIsPromoted(obj); } - public static void RuntimeHandleSetDependentSecondary(IntPtr handle, Object secondary) + public static void RuntimeHandleSetDependentSecondary(IntPtr handle, object secondary) { RuntimeImports.RhHandleSetDependentSecondary(handle, secondary); } @@ -338,7 +338,7 @@ public static char[] GetBuffer(this System.Text.StringBuilder stringBuilder, out return stringBuilder.GetBuffer(out len); } - public static IntPtr RuntimeHandleAllocVariable(Object value, uint type) + public static IntPtr RuntimeHandleAllocVariable(object value, uint type) { return RuntimeImports.RhHandleAllocVariable(value, type); } @@ -373,7 +373,7 @@ public static Exception CreateDataMisalignedException(string message) return new DataMisalignedException(message); } - public static Delegate CreateDelegate(RuntimeTypeHandle typeHandleForDelegate, IntPtr ldftnResult, Object thisObject, bool isStatic, bool isVirtual, bool isOpen) + public static Delegate CreateDelegate(RuntimeTypeHandle typeHandleForDelegate, IntPtr ldftnResult, object thisObject, bool isStatic, bool isVirtual, bool isOpen) { return Delegate.CreateDelegate(typeHandleForDelegate.ToEETypePtr(), ldftnResult, thisObject, isStatic, isOpen); } @@ -419,7 +419,7 @@ public static bool RhpETWShouldWalkCom() return RuntimeImports.RhpETWShouldWalkCom(); } - public static void RhpETWLogLiveCom(int eventType, IntPtr CCWHandle, IntPtr objectID, IntPtr typeRawValue, IntPtr IUnknown, IntPtr VTable, Int32 comRefCount, Int32 jupiterRefCount, Int32 flags) + public static void RhpETWLogLiveCom(int eventType, IntPtr CCWHandle, IntPtr objectID, IntPtr typeRawValue, IntPtr IUnknown, IntPtr VTable, int comRefCount, int jupiterRefCount, int flags) { RuntimeImports.RhpETWLogLiveCom(eventType, CCWHandle, objectID, typeRawValue, IUnknown, VTable, comRefCount, jupiterRefCount, flags); } diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.cs index 5af9ce674d5..00b7449da40 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.cs @@ -12,12 +12,12 @@ namespace System.Runtime.InteropServices /// internal class Marshal { - public static unsafe String PtrToStringUni(IntPtr ptr, int len) + public static unsafe string PtrToStringUni(IntPtr ptr, int len) { return PInvokeMarshal.PtrToStringUni(ptr, len); } - public static unsafe String PtrToStringUni(IntPtr ptr) + public static unsafe string PtrToStringUni(IntPtr ptr) { return PInvokeMarshal.PtrToStringUni(ptr); } diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/PInvokeMarshal.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/PInvokeMarshal.cs index bca69bce3e6..cf407908481 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/PInvokeMarshal.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/PInvokeMarshal.cs @@ -443,17 +443,17 @@ private static unsafe class CalliIntrinsics #endregion #region String marshalling - public static unsafe String PtrToStringUni(IntPtr ptr, int len) + public static unsafe string PtrToStringUni(IntPtr ptr, int len) { if (ptr == IntPtr.Zero) throw new ArgumentNullException(nameof(ptr)); if (len < 0) throw new ArgumentException(nameof(len)); - return new String((char*)ptr, 0, len); + return new string((char*)ptr, 0, len); } - public static unsafe String PtrToStringUni(IntPtr ptr) + public static unsafe string PtrToStringUni(IntPtr ptr) { if (IntPtr.Zero == ptr) { @@ -465,7 +465,7 @@ public static unsafe String PtrToStringUni(IntPtr ptr) } else { - return new String((char*)ptr); + return new string((char*)ptr); } } @@ -553,7 +553,7 @@ public static unsafe string AnsiStringToString(byte* pchBuffer) int lenUnicode; CalculateStringLength(pchBuffer, out lenAnsi, out lenUnicode); - string result = String.Empty; + string result = string.Empty; if (lenUnicode > 0) { @@ -768,7 +768,7 @@ public static unsafe string ByValAnsiStringToString(byte* pchBuffer, int charCou int lenAnsi = GetAnsiStringLen(pchBuffer); int lenUnicode = charCount; - string result = String.Empty; + string result = string.Empty; if (lenUnicode > 0) { diff --git a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/UnsafeGCHandle.cs b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/UnsafeGCHandle.cs index d7fbf759712..4a0b1d2ce30 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/InteropServices/UnsafeGCHandle.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/InteropServices/UnsafeGCHandle.cs @@ -36,19 +36,19 @@ public struct UnsafeGCHandle private IntPtr _handle; // Allocate a handle storing the object and the type. - private UnsafeGCHandle(Object value, GCHandleType type) + private UnsafeGCHandle(object value, GCHandleType type) { Debug.Assert((uint)type <= (uint)MaxHandleType, "Unexpected handle type"); _handle = RuntimeImports.RhHandleAlloc(value, type); } - public static UnsafeGCHandle Alloc(Object value, GCHandleType type) + public static UnsafeGCHandle Alloc(object value, GCHandleType type) { return new UnsafeGCHandle(value, type); } // Target property - allows getting / updating of the handle's referent. - public Object Target + public object Target { get { diff --git a/src/System.Private.CoreLib/src/System/Runtime/RuntimeImports.cs b/src/System.Private.CoreLib/src/System/Runtime/RuntimeImports.cs index 5f17de86e79..49ed62a7987 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/RuntimeImports.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/RuntimeImports.cs @@ -71,9 +71,9 @@ public static class RuntimeImports // Mark an object instance as already finalized. [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhSuppressFinalize")] - internal static extern void RhSuppressFinalize(Object obj); + internal static extern void RhSuppressFinalize(object obj); - internal static void RhReRegisterForFinalize(Object obj) + internal static void RhReRegisterForFinalize(object obj) { if (!_RhReRegisterForFinalize(obj)) throw new OutOfMemoryException(); @@ -81,7 +81,7 @@ internal static void RhReRegisterForFinalize(Object obj) [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhReRegisterForFinalize")] - private static extern bool _RhReRegisterForFinalize(Object obj); + private static extern bool _RhReRegisterForFinalize(object obj); // Wait for all pending finalizers. This must be a p/invoke to avoid starving the GC. [DllImport(RuntimeLibrary, ExactSpelling = true)] @@ -109,7 +109,7 @@ internal static void RhWaitForPendingFinalizers(bool allowReentrantWait) [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhGetGeneration")] - internal static extern int RhGetGeneration(Object obj); + internal static extern int RhGetGeneration(object obj); [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhGetGcLatencyMode")] @@ -207,9 +207,9 @@ internal static void RhWaitForPendingFinalizers(bool allowReentrantWait) // Allocate handle. [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhpHandleAlloc")] - private static extern IntPtr RhpHandleAlloc(Object value, GCHandleType type); + private static extern IntPtr RhpHandleAlloc(object value, GCHandleType type); - internal static IntPtr RhHandleAlloc(Object value, GCHandleType type) + internal static IntPtr RhHandleAlloc(object value, GCHandleType type) { IntPtr h = RhpHandleAlloc(value, type); if (h == IntPtr.Zero) @@ -220,9 +220,9 @@ internal static IntPtr RhHandleAlloc(Object value, GCHandleType type) // Allocate handle for dependent handle case where a secondary can be set at the same time. [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhpHandleAllocDependent")] - private static extern IntPtr RhpHandleAllocDependent(Object primary, Object secondary); + private static extern IntPtr RhpHandleAllocDependent(object primary, object secondary); - internal static IntPtr RhHandleAllocDependent(Object primary, Object secondary) + internal static IntPtr RhHandleAllocDependent(object primary, object secondary) { IntPtr h = RhpHandleAllocDependent(primary, secondary); if (h == IntPtr.Zero) @@ -233,9 +233,9 @@ internal static IntPtr RhHandleAllocDependent(Object primary, Object secondary) // Allocate variable handle with its initial type. [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhpHandleAllocVariable")] - private static extern IntPtr RhpHandleAllocVariable(Object value, uint type); + private static extern IntPtr RhpHandleAllocVariable(object value, uint type); - internal static IntPtr RhHandleAllocVariable(Object value, uint type) + internal static IntPtr RhHandleAllocVariable(object value, uint type) { IntPtr h = RhpHandleAllocVariable(value, type); if (h == IntPtr.Zero) @@ -251,9 +251,9 @@ internal static IntPtr RhHandleAllocVariable(Object value, uint type) // Get object reference from handle. [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhHandleGet")] - private static extern Object _RhHandleGet(IntPtr handle); + private static extern object _RhHandleGet(IntPtr handle); - internal static unsafe Object RhHandleGet(IntPtr handle) + internal static unsafe object RhHandleGet(IntPtr handle) { #if DEBUG // The runtime performs additional checks in debug builds @@ -266,17 +266,17 @@ internal static unsafe Object RhHandleGet(IntPtr handle) // Get primary and secondary object references from dependent handle. [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhHandleGetDependent")] - internal static extern Object RhHandleGetDependent(IntPtr handle, out Object secondary); + internal static extern object RhHandleGetDependent(IntPtr handle, out object secondary); // Set object reference into handle. [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhHandleSet")] - internal static extern void RhHandleSet(IntPtr handle, Object value); + internal static extern void RhHandleSet(IntPtr handle, object value); // Set the secondary object reference into a dependent handle. [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhHandleSetDependentSecondary")] - internal static extern void RhHandleSetDependentSecondary(IntPtr handle, Object secondary); + internal static extern void RhHandleSetDependentSecondary(IntPtr handle, object secondary); // Get the handle type associated with a variable handle. [MethodImpl(MethodImplOptions.InternalCall)] @@ -308,7 +308,7 @@ internal static unsafe Object RhHandleGet(IntPtr handle) [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhTypeCast_CheckArrayStore")] - internal static extern void RhCheckArrayStore(Object array, Object obj); + internal static extern void RhCheckArrayStore(object array, object obj); [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhTypeCast_IsInstanceOf")] @@ -346,7 +346,7 @@ internal static unsafe Object RhHandleGet(IntPtr handle) [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhNewString")] - internal static extern String RhNewString(EETypePtr pEEType, int length); + internal static extern string RhNewString(EETypePtr pEEType, int length); [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhBox")] @@ -561,11 +561,11 @@ internal static IntPtr RhGetModuleSection(TypeManagerHandle module, ReadyToRunSe #if !PROJECTN [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhGetThreadStaticStorageForModule")] - internal static unsafe extern Array RhGetThreadStaticStorageForModule(Int32 moduleIndex); + internal static unsafe extern Array RhGetThreadStaticStorageForModule(int moduleIndex); [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhSetThreadStaticStorageForModule")] - internal static unsafe extern bool RhSetThreadStaticStorageForModule(Array storage, Int32 moduleIndex); + internal static unsafe extern bool RhSetThreadStaticStorageForModule(Array storage, int moduleIndex); [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhCurrentNativeThreadId")] @@ -717,7 +717,7 @@ internal static byte[] ConvertPublicKeyToPublicKeyToken(byte[] publicKey) // [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhpETWLogLiveCom")] - internal extern static void RhpETWLogLiveCom(int eventType, IntPtr CCWHandle, IntPtr objectID, IntPtr typeRawValue, IntPtr IUnknown, IntPtr VTable, Int32 comRefCount, Int32 jupiterRefCount, Int32 flags); + internal extern static void RhpETWLogLiveCom(int eventType, IntPtr CCWHandle, IntPtr objectID, IntPtr typeRawValue, IntPtr IUnknown, IntPtr VTable, int comRefCount, int jupiterRefCount, int flags); [MethodImplAttribute(MethodImplOptions.InternalCall)] [RuntimeImport(RuntimeLibrary, "RhpETWShouldWalkCom")] diff --git a/src/System.Private.CoreLib/src/System/Runtime/TypeLoaderExports.cs b/src/System.Private.CoreLib/src/System/Runtime/TypeLoaderExports.cs index fe283e992d6..8e08a76daf4 100644 --- a/src/System.Private.CoreLib/src/System/Runtime/TypeLoaderExports.cs +++ b/src/System.Private.CoreLib/src/System/Runtime/TypeLoaderExports.cs @@ -109,7 +109,7 @@ public static IntPtr GenericLookup(IntPtr context, IntPtr signature) #if PROJECTN [RuntimeExport("GenericLookupAndCallCtor")] #endif - public static void GenericLookupAndCallCtor(Object arg, IntPtr context, IntPtr signature) + public static void GenericLookupAndCallCtor(object arg, IntPtr context, IntPtr signature) { Entry entry = LookupInCache(s_cache, context, signature); if (entry == null) @@ -122,27 +122,27 @@ public static void GenericLookupAndCallCtor(Object arg, IntPtr context, IntPtr s #if PROJECTN [RuntimeExport("GenericLookupAndAllocObject")] #endif - public static Object GenericLookupAndAllocObject(IntPtr context, IntPtr signature) + public static object GenericLookupAndAllocObject(IntPtr context, IntPtr signature) { Entry entry = LookupInCache(s_cache, context, signature); if (entry == null) { entry = CacheMiss(context, signature); } - return RawCalliHelper.Call(entry.Result, entry.AuxResult); + return RawCalliHelper.Call(entry.Result, entry.AuxResult); } #if PROJECTN [RuntimeExport("GenericLookupAndAllocArray")] #endif - public static Object GenericLookupAndAllocArray(IntPtr context, IntPtr arg, IntPtr signature) + public static object GenericLookupAndAllocArray(IntPtr context, IntPtr arg, IntPtr signature) { Entry entry = LookupInCache(s_cache, context, signature); if (entry == null) { entry = CacheMiss(context, signature); } - return RawCalliHelper.Call(entry.Result, entry.AuxResult, arg); + return RawCalliHelper.Call(entry.Result, entry.AuxResult, arg); } #if PROJECTN @@ -161,14 +161,14 @@ public static void GenericLookupAndCheckArrayElemType(IntPtr context, object arg #if PROJECTN [RuntimeExport("GenericLookupAndCast")] #endif - public static Object GenericLookupAndCast(Object arg, IntPtr context, IntPtr signature) + public static object GenericLookupAndCast(object arg, IntPtr context, IntPtr signature) { Entry entry = LookupInCache(s_cache, context, signature); if (entry == null) { entry = CacheMiss(context, signature); } - return RawCalliHelper.Call(entry.Result, arg, entry.AuxResult); + return RawCalliHelper.Call(entry.Result, arg, entry.AuxResult); } #if PROJECTN @@ -433,7 +433,7 @@ public static T Call(System.IntPtr pfn, IntPtr arg) } [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static void Call(System.IntPtr pfn, Object arg) + public static void Call(System.IntPtr pfn, object arg) { } @@ -451,12 +451,12 @@ public static T Call(System.IntPtr pfn, IntPtr arg1, IntPtr arg2, object arg3 } [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static void Call(System.IntPtr pfn, IntPtr arg1, Object arg2) + public static void Call(System.IntPtr pfn, IntPtr arg1, object arg2) { } [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] - public static T Call(System.IntPtr pfn, Object arg1, IntPtr arg2) + public static T Call(System.IntPtr pfn, object arg1, IntPtr arg2) { return default(T); } diff --git a/src/System.Private.CoreLib/src/System/RuntimeExceptionHelpers.cs b/src/System.Private.CoreLib/src/System/RuntimeExceptionHelpers.cs index ec40c126dc1..35d954368f7 100644 --- a/src/System.Private.CoreLib/src/System/RuntimeExceptionHelpers.cs +++ b/src/System.Private.CoreLib/src/System/RuntimeExceptionHelpers.cs @@ -129,7 +129,7 @@ private static string GetStringForFailFastReason(RhFailFastReason reason) } - public static void FailFast(String message) + public static void FailFast(string message) { FailFast(message, null, RhFailFastReason.Unknown, IntPtr.Zero, IntPtr.Zero); } @@ -184,7 +184,7 @@ public static void RuntimeFailFast(RhFailFastReason reason, Exception exception, Debug.WriteLine("Unhandled Exception: " + exception.ToString()); } - failFastMessage = String.Format("Runtime-generated FailFast: ({0}): {1}{2}", + failFastMessage = string.Format("Runtime-generated FailFast: ({0}): {1}{2}", reason.ToString(), // Explicit call to ToString() to avoid MissingMetadataException inside String.Format() GetStringForFailFastReason(reason), exception != null ? " [exception object available]" : ""); @@ -208,7 +208,7 @@ internal static void FailFast(string message, Exception exception, RhFailFastRea if (!minimalFailFast) { - String output = (exception != null) ? + string output = (exception != null) ? "Unhandled Exception: " + exception.ToString() : message; DeveloperExperience.Default.WriteLine(output); @@ -309,10 +309,10 @@ public ExceptionData() public struct ExceptionMetadataStruct { - public UInt32 ExceptionId { get; set; } // Id assigned to the exception. May not be contiguous or start at 0. - public UInt32 InnerExceptionId { get; set; } // ID of the inner exception or 0xFFFFFFFF for 'no inner exception' - public UInt32 ThreadId { get; set; } // Managed thread ID the eception was thrown on - public Int32 NestingLevel { get; set; } // If multiple exceptions are currently active on a thread, this gives the ordering for them. + public uint ExceptionId { get; set; } // Id assigned to the exception. May not be contiguous or start at 0. + public uint InnerExceptionId { get; set; } // ID of the inner exception or 0xFFFFFFFF for 'no inner exception' + public uint ThreadId { get; set; } // Managed thread ID the eception was thrown on + public int NestingLevel { get; set; } // If multiple exceptions are currently active on a thread, this gives the ordering for them. // The highest number is the most recent exception. -1 means the exception is not currently in flight // (but it may still be an InnerException). public IntPtr ExceptionCCWPtr { get; set; } // If the exception was thrown in an interop scenario, this contains the CCW pointer, otherwise, IntPtr.Zero @@ -390,7 +390,7 @@ public static void GenerateExceptionInformationForDump(Exception currentExceptio private static void SerializeExceptionsForDump(Exception currentException, IntPtr exceptionCCWPtr, LowLevelList serializedExceptions) { - const UInt32 NoInnerExceptionValue = 0xFFFFFFFF; + const uint NoInnerExceptionValue = 0xFFFFFFFF; // Approximate upper size limit for the serialized exceptions (but we'll always serialize currentException) // If we hit the limit, because we serialize in arbitrary order, there may be missing InnerExceptions or nested exceptions. @@ -442,10 +442,10 @@ private static void SerializeExceptionsForDump(Exception currentException, IntPt { ExceptionData exceptionData = s_exceptionDataTable.GetOrCreateValue(exceptions[i]); - exceptionData.ExceptionMetadata.ExceptionId = (UInt32)System.Threading.Interlocked.Increment(ref s_currentExceptionId); + exceptionData.ExceptionMetadata.ExceptionId = (uint)System.Threading.Interlocked.Increment(ref s_currentExceptionId); if (exceptionData.ExceptionMetadata.ExceptionId == NoInnerExceptionValue) { - exceptionData.ExceptionMetadata.ExceptionId = (UInt32)System.Threading.Interlocked.Increment(ref s_currentExceptionId); + exceptionData.ExceptionMetadata.ExceptionId = (uint)System.Threading.Interlocked.Increment(ref s_currentExceptionId); } exceptionData.ExceptionMetadata.ThreadId = currentThreadId; @@ -462,7 +462,7 @@ private static void SerializeExceptionsForDump(Exception currentException, IntPt } // Only match the CCW pointer up to the current exception - if (Object.ReferenceEquals(exceptions[i], currentException)) + if (object.ReferenceEquals(exceptions[i], currentException)) { exceptionData.ExceptionMetadata.ExceptionCCWPtr = exceptionCCWPtr; } diff --git a/src/System.Private.CoreLib/src/System/RuntimeFieldHandle.cs b/src/System.Private.CoreLib/src/System/RuntimeFieldHandle.cs index dac2f2958ac..3e9b5a5e2ec 100644 --- a/src/System.Private.CoreLib/src/System/RuntimeFieldHandle.cs +++ b/src/System.Private.CoreLib/src/System/RuntimeFieldHandle.cs @@ -18,7 +18,7 @@ public struct RuntimeFieldHandle : ISerializable public IntPtr Value => _value; - public override bool Equals(Object obj) + public override bool Equals(object obj) { if (!(obj is RuntimeFieldHandle)) return false; diff --git a/src/System.Private.CoreLib/src/System/RuntimeMethodHandle.cs b/src/System.Private.CoreLib/src/System/RuntimeMethodHandle.cs index c079f4756d0..02d1b8da082 100644 --- a/src/System.Private.CoreLib/src/System/RuntimeMethodHandle.cs +++ b/src/System.Private.CoreLib/src/System/RuntimeMethodHandle.cs @@ -20,7 +20,7 @@ public struct RuntimeMethodHandle : ISerializable public unsafe IntPtr Value => _value; - public override bool Equals(Object obj) + public override bool Equals(object obj) { if (!(obj is RuntimeMethodHandle)) return false; diff --git a/src/System.Private.CoreLib/src/System/RuntimeTypeHandle.cs b/src/System.Private.CoreLib/src/System/RuntimeTypeHandle.cs index c713560e67e..bf45ec90a14 100644 --- a/src/System.Private.CoreLib/src/System/RuntimeTypeHandle.cs +++ b/src/System.Private.CoreLib/src/System/RuntimeTypeHandle.cs @@ -26,7 +26,7 @@ internal RuntimeTypeHandle(EETypePtr pEEType) _value = pEEType.RawValue; } - public override bool Equals(Object obj) + public override bool Equals(object obj) { if (obj is RuntimeTypeHandle) { @@ -119,11 +119,11 @@ internal bool IsNull } // Last resort string for Type.ToString() when no metadata around. - internal String LastResortToString + internal string LastResortToString { get { - String s; + string s; EETypePtr eeType = this.ToEETypePtr(); IntPtr rawEEType = eeType.RawValue; IntPtr moduleBase = RuntimeImports.RhGetOSModuleFromEEType(rawEEType); @@ -140,7 +140,7 @@ internal String LastResortToString ReflectionExecutionDomainCallbacks callbacks = RuntimeAugments.CallbacksIfAvailable; if (callbacks != null) { - String penultimateLastResortString = callbacks.GetBetterDiagnosticInfoIfAvailable(this); + string penultimateLastResortString = callbacks.GetBetterDiagnosticInfoIfAvailable(this); if (penultimateLastResortString != null) s += "(" + penultimateLastResortString + ")"; } diff --git a/src/System.Private.CoreLib/src/System/String.CoreRT.cs b/src/System.Private.CoreLib/src/System/String.CoreRT.cs index 6e6603fa32d..3aedf2c5089 100644 --- a/src/System.Private.CoreLib/src/System/String.CoreRT.cs +++ b/src/System.Private.CoreLib/src/System/String.CoreRT.cs @@ -90,7 +90,7 @@ public partial class String #pragma warning restore - public static readonly String Empty = ""; + public static readonly string Empty = ""; [System.Runtime.CompilerServices.IndexerName("Chars")] public unsafe char this[int index] @@ -117,7 +117,7 @@ public int Length get { return _stringLength; } } - internal static String FastAllocateString(int length) + internal static string FastAllocateString(int length) { // We allocate one extra char as an interop convenience so that our strings are null- // terminated, however, we don't pass the extra +1 to the string allocation because the base diff --git a/src/System.Private.CoreLib/src/System/Text/EncodingData.cs b/src/System.Private.CoreLib/src/System/Text/EncodingData.cs index bff11e74418..852f578dcea 100644 --- a/src/System.Private.CoreLib/src/System/Text/EncodingData.cs +++ b/src/System.Private.CoreLib/src/System/Text/EncodingData.cs @@ -121,7 +121,7 @@ internal static partial class EncodingTable // The index of the entry in s_encodingNamesIndices will be the index of codepage in // s_codePagesByName. // - private static readonly UInt16[] s_codePagesByName = new UInt16[] + private static readonly ushort[] s_codePagesByName = new ushort[] { 20127, // ansi_x3.4-1968 20127, // ansi_x3.4-1986 @@ -177,7 +177,7 @@ internal static partial class EncodingTable // s_englishNames. In addition, this arrays indices correspond to the indices // into s_uiFamilyCodePages and s_flags. // - private static readonly UInt16[] s_mappedCodePages = new UInt16[] + private static readonly ushort[] s_mappedCodePages = new ushort[] { 1200, // utf-16 1201, // utf-16be diff --git a/src/System.Private.CoreLib/src/System/Text/StringBuilder.CoreRT.cs b/src/System.Private.CoreLib/src/System/Text/StringBuilder.CoreRT.cs index aab4e5d315a..9a9516e4f62 100644 --- a/src/System.Private.CoreLib/src/System/Text/StringBuilder.CoreRT.cs +++ b/src/System.Private.CoreLib/src/System/Text/StringBuilder.CoreRT.cs @@ -32,7 +32,7 @@ internal int GetAllocationLength(int requiredLength) /// internal unsafe void ReplaceBuffer(char* newBuffer) { - int len = String.wcslen(newBuffer); + int len = string.wcslen(newBuffer); // the '+1' is for back-compat with desktop CLR in terms of length calculation because desktop // CLR had '\0' diff --git a/src/System.Private.CoreLib/src/System/Threading/CancellationToken.cs b/src/System.Private.CoreLib/src/System/Threading/CancellationToken.cs index f37dc345799..ee7d8bf90f7 100644 --- a/src/System.Private.CoreLib/src/System/Threading/CancellationToken.cs +++ b/src/System.Private.CoreLib/src/System/Threading/CancellationToken.cs @@ -147,7 +147,7 @@ internal CancellationToken(CancellationTokenSource source) /* Methods */ - private static readonly Action s_ActionToActionObjShunt = new Action(ActionToActionObjShunt); + private static readonly Action s_ActionToActionObjShunt = new Action(ActionToActionObjShunt); private static void ActionToActionObjShunt(object obj) { Action action = obj as Action; @@ -231,7 +231,7 @@ public CancellationTokenRegistration Register(Action callback, bool useSynchroni /// The instance that can /// be used to unregister the callback. /// is null. - public CancellationTokenRegistration Register(Action callback, Object state) + public CancellationTokenRegistration Register(Action callback, object state) { if (callback == null) throw new ArgumentNullException(nameof(callback)); @@ -269,7 +269,7 @@ public CancellationTokenRegistration Register(Action callback, Object st /// is null. /// The associated CancellationTokenSource has been disposed. - public CancellationTokenRegistration Register(Action callback, Object state, bool useSynchronizationContext) + public CancellationTokenRegistration Register(Action callback, object state, bool useSynchronizationContext) { return Register( callback, @@ -281,7 +281,7 @@ public CancellationTokenRegistration Register(Action callback, Object st // 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 callback, Object state) + internal CancellationTokenRegistration InternalRegisterWithoutEC(Action callback, object state) { return Register( callback, @@ -313,7 +313,7 @@ internal CancellationTokenRegistration InternalRegisterWithoutEC(Action /// The associated CancellationTokenSource has been disposed. [MethodImpl(MethodImplOptions.NoInlining)] - public CancellationTokenRegistration Register(Action callback, Object state, bool useSynchronizationContext, bool useExecutionContext) + public CancellationTokenRegistration Register(Action callback, object state, bool useSynchronizationContext, bool useExecutionContext) { if (callback == null) throw new ArgumentNullException(nameof(callback)); @@ -386,7 +386,7 @@ public bool Equals(CancellationToken other) /// from public CancellationToken constructors and their values are equal. /// An associated CancellationTokenSource has been disposed. - public override bool Equals(Object other) + public override bool Equals(object other) { if (other is CancellationToken) { @@ -400,7 +400,7 @@ public override bool Equals(Object other) /// Serves as a hash function for a CancellationToken. /// /// A hash code for the current CancellationToken instance. - public override Int32 GetHashCode() + public override int GetHashCode() { if (m_source == null) { diff --git a/src/System.Private.CoreLib/src/System/Threading/CancellationTokenSource.cs b/src/System.Private.CoreLib/src/System/Threading/CancellationTokenSource.cs index fa34800a5bb..8a2e15b88f4 100644 --- a/src/System.Private.CoreLib/src/System/Threading/CancellationTokenSource.cs +++ b/src/System.Private.CoreLib/src/System/Threading/CancellationTokenSource.cs @@ -267,7 +267,7 @@ private CancellationTokenSource(bool set) public CancellationTokenSource(TimeSpan delay) { long totalMilliseconds = (long)delay.TotalMilliseconds; - if (totalMilliseconds < -1 || totalMilliseconds > Int32.MaxValue) + if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue) { throw new ArgumentOutOfRangeException(nameof(delay)); } @@ -294,7 +294,7 @@ public CancellationTokenSource(TimeSpan delay) /// canceled already. /// /// - public CancellationTokenSource(Int32 millisecondsDelay) + public CancellationTokenSource(int millisecondsDelay) { if (millisecondsDelay < -1) { @@ -305,7 +305,7 @@ public CancellationTokenSource(Int32 millisecondsDelay) } // Common initialization logic when constructing a CTS with a delay parameter - private void InitializeWithTimer(Int32 millisecondsDelay) + private void InitializeWithTimer(int millisecondsDelay) { m_state = NOT_CANCELED; m_timer = new Timer(s_timerCallback, this, millisecondsDelay, -1); @@ -398,7 +398,7 @@ public void Cancel(bool throwOnFirstException) public void CancelAfter(TimeSpan delay) { long totalMilliseconds = (long)delay.TotalMilliseconds; - if (totalMilliseconds < -1 || totalMilliseconds > Int32.MaxValue) + if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue) { throw new ArgumentOutOfRangeException(nameof(delay)); } @@ -430,7 +430,7 @@ public void CancelAfter(TimeSpan delay) /// canceled already. /// /// - public void CancelAfter(Int32 millisecondsDelay) + public void CancelAfter(int millisecondsDelay) { ThrowIfDisposed(); diff --git a/src/System.Private.CoreLib/src/System/Threading/Interlocked.cs b/src/System.Private.CoreLib/src/System/Threading/Interlocked.cs index e07fbf97ba3..c3917e87356 100644 --- a/src/System.Private.CoreLib/src/System/Threading/Interlocked.cs +++ b/src/System.Private.CoreLib/src/System/Threading/Interlocked.cs @@ -322,7 +322,7 @@ public static unsafe double CompareExchange(ref double location1, double value, [MethodImpl(MethodImplOptions.AggressiveInlining)] public static T CompareExchange(ref T location1, T value, T comparand) where T : class { - return Unsafe.As(RuntimeImports.InterlockedCompareExchange(ref Unsafe.As(ref location1), value, comparand)); + return Unsafe.As(RuntimeImports.InterlockedCompareExchange(ref Unsafe.As(ref location1), value, comparand)); } [Intrinsic] @@ -394,7 +394,7 @@ public static unsafe double Exchange(ref double location1, double value) [MethodImpl(MethodImplOptions.AggressiveInlining)] public static T Exchange(ref T location1, T value) where T : class { - return Unsafe.As(RuntimeImports.InterlockedExchange(ref Unsafe.As(ref location1), value)); + return Unsafe.As(RuntimeImports.InterlockedExchange(ref Unsafe.As(ref location1), value)); } [Intrinsic] diff --git a/src/System.Private.CoreLib/src/System/Threading/ManagedThreadId.cs b/src/System.Private.CoreLib/src/System/Threading/ManagedThreadId.cs index 370aeca095c..8bbb8ba259d 100644 --- a/src/System.Private.CoreLib/src/System/Threading/ManagedThreadId.cs +++ b/src/System.Private.CoreLib/src/System/Threading/ManagedThreadId.cs @@ -103,7 +103,7 @@ public ImmutableIdDispenser AllocateId(out int id) var right = _right; // Any free bits in current node? - if (bitmap != UInt32.MaxValue) + if (bitmap != uint.MaxValue) { int bit = 0; while ((bitmap & (uint)(1 << bit)) != 0) @@ -218,7 +218,7 @@ public static int AllocateId() { var updatedIdDispenser = priorIdDispenser.AllocateId(out id); var interlockedResult = Interlocked.CompareExchange(ref s_idDispenser, updatedIdDispenser, priorIdDispenser); - if (Object.ReferenceEquals(priorIdDispenser, interlockedResult)) + if (object.ReferenceEquals(priorIdDispenser, interlockedResult)) break; priorIdDispenser = interlockedResult; // we already have a volatile read that we can reuse for the next loop } @@ -240,7 +240,7 @@ public static void RecycleId(int id) { var updatedIdDispenser = s_idDispenser.RecycleId(id); var interlockedResult = Interlocked.CompareExchange(ref s_idDispenser, updatedIdDispenser, priorIdDispenser); - if (Object.ReferenceEquals(priorIdDispenser, interlockedResult)) + if (object.ReferenceEquals(priorIdDispenser, interlockedResult)) break; priorIdDispenser = interlockedResult; // we already have a volatile read that we can reuse for the next loop } diff --git a/src/System.Private.CoreLib/src/System/Threading/ManualResetEventSlim.cs b/src/System.Private.CoreLib/src/System/Threading/ManualResetEventSlim.cs index e092eb0f7bb..8153e3f907f 100644 --- a/src/System.Private.CoreLib/src/System/Threading/ManualResetEventSlim.cs +++ b/src/System.Private.CoreLib/src/System/Threading/ManualResetEventSlim.cs @@ -57,7 +57,7 @@ public class ManualResetEventSlim : IDisposable // -- State -- // //For a packed word a uint would seem better, but Interlocked.* doesn't support them as uint isn't CLS-compliant. - private volatile int m_combinedState; //ie a UInt32. Used for the state items listed below. + private volatile int m_combinedState; //ie a uint. Used for the state items listed below. //1-bit for signalled state private const int SignalledState_BitMask = unchecked((int)0x80000000);//1000 0000 0000 0000 0000 0000 0000 0000 @@ -163,7 +163,7 @@ private int Waiters // it is possible for the max number of waiters to be exceeded via user-code, hence we use a real exception here. if (value >= NumWaitersState_MaxValue) - throw new InvalidOperationException(String.Format(SR.ManualResetEventSlim_ctor_TooManyWaiters, NumWaitersState_MaxValue)); + throw new InvalidOperationException(string.Format(SR.ManualResetEventSlim_ctor_TooManyWaiters, NumWaitersState_MaxValue)); UpdateStateAtomically(value << NumWaitersState_ShiftCount, NumWaitersState_BitMask); } @@ -218,7 +218,7 @@ public ManualResetEventSlim(bool initialState, int spinCount) { throw new ArgumentOutOfRangeException( nameof(spinCount), - String.Format(SR.ManualResetEventSlim_ctor_SpinCountOutOfRange, SpinCountState_MaxValue)); + string.Format(SR.ManualResetEventSlim_ctor_SpinCountOutOfRange, SpinCountState_MaxValue)); } // We will suppress default spin because the user specified a count. @@ -690,7 +690,7 @@ public void Dispose() /// true to release both managed and unmanaged resources; /// false to release only unmanaged resources. /// - /// Unlike most of the members of , is not + /// Unlike most of the members of , is not /// thread-safe and may not be used concurrently with other members of this instance. /// protected virtual void Dispose(bool disposing) diff --git a/src/System.Private.CoreLib/src/System/Threading/Monitor.cs b/src/System.Private.CoreLib/src/System/Threading/Monitor.cs index e825d625bb2..b9839321a50 100644 --- a/src/System.Private.CoreLib/src/System/Threading/Monitor.cs +++ b/src/System.Private.CoreLib/src/System/Threading/Monitor.cs @@ -32,7 +32,7 @@ public static class Monitor private static ConditionalWeakTable s_conditionTable = new ConditionalWeakTable(); private static ConditionalWeakTable.CreateValueCallback s_createCondition = (o) => new Condition(GetLock(o)); - internal static Lock GetLock(Object obj) + internal static Lock GetLock(object obj) { if (obj == null) throw new ArgumentNullException(nameof(obj)); @@ -47,7 +47,7 @@ internal static Lock GetLock(Object obj) #endif } - private static Condition GetCondition(Object obj) + private static Condition GetCondition(object obj) { Debug.Assert( !(obj is Condition || obj is Lock), @@ -58,7 +58,7 @@ private static Condition GetCondition(Object obj) #region Public Enter/Exit methods - public static void Enter(Object obj) + public static void Enter(object obj) { Lock lck = GetLock(obj); if (lck.TryAcquire(0)) @@ -66,7 +66,7 @@ public static void Enter(Object obj) TryAcquireContended(lck, obj, Timeout.Infinite); } - public static void Enter(Object obj, ref bool lockTaken) + public static void Enter(object obj, ref bool lockTaken) { if (lockTaken) throw new ArgumentException(SR.Argument_MustBeFalse, nameof(lockTaken)); @@ -81,12 +81,12 @@ public static void Enter(Object obj, ref bool lockTaken) lockTaken = true; } - public static bool TryEnter(Object obj) + public static bool TryEnter(object obj) { return GetLock(obj).TryAcquire(0); } - public static void TryEnter(Object obj, ref bool lockTaken) + public static void TryEnter(object obj, ref bool lockTaken) { if (lockTaken) throw new ArgumentException(SR.Argument_MustBeFalse, nameof(lockTaken)); @@ -94,7 +94,7 @@ public static void TryEnter(Object obj, ref bool lockTaken) lockTaken = GetLock(obj).TryAcquire(0); } - public static bool TryEnter(Object obj, int millisecondsTimeout) + public static bool TryEnter(object obj, int millisecondsTimeout) { if (millisecondsTimeout < -1) throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); @@ -105,7 +105,7 @@ public static bool TryEnter(Object obj, int millisecondsTimeout) return TryAcquireContended(lck, obj, millisecondsTimeout); } - public static void TryEnter(Object obj, int millisecondsTimeout, ref bool lockTaken) + public static void TryEnter(object obj, int millisecondsTimeout, ref bool lockTaken) { if (lockTaken) throw new ArgumentException(SR.Argument_MustBeFalse, nameof(lockTaken)); @@ -121,18 +121,18 @@ public static void TryEnter(Object obj, int millisecondsTimeout, ref bool lockTa lockTaken = TryAcquireContended(lck, obj, millisecondsTimeout); } - public static bool TryEnter(Object obj, TimeSpan timeout) => + public static bool TryEnter(object obj, TimeSpan timeout) => TryEnter(obj, WaitHandle.ToTimeoutMilliseconds(timeout)); - public static void TryEnter(Object obj, TimeSpan timeout, ref bool lockTaken) => + public static void TryEnter(object obj, TimeSpan timeout, ref bool lockTaken) => TryEnter(obj, WaitHandle.ToTimeoutMilliseconds(timeout), ref lockTaken); - public static void Exit(Object obj) + public static void Exit(object obj) { GetLock(obj).Release(); } - public static bool IsEntered(Object obj) + public static bool IsEntered(object obj) { return GetLock(obj).IsAcquired; } @@ -142,14 +142,14 @@ public static bool IsEntered(Object obj) #region Public Wait/Pulse methods // Remoting is not supported, ignore exitContext - public static bool Wait(Object obj, int millisecondsTimeout, bool exitContext) => + public static bool Wait(object obj, int millisecondsTimeout, bool exitContext) => Wait(obj, millisecondsTimeout); // Remoting is not supported, ignore exitContext - public static bool Wait(Object obj, TimeSpan timeout, bool exitContext) => + public static bool Wait(object obj, TimeSpan timeout, bool exitContext) => Wait(obj, WaitHandle.ToTimeoutMilliseconds(timeout)); - public static bool Wait(Object obj, int millisecondsTimeout) + public static bool Wait(object obj, int millisecondsTimeout) { Condition condition = GetCondition(obj); DebugBlockingItem blockingItem; @@ -160,9 +160,9 @@ public static bool Wait(Object obj, int millisecondsTimeout) } } - public static bool Wait(Object obj, TimeSpan timeout) => Wait(obj, WaitHandle.ToTimeoutMilliseconds(timeout)); + public static bool Wait(object obj, TimeSpan timeout) => Wait(obj, WaitHandle.ToTimeoutMilliseconds(timeout)); - public static bool Wait(Object obj) => Wait(obj, Timeout.Infinite); + public static bool Wait(object obj) => Wait(obj, Timeout.Infinite); public static void Pulse(object obj) { @@ -178,7 +178,7 @@ public static void PulseAll(object obj) #region Slow path for Entry/TryEnter methods. - internal static bool TryAcquireContended(Lock lck, Object obj, int millisecondsTimeout) + internal static bool TryAcquireContended(Lock lck, object obj, int millisecondsTimeout) { DebugBlockingItem blockingItem; diff --git a/src/System.Private.CoreLib/src/System/Threading/SemaphoreSlim.cs b/src/System.Private.CoreLib/src/System/Threading/SemaphoreSlim.cs index a6828558be8..0fa2606025b 100644 --- a/src/System.Private.CoreLib/src/System/Threading/SemaphoreSlim.cs +++ b/src/System.Private.CoreLib/src/System/Threading/SemaphoreSlim.cs @@ -76,7 +76,7 @@ public class SemaphoreSlim : IDisposable new Task(false, false, (TaskCreationOptions)InternalTaskOptions.DoNotDispose, default(CancellationToken)); // No maximum constant - private const int NO_MAXIMUM = Int32.MaxValue; + private const int NO_MAXIMUM = int.MaxValue; // Task in a linked list of asynchronous waiters private sealed class TaskNode : Task, IThreadPoolWorkItem @@ -233,8 +233,8 @@ public void Wait(CancellationToken cancellationToken) public bool Wait(TimeSpan timeout) { // Validate the timeout - Int64 totalMilliseconds = (Int64)timeout.TotalMilliseconds; - if (totalMilliseconds < -1 || totalMilliseconds > Int32.MaxValue) + long totalMilliseconds = (long)timeout.TotalMilliseconds; + if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue) { throw new System.ArgumentOutOfRangeException( nameof(timeout), timeout, SR.SemaphoreSlim_Wait_TimeoutWrong); @@ -263,8 +263,8 @@ public bool Wait(TimeSpan timeout) public bool Wait(TimeSpan timeout, CancellationToken cancellationToken) { // Validate the timeout - Int64 totalMilliseconds = (Int64)timeout.TotalMilliseconds; - if (totalMilliseconds < -1 || totalMilliseconds > Int32.MaxValue) + long totalMilliseconds = (long)timeout.TotalMilliseconds; + if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue) { throw new System.ArgumentOutOfRangeException( nameof(timeout), timeout, SR.SemaphoreSlim_Wait_TimeoutWrong); @@ -568,8 +568,8 @@ public Task WaitAsync(TimeSpan timeout) public Task WaitAsync(TimeSpan timeout, CancellationToken cancellationToken) { // Validate the timeout - Int64 totalMilliseconds = (Int64)timeout.TotalMilliseconds; - if (totalMilliseconds < -1 || totalMilliseconds > Int32.MaxValue) + long totalMilliseconds = (long)timeout.TotalMilliseconds; + if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue) { throw new System.ArgumentOutOfRangeException( nameof(timeout), timeout, SR.SemaphoreSlim_Wait_TimeoutWrong); @@ -861,7 +861,7 @@ public void Dispose() /// true to release both managed and unmanaged resources; /// false to release only unmanaged resources. /// - /// Unlike most of the members of , is not + /// Unlike most of the members of , is not /// thread-safe and may not be used concurrently with other members of this instance. /// protected virtual void Dispose(bool disposing) diff --git a/src/System.Private.CoreLib/src/System/Threading/SpinLock.cs b/src/System.Private.CoreLib/src/System/Threading/SpinLock.cs index f949896e2ce..1c6c570b1f9 100644 --- a/src/System.Private.CoreLib/src/System/Threading/SpinLock.cs +++ b/src/System.Private.CoreLib/src/System/Threading/SpinLock.cs @@ -234,7 +234,7 @@ public void TryEnter(ref bool lockTaken) public void TryEnter(TimeSpan timeout, ref bool lockTaken) { // Validate the timeout - Int64 totalMilliseconds = (Int64)timeout.TotalMilliseconds; + long totalMilliseconds = (long)timeout.TotalMilliseconds; if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue) { throw new System.ArgumentOutOfRangeException( @@ -508,7 +508,7 @@ private void ContinueTryEnterWithThreadTracking(int millisecondsTimeout, uint st /// /// /// The default overload of provides the same behavior as if calling using true as the argument, but Exit() could be slightly faster than Exit(true). + /// cref="Exit(bool)"/> using true as the argument, but Exit() could be slightly faster than Exit(true). /// /// /// Thread ownership tracking is enabled, and the current thread is not the owner of this lock. @@ -530,7 +530,7 @@ public void Exit() /// publish the exit operation to other threads. /// /// - /// Calling with the argument set to + /// Calling with the argument set to /// true will improve the fairness of the lock at the expense of some performance. The default /// overload behaves as if specifying true for . diff --git a/src/System.Private.CoreLib/src/System/Threading/SynchronizationContext.cs b/src/System.Private.CoreLib/src/System/Threading/SynchronizationContext.cs index 92df1152a1a..f939c1647c1 100644 --- a/src/System.Private.CoreLib/src/System/Threading/SynchronizationContext.cs +++ b/src/System.Private.CoreLib/src/System/Threading/SynchronizationContext.cs @@ -43,12 +43,12 @@ public bool IsWaitNotificationRequired() return ((_props & SynchronizationContextProperties.RequireWaitNotification) != 0); } - public virtual void Send(SendOrPostCallback d, Object state) + public virtual void Send(SendOrPostCallback d, object state) { d(state); } - public virtual void Post(SendOrPostCallback d, Object state) + public virtual void Post(SendOrPostCallback d, object state) { ThreadPool.QueueUserWorkItem(new WaitCallback(d), state); } diff --git a/src/System.Private.CoreLib/src/System/Threading/Tasks/DebuggerSupport.Dummy.cs b/src/System.Private.CoreLib/src/System/Threading/Tasks/DebuggerSupport.Dummy.cs index 2cfa1be1f1e..12da2bd9045 100644 --- a/src/System.Private.CoreLib/src/System/Threading/Tasks/DebuggerSupport.Dummy.cs +++ b/src/System.Private.CoreLib/src/System/Threading/Tasks/DebuggerSupport.Dummy.cs @@ -22,7 +22,7 @@ public static bool LoggingOn } } - public static void TraceOperationCreation(CausalityTraceLevel traceLevel, Task task, String operationName, ulong relatedContext) + public static void TraceOperationCreation(CausalityTraceLevel traceLevel, Task task, string operationName, ulong relatedContext) { } diff --git a/src/System.Private.CoreLib/src/System/Threading/Tasks/DebuggerSupport.cs b/src/System.Private.CoreLib/src/System/Threading/Tasks/DebuggerSupport.cs index 0ee81c9376e..d58332dc1df 100644 --- a/src/System.Private.CoreLib/src/System/Threading/Tasks/DebuggerSupport.cs +++ b/src/System.Private.CoreLib/src/System/Threading/Tasks/DebuggerSupport.cs @@ -60,7 +60,7 @@ public static Task GetActiveTaskFromId(int taskId) } private static readonly LowLevelDictionary s_activeTasks = new LowLevelDictionary(); - private static readonly Object s_activeTasksLock = new Object(); + private static readonly object s_activeTasksLock = new object(); //============================================================================================================== // This section of the class wraps calls to get the lazy-created Task object for the purpose of reporting diff --git a/src/System.Private.CoreLib/src/System/Threading/Tasks/Future.cs b/src/System.Private.CoreLib/src/System/Threading/Tasks/Future.cs index cba96d1a4b9..6cb386ce0c6 100644 --- a/src/System.Private.CoreLib/src/System/Threading/Tasks/Future.cs +++ b/src/System.Private.CoreLib/src/System/Threading/Tasks/Future.cs @@ -773,7 +773,7 @@ public Task ContinueWith(Action> continuationAction, TaskContinuat /// /// The argument is null. /// - public Task ContinueWith(Action, Object> continuationAction, Object state) + public Task ContinueWith(Action, object> continuationAction, object state) { return ContinueWith(continuationAction, state, TaskScheduler.Current, default(CancellationToken), TaskContinuationOptions.None); } @@ -800,7 +800,7 @@ public Task ContinueWith(Action, Object> continuationAction, Objec /// The provided CancellationToken /// has already been disposed. /// - public Task ContinueWith(Action, Object> continuationAction, Object state, CancellationToken cancellationToken) + public Task ContinueWith(Action, object> continuationAction, object state, CancellationToken cancellationToken) { return ContinueWith(continuationAction, state, TaskScheduler.Current, cancellationToken, TaskContinuationOptions.None); } @@ -829,7 +829,7 @@ public Task ContinueWith(Action, Object> continuationAction, Objec /// /// The argument is null. /// - public Task ContinueWith(Action, Object> continuationAction, Object state, TaskScheduler scheduler) + public Task ContinueWith(Action, object> continuationAction, object state, TaskScheduler scheduler) { return ContinueWith(continuationAction, state, scheduler, default(CancellationToken), TaskContinuationOptions.None); } @@ -863,7 +863,7 @@ public Task ContinueWith(Action, Object> continuationAction, Objec /// The argument specifies an invalid value for TaskContinuationOptions. /// - public Task ContinueWith(Action, Object> continuationAction, Object state, TaskContinuationOptions continuationOptions) + public Task ContinueWith(Action, object> continuationAction, object state, TaskContinuationOptions continuationOptions) { return ContinueWith(continuationAction, state, TaskScheduler.Current, default(CancellationToken), continuationOptions); } @@ -907,14 +907,14 @@ public Task ContinueWith(Action, Object> continuationAction, Objec /// The provided CancellationToken /// has already been disposed. /// - public Task ContinueWith(Action, Object> continuationAction, Object state, CancellationToken cancellationToken, + public Task ContinueWith(Action, object> continuationAction, object state, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { return ContinueWith(continuationAction, state, scheduler, cancellationToken, continuationOptions); } // Same as the above overload, only with a stack mark. - internal Task ContinueWith(Action, Object> continuationAction, Object state, TaskScheduler scheduler, CancellationToken cancellationToken, + internal Task ContinueWith(Action, object> continuationAction, object state, TaskScheduler scheduler, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions) { if (continuationAction == null) @@ -1185,7 +1185,7 @@ public Task ContinueWith(Func, TNewResult> /// /// The argument is null. /// - public Task ContinueWith(Func, Object, TNewResult> continuationFunction, Object state) + public Task ContinueWith(Func, object, TNewResult> continuationFunction, object state) { return ContinueWith(continuationFunction, state, TaskScheduler.Current, default(CancellationToken), TaskContinuationOptions.None); } @@ -1215,7 +1215,7 @@ public Task ContinueWith(Func, Object, TNe /// The provided CancellationToken /// has already been disposed. /// - public Task ContinueWith(Func, Object, TNewResult> continuationFunction, Object state, + public Task ContinueWith(Func, object, TNewResult> continuationFunction, object state, CancellationToken cancellationToken) { return ContinueWith(continuationFunction, state, TaskScheduler.Current, cancellationToken, TaskContinuationOptions.None); @@ -1247,7 +1247,7 @@ public Task ContinueWith(Func, Object, TNe /// /// The argument is null. /// - public Task ContinueWith(Func, Object, TNewResult> continuationFunction, Object state, + public Task ContinueWith(Func, object, TNewResult> continuationFunction, object state, TaskScheduler scheduler) { return ContinueWith(continuationFunction, state, scheduler, default(CancellationToken), TaskContinuationOptions.None); @@ -1291,7 +1291,7 @@ public Task ContinueWith(Func, Object, TNe /// The argument specifies an invalid value for TaskContinuationOptions. /// - public Task ContinueWith(Func, Object, TNewResult> continuationFunction, Object state, + public Task ContinueWith(Func, object, TNewResult> continuationFunction, object state, TaskContinuationOptions continuationOptions) { return ContinueWith(continuationFunction, state, TaskScheduler.Current, default(CancellationToken), continuationOptions); @@ -1346,14 +1346,14 @@ public Task ContinueWith(Func, Object, TNe /// The provided CancellationToken /// has already been disposed. /// - public Task ContinueWith(Func, Object, TNewResult> continuationFunction, Object state, + public Task ContinueWith(Func, object, TNewResult> continuationFunction, object state, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { return ContinueWith(continuationFunction, state, scheduler, cancellationToken, continuationOptions); } // Same as the above overload, just with a stack mark. - internal Task ContinueWith(Func, Object, TNewResult> continuationFunction, Object state, + internal Task ContinueWith(Func, object, TNewResult> continuationFunction, object state, TaskScheduler scheduler, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions) { if (continuationFunction == null) diff --git a/src/System.Private.CoreLib/src/System/Threading/Tasks/FutureFactory.cs b/src/System.Private.CoreLib/src/System/Threading/Tasks/FutureFactory.cs index 4bee6c1e7be..f1b4d0e741a 100644 --- a/src/System.Private.CoreLib/src/System/Threading/Tasks/FutureFactory.cs +++ b/src/System.Private.CoreLib/src/System/Threading/Tasks/FutureFactory.cs @@ -401,7 +401,7 @@ public Task StartNew(Func function, CancellationToken cancella /// However, unless creation and scheduling must be separated, StartNew is the recommended approach /// for both simplicity and performance. /// - public Task StartNew(Func function, Object state) + public Task StartNew(Func function, object state) { Task currTask = Task.InternalCurrent; return Task.StartNew(currTask, function, state, m_defaultCancellationToken, @@ -430,7 +430,7 @@ public Task StartNew(Func function, Object state) /// However, unless creation and scheduling must be separated, StartNew is the recommended approach /// for both simplicity and performance. /// - public Task StartNew(Func function, Object state, CancellationToken cancellationToken) + public Task StartNew(Func function, object state, CancellationToken cancellationToken) { Task currTask = Task.InternalCurrent; return Task.StartNew(currTask, function, state, cancellationToken, @@ -461,7 +461,7 @@ public Task StartNew(Func function, Object state, Canc /// However, unless creation and scheduling must be separated, StartNew is the recommended approach /// for both simplicity and performance. /// - public Task StartNew(Func function, Object state, TaskCreationOptions creationOptions) + public Task StartNew(Func function, object state, TaskCreationOptions creationOptions) { Task currTask = Task.InternalCurrent; return Task.StartNew(currTask, function, state, m_defaultCancellationToken, @@ -503,7 +503,7 @@ public Task StartNew(Func function, Object state, Task /// However, unless creation and scheduling must be separated, StartNew is the recommended approach /// for both simplicity and performance. /// - public Task StartNew(Func function, Object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskScheduler scheduler) + public Task StartNew(Func function, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskScheduler scheduler) { return Task.StartNew(Task.InternalCurrentIfAttached(creationOptions), function, state, cancellationToken, creationOptions, InternalTaskOptions.None, scheduler); diff --git a/src/System.Private.CoreLib/src/System/Threading/Tasks/ProducerConsumerQueues.cs b/src/System.Private.CoreLib/src/System/Threading/Tasks/ProducerConsumerQueues.cs index 85a645dcd9b..3a75aaac8d1 100644 --- a/src/System.Private.CoreLib/src/System/Threading/Tasks/ProducerConsumerQueues.cs +++ b/src/System.Private.CoreLib/src/System/Threading/Tasks/ProducerConsumerQueues.cs @@ -129,7 +129,7 @@ internal sealed class SingleProducerSingleConsumerQueue : IProducerConsumerQu /// The initial size to use for segments (in number of elements). private const int INIT_SEGMENT_SIZE = 32; // must be a power of 2 /// The maximum size to use for segments (in number of elements). - private const int MAX_SEGMENT_SIZE = 0x1000000; // this could be made as large as Int32.MaxValue / 2 + private const int MAX_SEGMENT_SIZE = 0x1000000; // this could be made as large as int.MaxValue / 2 /// The head of the linked list of segments. private volatile Segment m_head; @@ -143,7 +143,7 @@ internal SingleProducerSingleConsumerQueue() Debug.Assert(INIT_SEGMENT_SIZE > 0, "Initial segment size must be > 0."); Debug.Assert((INIT_SEGMENT_SIZE & (INIT_SEGMENT_SIZE - 1)) == 0, "Initial segment size must be a power of 2"); Debug.Assert(INIT_SEGMENT_SIZE <= MAX_SEGMENT_SIZE, "Initial segment size should be <= maximum."); - Debug.Assert(MAX_SEGMENT_SIZE < Int32.MaxValue / 2, "Max segment size * 2 must be < Int32.MaxValue, or else overflow could occur."); + Debug.Assert(MAX_SEGMENT_SIZE < int.MaxValue / 2, "Max segment size * 2 must be < int.MaxValue, or else overflow could occur."); // Initialize the queue m_head = m_tail = new Segment(INIT_SEGMENT_SIZE); @@ -546,7 +546,7 @@ internal static class PaddingHelpers } /// Padding structure used to minimize false sharing in SingleProducerSingleConsumerQueue{T}. - [StructLayout(LayoutKind.Explicit, Size = PaddingHelpers.CACHE_LINE_SIZE - sizeof(Int32))] // Based on common case of 64-byte cache lines + [StructLayout(LayoutKind.Explicit, Size = PaddingHelpers.CACHE_LINE_SIZE - sizeof(int))] // Based on common case of 64-byte cache lines internal struct PaddingFor32 { } diff --git a/src/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs b/src/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs index 0ba4d97e076..c0123e4a482 100644 --- a/src/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs +++ b/src/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs @@ -648,8 +648,8 @@ private void AssignCancellationToken(CancellationToken cancellationToken, Task a // Static delegate to be used as a cancellation callback on unstarted tasks that have a valid cancellation token. // This is necessary to transition them into canceled state if their cancellation token is signalled while they are still not queued - private static readonly Action s_taskCancelCallback = new Action(TaskCancelCallback); - private static void TaskCancelCallback(Object o) + private static readonly Action s_taskCancelCallback = new Action(TaskCancelCallback); + private static void TaskCancelCallback(object o) { var targetTask = o as Task; if (targetTask == null) @@ -2649,7 +2649,7 @@ public void Wait() public bool Wait(TimeSpan timeout) { long totalMilliseconds = (long)timeout.TotalMilliseconds; - if (totalMilliseconds < -1 || totalMilliseconds > Int32.MaxValue) + if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue) { throw new ArgumentOutOfRangeException(nameof(timeout)); } @@ -3488,7 +3488,7 @@ public Task ContinueWith(Action continuationAction, TaskContinuationOption /// /// The argument is null. /// - public Task ContinueWith(Action continuationAction, Object state) + public Task ContinueWith(Action continuationAction, object state) { return ContinueWith(continuationAction, state, TaskScheduler.Current, default(CancellationToken), TaskContinuationOptions.None); } @@ -3514,7 +3514,7 @@ public Task ContinueWith(Action continuationAction, Object state) /// The provided CancellationToken /// has already been disposed. /// - public Task ContinueWith(Action continuationAction, Object state, CancellationToken cancellationToken) + public Task ContinueWith(Action continuationAction, object state, CancellationToken cancellationToken) { return ContinueWith(continuationAction, state, TaskScheduler.Current, cancellationToken, TaskContinuationOptions.None); } @@ -3542,7 +3542,7 @@ public Task ContinueWith(Action continuationAction, Object state, /// /// The argument is null. /// - public Task ContinueWith(Action continuationAction, Object state, TaskScheduler scheduler) + public Task ContinueWith(Action continuationAction, object state, TaskScheduler scheduler) { return ContinueWith(continuationAction, state, scheduler, default(CancellationToken), TaskContinuationOptions.None); } @@ -3576,7 +3576,7 @@ public Task ContinueWith(Action continuationAction, Object state, /// The argument specifies an invalid value for TaskContinuationOptions. /// - public Task ContinueWith(Action continuationAction, Object state, TaskContinuationOptions continuationOptions) + public Task ContinueWith(Action continuationAction, object state, TaskContinuationOptions continuationOptions) { return ContinueWith(continuationAction, state, TaskScheduler.Current, default(CancellationToken), continuationOptions); } @@ -3620,13 +3620,13 @@ public Task ContinueWith(Action continuationAction, Object state, /// The provided CancellationToken /// has already been disposed. /// - public Task ContinueWith(Action continuationAction, Object state, CancellationToken cancellationToken, + public Task ContinueWith(Action continuationAction, object state, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { return ContinueWith(continuationAction, state, scheduler, cancellationToken, continuationOptions); } - private Task ContinueWith(Action continuationAction, Object state, TaskScheduler scheduler, + private Task ContinueWith(Action continuationAction, object state, TaskScheduler scheduler, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions) { // Throw on continuation with null action @@ -3883,7 +3883,7 @@ public Task ContinueWith(Func continuationFunct /// /// The argument is null. /// - public Task ContinueWith(Func continuationFunction, Object state) + public Task ContinueWith(Func continuationFunction, object state) { return ContinueWith(continuationFunction, state, TaskScheduler.Current, default(CancellationToken), TaskContinuationOptions.None); @@ -3914,7 +3914,7 @@ public Task ContinueWith(Func continuat /// The provided CancellationToken /// has already been disposed. /// - public Task ContinueWith(Func continuationFunction, Object state, CancellationToken cancellationToken) + public Task ContinueWith(Func continuationFunction, object state, CancellationToken cancellationToken) { return ContinueWith(continuationFunction, state, TaskScheduler.Current, cancellationToken, TaskContinuationOptions.None); } @@ -3945,7 +3945,7 @@ public Task ContinueWith(Func continuat /// /// The argument is null. /// - public Task ContinueWith(Func continuationFunction, Object state, TaskScheduler scheduler) + public Task ContinueWith(Func continuationFunction, object state, TaskScheduler scheduler) { return ContinueWith(continuationFunction, state, scheduler, default(CancellationToken), TaskContinuationOptions.None); } @@ -3982,7 +3982,7 @@ public Task ContinueWith(Func continuat /// The argument specifies an invalid value for TaskContinuationOptions. /// - public Task ContinueWith(Func continuationFunction, Object state, TaskContinuationOptions continuationOptions) + public Task ContinueWith(Func continuationFunction, object state, TaskContinuationOptions continuationOptions) { return ContinueWith(continuationFunction, state, TaskScheduler.Current, default(CancellationToken), continuationOptions); } @@ -4029,14 +4029,14 @@ public Task ContinueWith(Func continuat /// The provided CancellationToken /// has already been disposed. /// - public Task ContinueWith(Func continuationFunction, Object state, CancellationToken cancellationToken, + public Task ContinueWith(Func continuationFunction, object state, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { return ContinueWith(continuationFunction, state, scheduler, cancellationToken, continuationOptions); } // Same as the above overload, just with a stack mark parameter. - private Task ContinueWith(Func continuationFunction, Object state, TaskScheduler scheduler, + private Task ContinueWith(Func continuationFunction, object state, TaskScheduler scheduler, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions) { // Throw on continuation with null function @@ -4416,7 +4416,7 @@ public static void WaitAll(params Task[] tasks) public static bool WaitAll(Task[] tasks, TimeSpan timeout) { long totalMilliseconds = (long)timeout.TotalMilliseconds; - if (totalMilliseconds < -1 || totalMilliseconds > Int32.MaxValue) + if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue) { throw new ArgumentOutOfRangeException(nameof(timeout)); } @@ -4799,7 +4799,7 @@ public static int WaitAny(params Task[] tasks) public static int WaitAny(Task[] tasks, TimeSpan timeout) { long totalMilliseconds = (long)timeout.TotalMilliseconds; - if (totalMilliseconds < -1 || totalMilliseconds > Int32.MaxValue) + if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue) { throw new ArgumentOutOfRangeException(nameof(timeout)); } @@ -5241,7 +5241,7 @@ public static Task Delay(TimeSpan delay) public static Task Delay(TimeSpan delay, CancellationToken cancellationToken) { long totalMilliseconds = (long)delay.TotalMilliseconds; - if (totalMilliseconds < -1 || totalMilliseconds > Int32.MaxValue) + if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue) { throw new ArgumentOutOfRangeException(nameof(delay), SR.Task_Delay_InvalidDelay); } diff --git a/src/System.Private.CoreLib/src/System/Threading/Tasks/TaskFactory.cs b/src/System.Private.CoreLib/src/System/Threading/Tasks/TaskFactory.cs index 89235b45cfb..05c829cbbd7 100644 --- a/src/System.Private.CoreLib/src/System/Threading/Tasks/TaskFactory.cs +++ b/src/System.Private.CoreLib/src/System/Threading/Tasks/TaskFactory.cs @@ -416,7 +416,7 @@ internal Task StartNew(Action action, CancellationToken cancellationToken, TaskC /// However, unless creation and scheduling must be separated, StartNew is the recommended approach /// for both simplicity and performance. /// - public Task StartNew(Action action, Object state) + public Task StartNew(Action action, object state) { Task currTask = Task.InternalCurrent; return Task.InternalStartNew(currTask, action, state, m_defaultCancellationToken, GetDefaultScheduler(currTask), @@ -445,7 +445,7 @@ public Task StartNew(Action action, Object state) /// However, unless creation and scheduling must be separated, StartNew is the recommended approach /// for both simplicity and performance. /// - public Task StartNew(Action action, Object state, CancellationToken cancellationToken) + public Task StartNew(Action action, object state, CancellationToken cancellationToken) { Task currTask = Task.InternalCurrent; return Task.InternalStartNew(currTask, action, state, cancellationToken, GetDefaultScheduler(currTask), @@ -475,7 +475,7 @@ public Task StartNew(Action action, Object state, CancellationToken canc /// However, unless creation and scheduling must be separated, StartNew is the recommended approach /// for both simplicity and performance. /// - public Task StartNew(Action action, Object state, TaskCreationOptions creationOptions) + public Task StartNew(Action action, object state, TaskCreationOptions creationOptions) { Task currTask = Task.InternalCurrent; return Task.InternalStartNew(currTask, action, state, m_defaultCancellationToken, GetDefaultScheduler(currTask), @@ -516,7 +516,7 @@ public Task StartNew(Action action, Object state, TaskCreationOptions cr /// However, unless creation and scheduling must be separated, StartNew is the recommended approach /// for both simplicity and performance. /// - public Task StartNew(Action action, Object state, CancellationToken cancellationToken, + public Task StartNew(Action action, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskScheduler scheduler) { return Task.InternalStartNew( @@ -677,7 +677,7 @@ public Task StartNew(Func function, CancellationToken /// However, unless creation and scheduling must be separated, StartNew is the recommended approach /// for both simplicity and performance. /// - public Task StartNew(Func function, Object state) + public Task StartNew(Func function, object state) { Task currTask = Task.InternalCurrent; return Task.StartNew(currTask, function, state, m_defaultCancellationToken, @@ -710,7 +710,7 @@ public Task StartNew(Func function, Object st /// However, unless creation and scheduling must be separated, StartNew is the recommended approach /// for both simplicity and performance. /// - public Task StartNew(Func function, Object state, CancellationToken cancellationToken) + public Task StartNew(Func function, object state, CancellationToken cancellationToken) { Task currTask = Task.InternalCurrent; return Task.StartNew(currTask, function, state, cancellationToken, @@ -744,7 +744,7 @@ public Task StartNew(Func function, Object st /// However, unless creation and scheduling must be separated, StartNew is the recommended approach /// for both simplicity and performance. /// - public Task StartNew(Func function, Object state, TaskCreationOptions creationOptions) + public Task StartNew(Func function, object state, TaskCreationOptions creationOptions) { Task currTask = Task.InternalCurrent; return Task.StartNew(currTask, function, state, m_defaultCancellationToken, @@ -789,7 +789,7 @@ public Task StartNew(Func function, Object st /// However, unless creation and scheduling must be separated, StartNew is the recommended approach /// for both simplicity and performance. /// - public Task StartNew(Func function, Object state, CancellationToken cancellationToken, + public Task StartNew(Func function, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskScheduler scheduler) { return Task.StartNew( diff --git a/src/System.Private.CoreLib/src/System/Threading/Tasks/TaskScheduler.cs b/src/System.Private.CoreLib/src/System/Threading/Tasks/TaskScheduler.cs index c9c6e4c807f..026cfce6dba 100644 --- a/src/System.Private.CoreLib/src/System/Threading/Tasks/TaskScheduler.cs +++ b/src/System.Private.CoreLib/src/System/Threading/Tasks/TaskScheduler.cs @@ -148,11 +148,11 @@ public abstract class TaskScheduler /// Indicates the maximum concurrency level this /// is able to support. /// - public virtual Int32 MaximumConcurrencyLevel + public virtual int MaximumConcurrencyLevel { get { - return Int32.MaxValue; + return int.MaxValue; } } @@ -366,7 +366,7 @@ public static TaskScheduler FromCurrentSynchronizationContext() /// /// Gets the unique ID for this . /// - public Int32 Id + public int Id { get { @@ -580,7 +580,7 @@ public SystemThreadingTasks_TaskSchedulerDebugView(TaskScheduler scheduler) } // returns the scheduler's Id - public Int32 Id + public int Id { get { return m_taskScheduler.Id; } } @@ -664,7 +664,7 @@ protected override IEnumerable GetScheduledTasks() /// By default it returns 1, because a based /// scheduler only supports execution on a single thread. /// - public override Int32 MaximumConcurrencyLevel + public override int MaximumConcurrencyLevel { get { diff --git a/src/System.Private.CoreLib/src/System/Threading/ThreadPool.Windows.cs b/src/System.Private.CoreLib/src/System/Threading/ThreadPool.Windows.cs index a15a38437fa..751fa683f33 100644 --- a/src/System.Private.CoreLib/src/System/Threading/ThreadPool.Windows.cs +++ b/src/System.Private.CoreLib/src/System/Threading/ThreadPool.Windows.cs @@ -326,7 +326,7 @@ internal static void RequestWorkerThread() private static RegisteredWaitHandle RegisterWaitForSingleObject( WaitHandle waitObject, WaitOrTimerCallback callBack, - Object state, + object state, uint millisecondsTimeOutInterval, bool executeOnlyOnce, bool flowExecutionContext) diff --git a/src/System.Private.CoreLib/src/System/Threading/ThreadPool.cs b/src/System.Private.CoreLib/src/System/Threading/ThreadPool.cs index 751a9f165d3..9eaf1d4d57d 100644 --- a/src/System.Private.CoreLib/src/System/Threading/ThreadPool.cs +++ b/src/System.Private.CoreLib/src/System/Threading/ThreadPool.cs @@ -673,9 +673,9 @@ private void CleanUp() } } - public delegate void WaitCallback(Object state); + public delegate void WaitCallback(object state); - public delegate void WaitOrTimerCallback(Object state, bool timedOut); // signalled or timed out + public delegate void WaitOrTimerCallback(object state, bool timedOut); // signalled or timed out // // Interface to something that can be queued to the TP. This is implemented by @@ -887,11 +887,11 @@ internal class _ThreadPoolWaitOrTimerCallback { private WaitOrTimerCallback _waitOrTimerCallback; private ExecutionContext _executionContext; - private Object _state; + private object _state; private static readonly ContextCallback _ccbt = new ContextCallback(WaitOrTimerCallback_Context_t); private static readonly ContextCallback _ccbf = new ContextCallback(WaitOrTimerCallback_Context_f); - internal _ThreadPoolWaitOrTimerCallback(WaitOrTimerCallback waitOrTimerCallback, Object state, bool flowExecutionContext) + internal _ThreadPoolWaitOrTimerCallback(WaitOrTimerCallback waitOrTimerCallback, object state, bool flowExecutionContext) { _waitOrTimerCallback = waitOrTimerCallback; _state = state; @@ -903,13 +903,13 @@ internal _ThreadPoolWaitOrTimerCallback(WaitOrTimerCallback waitOrTimerCallback, } } - private static void WaitOrTimerCallback_Context_t(Object state) => + private static void WaitOrTimerCallback_Context_t(object state) => WaitOrTimerCallback_Context(state, timedOut: true); - private static void WaitOrTimerCallback_Context_f(Object state) => + private static void WaitOrTimerCallback_Context_f(object state) => WaitOrTimerCallback_Context(state, timedOut: false); - private static void WaitOrTimerCallback_Context(Object state, bool timedOut) + private static void WaitOrTimerCallback_Context(object state, bool timedOut) { _ThreadPoolWaitOrTimerCallback helper = (_ThreadPoolWaitOrTimerCallback)state; helper._waitOrTimerCallback(helper._state, timedOut); @@ -938,7 +938,7 @@ public static partial class ThreadPool public static RegisteredWaitHandle RegisterWaitForSingleObject( WaitHandle waitObject, WaitOrTimerCallback callBack, - Object state, + object state, uint millisecondsTimeOutInterval, bool executeOnlyOnce) { @@ -951,7 +951,7 @@ public static partial class ThreadPool public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject( WaitHandle waitObject, WaitOrTimerCallback callBack, - Object state, + object state, uint millisecondsTimeOutInterval, bool executeOnlyOnce) { @@ -963,71 +963,71 @@ public static partial class ThreadPool public static RegisteredWaitHandle RegisterWaitForSingleObject( WaitHandle waitObject, WaitOrTimerCallback callBack, - Object state, + object state, int millisecondsTimeOutInterval, bool executeOnlyOnce) { if (millisecondsTimeOutInterval < -1) throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); - return RegisterWaitForSingleObject(waitObject, callBack, state, (UInt32)millisecondsTimeOutInterval, executeOnlyOnce, true); + return RegisterWaitForSingleObject(waitObject, callBack, state, (uint)millisecondsTimeOutInterval, executeOnlyOnce, true); } public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject( WaitHandle waitObject, WaitOrTimerCallback callBack, - Object state, + object state, int millisecondsTimeOutInterval, bool executeOnlyOnce) { if (millisecondsTimeOutInterval < -1) throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); - return RegisterWaitForSingleObject(waitObject, callBack, state, (UInt32)millisecondsTimeOutInterval, executeOnlyOnce, false); + return RegisterWaitForSingleObject(waitObject, callBack, state, (uint)millisecondsTimeOutInterval, executeOnlyOnce, false); } public static RegisteredWaitHandle RegisterWaitForSingleObject( WaitHandle waitObject, WaitOrTimerCallback callBack, - Object state, + object state, long millisecondsTimeOutInterval, bool executeOnlyOnce) { if (millisecondsTimeOutInterval < -1 || millisecondsTimeOutInterval > int.MaxValue) throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); - return RegisterWaitForSingleObject(waitObject, callBack, state, (UInt32)millisecondsTimeOutInterval, executeOnlyOnce, true); + return RegisterWaitForSingleObject(waitObject, callBack, state, (uint)millisecondsTimeOutInterval, executeOnlyOnce, true); } public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject( WaitHandle waitObject, WaitOrTimerCallback callBack, - Object state, + object state, long millisecondsTimeOutInterval, bool executeOnlyOnce) { if (millisecondsTimeOutInterval < -1 || millisecondsTimeOutInterval > int.MaxValue) throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); - return RegisterWaitForSingleObject(waitObject, callBack, state, (UInt32)millisecondsTimeOutInterval, executeOnlyOnce, false); + return RegisterWaitForSingleObject(waitObject, callBack, state, (uint)millisecondsTimeOutInterval, executeOnlyOnce, false); } public static RegisteredWaitHandle RegisterWaitForSingleObject( WaitHandle waitObject, WaitOrTimerCallback callBack, - Object state, + object state, TimeSpan timeout, bool executeOnlyOnce) { int tm = WaitHandle.ToTimeoutMilliseconds(timeout); - return RegisterWaitForSingleObject(waitObject, callBack, state, (UInt32)tm, executeOnlyOnce, true); + return RegisterWaitForSingleObject(waitObject, callBack, state, (uint)tm, executeOnlyOnce, true); } public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject( WaitHandle waitObject, WaitOrTimerCallback callBack, - Object state, + object state, TimeSpan timeout, bool executeOnlyOnce) { int tm = WaitHandle.ToTimeoutMilliseconds(timeout); - return RegisterWaitForSingleObject(waitObject, callBack, state, (UInt32)tm, executeOnlyOnce, false); + return RegisterWaitForSingleObject(waitObject, callBack, state, (uint)tm, executeOnlyOnce, false); } public static bool QueueUserWorkItem(WaitCallback callBack) => @@ -1069,7 +1069,7 @@ public static bool QueueUserWorkItem(Action callBack, TState sta return true; } - public static bool UnsafeQueueUserWorkItem(WaitCallback callBack, Object state) + public static bool UnsafeQueueUserWorkItem(WaitCallback callBack, object state) { if (callBack == null) { diff --git a/src/System.Private.CoreLib/src/System/Threading/Timer.Unix.cs b/src/System.Private.CoreLib/src/System/Threading/Timer.Unix.cs index 403478d98ad..705f93e7a7e 100644 --- a/src/System.Private.CoreLib/src/System/Threading/Timer.Unix.cs +++ b/src/System.Private.CoreLib/src/System/Threading/Timer.Unix.cs @@ -32,7 +32,7 @@ private void SetTimer(uint actualDuration) // Note: AutoResetEvent.WaitOne takes an Int32 value as a timeout. // The TimerQueue code ensures that timer duration is not greater than max Int32 value - Debug.Assert(actualDuration <= (uint)Int32.MaxValue); + Debug.Assert(actualDuration <= (uint)int.MaxValue); s_nextTimerDuration = (int)actualDuration; // If this is the first time the timer is set then we need to create a thread that diff --git a/src/System.Private.CoreLib/src/System/Threading/Timer.cs b/src/System.Private.CoreLib/src/System/Threading/Timer.cs index fc284fd4e9c..9fd71a0b419 100644 --- a/src/System.Private.CoreLib/src/System/Threading/Timer.cs +++ b/src/System.Private.CoreLib/src/System/Threading/Timer.cs @@ -6,7 +6,7 @@ namespace System.Threading { - public delegate void TimerCallback(Object state); + public delegate void TimerCallback(object state); // // TimerQueue maintains a list of active timers in this AppDomain. We use a single native timer to schedule @@ -51,7 +51,7 @@ private TimerQueue() #region interface to native per-AppDomain timer private int _currentNativeTimerStartTicks; - private uint _currentNativeTimerDuration = UInt32.MaxValue; + private uint _currentNativeTimerDuration = uint.MaxValue; private void EnsureAppDomainTimerFiresBy(uint requestedDuration) { @@ -66,7 +66,7 @@ private void EnsureAppDomainTimerFiresBy(uint requestedDuration) const uint maxPossibleDuration = 0x0fffffff; uint actualDuration = Math.Min(requestedDuration, maxPossibleDuration); - if (_currentNativeTimerDuration != UInt32.MaxValue) + if (_currentNativeTimerDuration != uint.MaxValue) { uint elapsed = (uint)(TickCount - _currentNativeTimerStartTicks); if (elapsed >= _currentNativeTimerDuration) @@ -109,7 +109,7 @@ private void FireNextTimers() // // since we got here, that means our previous timer has fired. // - _currentNativeTimerDuration = UInt32.MaxValue; + _currentNativeTimerDuration = uint.MaxValue; bool haveTimerToSchedule = false; uint nextAppDomainTimerDuration = uint.MaxValue; @@ -298,7 +298,7 @@ internal sealed partial class TimerQueueTimer // Info about the user's callback // private readonly TimerCallback _timerCallback; - private readonly Object _state; + private readonly object _state; private readonly ExecutionContext _executionContext; @@ -496,12 +496,12 @@ public bool Close(WaitHandle notifyObject) public sealed class Timer : MarshalByRefObject, IDisposable { - private const UInt32 MAX_SUPPORTED_TIMEOUT = (uint)0xfffffffe; + private const uint MAX_SUPPORTED_TIMEOUT = (uint)0xfffffffe; private TimerHolder _timer; public Timer(TimerCallback callback, - Object state, + object state, int dueTime, int period) { @@ -510,11 +510,11 @@ public sealed class Timer : MarshalByRefObject, IDisposable if (period < -1) throw new ArgumentOutOfRangeException(nameof(period), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); - TimerSetup(callback, state, (UInt32)dueTime, (UInt32)period); + TimerSetup(callback, state, (uint)dueTime, (uint)period); } public Timer(TimerCallback callback, - Object state, + object state, TimeSpan dueTime, TimeSpan period) { @@ -530,20 +530,20 @@ public sealed class Timer : MarshalByRefObject, IDisposable if (periodTm > MAX_SUPPORTED_TIMEOUT) throw new ArgumentOutOfRangeException(nameof(periodTm), SR.ArgumentOutOfRange_PeriodTooLarge); - TimerSetup(callback, state, (UInt32)dueTm, (UInt32)periodTm); + TimerSetup(callback, state, (uint)dueTm, (uint)periodTm); } [CLSCompliant(false)] public Timer(TimerCallback callback, - Object state, - UInt32 dueTime, - UInt32 period) + object state, + uint dueTime, + uint period) { TimerSetup(callback, state, dueTime, period); } public Timer(TimerCallback callback, - Object state, + object state, long dueTime, long period) { @@ -555,7 +555,7 @@ public sealed class Timer : MarshalByRefObject, IDisposable throw new ArgumentOutOfRangeException(nameof(dueTime), SR.ArgumentOutOfRange_TimeoutTooLarge); if (period > MAX_SUPPORTED_TIMEOUT) throw new ArgumentOutOfRangeException(nameof(period), SR.ArgumentOutOfRange_PeriodTooLarge); - TimerSetup(callback, state, (UInt32)dueTime, (UInt32)period); + TimerSetup(callback, state, (uint)dueTime, (uint)period); } public Timer(TimerCallback callback) @@ -565,13 +565,13 @@ public Timer(TimerCallback callback) // 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); + TimerSetup(callback, this, (uint)dueTime, (uint)period); } private void TimerSetup(TimerCallback callback, - Object state, - UInt32 dueTime, - UInt32 period) + object state, + uint dueTime, + uint period) { if (callback == null) throw new ArgumentNullException(nameof(TimerCallback)); @@ -586,7 +586,7 @@ public bool Change(int dueTime, int period) if (period < -1) throw new ArgumentOutOfRangeException(nameof(period), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); - return _timer.m_timer.Change((UInt32)dueTime, (UInt32)period); + return _timer.m_timer.Change((uint)dueTime, (uint)period); } public bool Change(TimeSpan dueTime, TimeSpan period) @@ -595,7 +595,7 @@ public bool Change(TimeSpan dueTime, TimeSpan period) } [CLSCompliant(false)] - public bool Change(UInt32 dueTime, UInt32 period) + public bool Change(uint dueTime, uint period) { return _timer.m_timer.Change(dueTime, period); } @@ -611,7 +611,7 @@ public bool Change(long dueTime, long period) if (period > MAX_SUPPORTED_TIMEOUT) throw new ArgumentOutOfRangeException(nameof(period), SR.ArgumentOutOfRange_PeriodTooLarge); - return _timer.m_timer.Change((UInt32)dueTime, (UInt32)period); + return _timer.m_timer.Change((uint)dueTime, (uint)period); } public bool Dispose(WaitHandle notifyObject) diff --git a/src/System.Private.CoreLib/src/System/Threading/Volatile.cs b/src/System.Private.CoreLib/src/System/Threading/Volatile.cs index d9a009d7311..00543f82da2 100644 --- a/src/System.Private.CoreLib/src/System/Threading/Volatile.cs +++ b/src/System.Private.CoreLib/src/System/Threading/Volatile.cs @@ -17,76 +17,76 @@ namespace System.Threading public static unsafe class Volatile { #region Boolean - private struct VolatileBoolean { public volatile Boolean Value; } + private struct VolatileBoolean { public volatile bool Value; } - public static Boolean Read(ref Boolean location) + public static bool Read(ref bool location) { - return Unsafe.As(ref location).Value; + return Unsafe.As(ref location).Value; } - public static void Write(ref Boolean location, Boolean value) + public static void Write(ref bool location, bool value) { - Unsafe.As(ref location).Value = value; + Unsafe.As(ref location).Value = value; } #endregion #region Byte - private struct VolatileByte { public volatile Byte Value; } + private struct VolatileByte { public volatile byte Value; } - public static Byte Read(ref Byte location) + public static byte Read(ref byte location) { - return Unsafe.As(ref location).Value; + return Unsafe.As(ref location).Value; } - public static void Write(ref Byte location, Byte value) + public static void Write(ref byte location, byte value) { - Unsafe.As(ref location).Value = value; + Unsafe.As(ref location).Value = value; } #endregion #region Double - public static Double Read(ref Double location) + public static double Read(ref double location) { - Int64 result = Read(ref Unsafe.As(ref location)); + long result = Read(ref Unsafe.As(ref location)); return *(double*)&result; } - public static void Write(ref Double location, Double value) + public static void Write(ref double location, double value) { - Write(ref Unsafe.As(ref location), *(Int64*)&value); + Write(ref Unsafe.As(ref location), *(long*)&value); } #endregion #region Int16 - private struct VolatileInt16 { public volatile Int16 Value; } + private struct VolatileInt16 { public volatile short Value; } - public static Int16 Read(ref Int16 location) + public static short Read(ref short location) { - return Unsafe.As(ref location).Value; + return Unsafe.As(ref location).Value; } - public static void Write(ref Int16 location, Int16 value) + public static void Write(ref short location, short value) { - Unsafe.As(ref location).Value = value; + Unsafe.As(ref location).Value = value; } #endregion #region Int32 - private struct VolatileInt32 { public volatile Int32 Value; } + private struct VolatileInt32 { public volatile int Value; } - public static Int32 Read(ref Int32 location) + public static int Read(ref int location) { - return Unsafe.As(ref location).Value; + return Unsafe.As(ref location).Value; } - public static void Write(ref Int32 location, Int32 value) + public static void Write(ref int location, int value) { - Unsafe.As(ref location).Value = value; + Unsafe.As(ref location).Value = value; } #endregion #region Int64 - public static Int64 Read(ref Int64 location) + public static long Read(ref long location) { #if BIT64 return (Int64)Unsafe.As(ref location).Value; @@ -95,7 +95,7 @@ public static Int64 Read(ref Int64 location) #endif } - public static void Write(ref Int64 location, Int64 value) + public static void Write(ref long location, long value) { #if BIT64 Unsafe.As(ref location).Value = (IntPtr)value; @@ -123,78 +123,78 @@ public static void Write(ref IntPtr location, IntPtr value) #endregion #region SByte - private struct VolatileSByte { public volatile SByte Value; } + private struct VolatileSByte { public volatile sbyte Value; } [CLSCompliant(false)] - public static SByte Read(ref SByte location) + public static sbyte Read(ref sbyte location) { - return Unsafe.As(ref location).Value; + return Unsafe.As(ref location).Value; } [CLSCompliant(false)] - public static void Write(ref SByte location, SByte value) + public static void Write(ref sbyte location, sbyte value) { - Unsafe.As(ref location).Value = value; + Unsafe.As(ref location).Value = value; } #endregion #region Single - private struct VolatileSingle { public volatile Single Value; } + private struct VolatileSingle { public volatile float Value; } - public static Single Read(ref Single location) + public static float Read(ref float location) { - return Unsafe.As(ref location).Value; + return Unsafe.As(ref location).Value; } - public static void Write(ref Single location, Single value) + public static void Write(ref float location, float value) { - Unsafe.As(ref location).Value = value; + Unsafe.As(ref location).Value = value; } #endregion #region UInt16 - private struct VolatileUInt16 { public volatile UInt16 Value; } + private struct VolatileUInt16 { public volatile ushort Value; } [CLSCompliant(false)] - public static UInt16 Read(ref UInt16 location) + public static ushort Read(ref ushort location) { - return Unsafe.As(ref location).Value; + return Unsafe.As(ref location).Value; } [CLSCompliant(false)] - public static void Write(ref UInt16 location, UInt16 value) + public static void Write(ref ushort location, ushort value) { - Unsafe.As(ref location).Value = value; + Unsafe.As(ref location).Value = value; } #endregion #region UInt32 - private struct VolatileUInt32 { public volatile UInt32 Value; } + private struct VolatileUInt32 { public volatile uint Value; } [CLSCompliant(false)] - public static UInt32 Read(ref UInt32 location) + public static uint Read(ref uint location) { - return Unsafe.As(ref location).Value; + return Unsafe.As(ref location).Value; } [CLSCompliant(false)] - public static void Write(ref UInt32 location, UInt32 value) + public static void Write(ref uint location, uint value) { - Unsafe.As(ref location).Value = value; + Unsafe.As(ref location).Value = value; } #endregion #region UInt64 [CLSCompliant(false)] - public static UInt64 Read(ref UInt64 location) + public static ulong Read(ref ulong location) { - return (UInt64)Read(ref Unsafe.As(ref location)); + return (ulong)Read(ref Unsafe.As(ref location)); } [CLSCompliant(false)] - public static void Write(ref UInt64 location, UInt64 value) + public static void Write(ref ulong location, ulong value) { - Write(ref Unsafe.As(ref location), (Int64)value); + Write(ref Unsafe.As(ref location), (long)value); } #endregion @@ -215,7 +215,7 @@ public static void Write(ref UIntPtr location, UIntPtr value) #endregion #region T - private struct VolatileObject { public volatile Object Value; } + private struct VolatileObject { public volatile object Value; } public static T Read(ref T location) where T : class { diff --git a/src/System.Private.CoreLib/src/System/TimeZoneInfo.WinRT.cs b/src/System.Private.CoreLib/src/System/TimeZoneInfo.WinRT.cs index 4701b3e13a4..f0593b89907 100644 --- a/src/System.Private.CoreLib/src/System/TimeZoneInfo.WinRT.cs +++ b/src/System.Private.CoreLib/src/System/TimeZoneInfo.WinRT.cs @@ -94,9 +94,9 @@ private static bool GetTimeZoneInfo(out TimeZoneInformation timeZoneInfo) return true; } - private TimeZoneInfo(TimeZoneInformation zone, Boolean dstDisabled) + private TimeZoneInfo(TimeZoneInformation zone, bool dstDisabled) { - if (String.IsNullOrEmpty(zone.StandardName)) + if (string.IsNullOrEmpty(zone.StandardName)) { _id = LocalId; // the ID must contain at least 1 character - initialize m_id to "Local" } @@ -134,9 +134,9 @@ private sealed class TimeZoneInformation public unsafe TimeZoneInformation(TIME_DYNAMIC_ZONE_INFORMATION dtzi) { - StandardName = new String(dtzi.StandardName); - DaylightName = new String(dtzi.DaylightName); - TimeZoneKeyName = new String(dtzi.TimeZoneKeyName); + StandardName = new string(dtzi.StandardName); + DaylightName = new string(dtzi.DaylightName); + TimeZoneKeyName = new string(dtzi.TimeZoneKeyName); Dtzi = dtzi; } } @@ -150,7 +150,7 @@ public unsafe TimeZoneInformation(TIME_DYNAMIC_ZONE_INFORMATION dtzi) // // assumes cachedData lock is taken // - private static TimeZoneInfoResult TryGetTimeZone(ref TimeZoneInformation timeZoneInformation, Boolean dstDisabled, out TimeZoneInfo value, out Exception e, CachedData cachedData) + private static TimeZoneInfoResult TryGetTimeZone(ref TimeZoneInformation timeZoneInformation, bool dstDisabled, out TimeZoneInfo value, out Exception e, CachedData cachedData) { TimeZoneInfoResult result = TimeZoneInfoResult.Success; e = null; @@ -822,10 +822,10 @@ private static unsafe bool FindMatchToCurrentTimeZone(TimeZoneInformation timeZo { string s = new String(tdzi.StandardName); - if (!String.IsNullOrEmpty(s) && + if (!string.IsNullOrEmpty(s) && EqualStandardDates(timeZoneInformation, ref tdzi) && (notSupportedDaylightSaving || EqualDaylightDates(timeZoneInformation, ref tdzi)) && - String.Compare(s, timeZoneInformation.StandardName, StringComparison.Ordinal) == 0) + string.Compare(s, timeZoneInformation.StandardName, StringComparison.Ordinal) == 0) { // found a match timeZoneInformation.TimeZoneKeyName = s; @@ -861,10 +861,10 @@ private static TimeZoneInfo GetLocalTimeZone(CachedData cachedData) return CreateCustomTimeZone(LocalId, TimeSpan.Zero, LocalId, LocalId); } - Boolean dstDisabled = timeZoneInformation.Dtzi.DynamicDaylightTimeDisabled != 0; + bool dstDisabled = timeZoneInformation.Dtzi.DynamicDaylightTimeDisabled != 0; //// check to see if we can use the key name returned from the API call - if (!String.IsNullOrEmpty(timeZoneInformation.TimeZoneKeyName) || FindMatchToCurrentTimeZone(timeZoneInformation)) + if (!string.IsNullOrEmpty(timeZoneInformation.TimeZoneKeyName) || FindMatchToCurrentTimeZone(timeZoneInformation)) { TimeZoneInfo zone = null; Exception ex; diff --git a/src/System.Private.CoreLib/src/System/ValueType.cs b/src/System.Private.CoreLib/src/System/ValueType.cs index 2c71bbcfe21..7fad0ee3111 100644 --- a/src/System.Private.CoreLib/src/System/ValueType.cs +++ b/src/System.Private.CoreLib/src/System/ValueType.cs @@ -26,7 +26,7 @@ namespace System [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public abstract class ValueType { - public override String ToString() + public override string ToString() { return this.GetType().ToString(); } diff --git a/src/System.Private.CoreLib/src/System/WeakReference.cs b/src/System.Private.CoreLib/src/System/WeakReference.cs index 4996e94ee5b..8ebe58b51ce 100644 --- a/src/System.Private.CoreLib/src/System/WeakReference.cs +++ b/src/System.Private.CoreLib/src/System/WeakReference.cs @@ -35,14 +35,14 @@ public class WeakReference : ISerializable // Creates a new WeakReference that keeps track of target. // Assumes a Short Weak Reference (ie TrackResurrection is false.) // - public WeakReference(Object target) + 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) { m_IsLongReference = trackResurrection; m_handle = GCHandle.ToIntPtr(GCHandle.Alloc(target, trackResurrection ? GCHandleType.WeakTrackResurrection : GCHandleType.Weak)); @@ -58,7 +58,7 @@ protected WeakReference(SerializationInfo info, StreamingContext context) throw new ArgumentNullException(nameof(info)); } - Object target = info.GetValue("TrackedObject", typeof(Object)); // Do not rename (binary serialization) + object target = info.GetValue("TrackedObject", typeof(object)); // Do not rename (binary serialization) bool trackResurrection = info.GetBoolean("TrackResurrection"); // Do not rename (binary serialization) m_IsLongReference = trackResurrection; @@ -105,7 +105,7 @@ public virtual bool TrackResurrection //Gets the Object stored in the handle if it's accessible. // Or sets it. // - public virtual Object Target + public virtual object Target { get { @@ -115,7 +115,7 @@ public virtual Object Target if (default(IntPtr) == h) return null; - Object o = RuntimeImports.RhHandleGet(h); + object o = RuntimeImports.RhHandleGet(h); if (o == null) { @@ -188,7 +188,7 @@ public virtual Object Target /// and gets\create a new RCW in case it is alive. /// /// - private Object TryGetComTarget() + private object TryGetComTarget() { #if ENABLE_WINRT WinRTInteropCallbacks callbacks = WinRTInterop.UnsafeCallbacks; @@ -231,7 +231,7 @@ public virtual void GetObjectData(SerializationInfo info, StreamingContext conte throw new ArgumentNullException(nameof(info)); } - info.AddValue("TrackedObject", Target, typeof(Object)); // Do not rename (binary serialization) + info.AddValue("TrackedObject", Target, typeof(object)); // Do not rename (binary serialization) info.AddValue("TrackResurrection", m_IsLongReference); // Do not rename (binary serialization) } diff --git a/src/System.Private.CoreLib/src/System/WeakReferenceOfT.cs b/src/System.Private.CoreLib/src/System/WeakReferenceOfT.cs index e36cda5082d..81040e3e4b2 100644 --- a/src/System.Private.CoreLib/src/System/WeakReferenceOfT.cs +++ b/src/System.Private.CoreLib/src/System/WeakReferenceOfT.cs @@ -134,7 +134,7 @@ private T GetTarget() /// and gets\create a new RCW in case it is alive. /// /// - private Object TryGetComTarget() + private object TryGetComTarget() { #if ENABLE_WINRT WinRTInteropCallbacks callbacks = WinRTInterop.UnsafeCallbacks; From ef047a97b7428fea47245f2dce3b27505a799b39 Mon Sep 17 00:00:00 2001 From: Jan Kotas Date: Sun, 24 Jun 2018 20:14:13 -0700 Subject: [PATCH 17/69] Minor cleanup of the framework depproj files --- src/Framework/Framework-uapaot.depproj | 1 - src/Framework/Framework.depproj | 5 ++--- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/src/Framework/Framework-uapaot.depproj b/src/Framework/Framework-uapaot.depproj index ab8e28d15e3..38b8dfec98d 100644 --- a/src/Framework/Framework-uapaot.depproj +++ b/src/Framework/Framework-uapaot.depproj @@ -21,7 +21,6 @@ - diff --git a/src/Framework/Framework.depproj b/src/Framework/Framework.depproj index 2199f01022c..77be5574867 100644 --- a/src/Framework/Framework.depproj +++ b/src/Framework/Framework.depproj @@ -31,15 +31,14 @@ - + + - - From 8b5ccfa09e65260480163f3ce4577e7c1bea8132 Mon Sep 17 00:00:00 2001 From: Jan Kotas Date: Sun, 24 Jun 2018 21:04:55 -0700 Subject: [PATCH 18/69] Update CoreFX --- dependencies.props | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/dependencies.props b/dependencies.props index 228c65c950c..0b8fd393236 100644 --- a/dependencies.props +++ b/dependencies.props @@ -2,8 +2,8 @@ 3.0.0-preview1-26624-03 1.0.0-alpha-26412-0 - 4.6.0-preview1-26624-03 - 4.7.0-preview1-26624-03 + 4.6.0-preview1-26625-01 + 4.7.0-preview1-26625-01 3.0.0-preview1-26624-03 2.1.0 1.0.1-prerelease-02104-02 From 8e3635626e4b7068d1aaf234b49b5e920721ca67 Mon Sep 17 00:00:00 2001 From: Jan Kotas Date: Sun, 24 Jun 2018 21:23:41 -0700 Subject: [PATCH 19/69] Include clrcompression.dll in the CoreRT package This makes it easier to work around #5496 --- src/BuildIntegration/Microsoft.NETCore.Native.targets | 3 ++- src/Framework/Framework.depproj | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/BuildIntegration/Microsoft.NETCore.Native.targets b/src/BuildIntegration/Microsoft.NETCore.Native.targets index bb77e066700..92b67de0272 100644 --- a/src/BuildIntegration/Microsoft.NETCore.Native.targets +++ b/src/BuildIntegration/Microsoft.NETCore.Native.targets @@ -91,7 +91,8 @@ See the LICENSE file in the project root for more information. - + + diff --git a/src/Framework/Framework.depproj b/src/Framework/Framework.depproj index 77be5574867..9b5a29af43d 100644 --- a/src/Framework/Framework.depproj +++ b/src/Framework/Framework.depproj @@ -42,8 +42,8 @@ - - + + From 635cf21aca11265ded9d78d216424bd609c052f5 Mon Sep 17 00:00:00 2001 From: Andon Andonov Date: Mon, 25 Jun 2018 19:52:16 -0700 Subject: [PATCH 20/69] Add cumulative error checking to CoreFX tests (#6014) * Add cumulative error checking * Disable regressed tests * Add issue links --- tests/CoreFX/runtest/runtest.cmd | 9 +++++++-- tests/TopN.CoreFX.Windows.issues.json | 12 ++++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/tests/CoreFX/runtest/runtest.cmd b/tests/CoreFX/runtest/runtest.cmd index a36b7b9b8be..76b81430e1f 100644 --- a/tests/CoreFX/runtest/runtest.cmd +++ b/tests/CoreFX/runtest/runtest.cmd @@ -72,7 +72,7 @@ if not defined FXCustomTestLauncher ( exit /b 1 ) - +set SAVED_ERROR_LEVEL=0 :: Iterate through unzipped CoreFX tests for /D %%i in ("%XunitTestBinBase%\*" ) do ( set TestFolderName=%%i @@ -80,10 +80,15 @@ for /D %%i in ("%XunitTestBinBase%\*" ) do ( echo %FXCustomTestLauncher% !TestFolderName! !TestFileName! call %FXCustomTestLauncher% !TestFolderName! !TestFileName! + set TestExitCode=!errorlevel! + if !TestExitCode! neq 0 ( + echo Test !TestFileName! failed with !TestExitCode! + set SAVED_ERROR_LEVEL=!TestExitCode! + ) ) -exit /b 0 +exit /b !SAVED_ERROR_LEVEL! :Usage echo. diff --git a/tests/TopN.CoreFX.Windows.issues.json b/tests/TopN.CoreFX.Windows.issues.json index c1511d85bff..87b9bd16205 100644 --- a/tests/TopN.CoreFX.Windows.issues.json +++ b/tests/TopN.CoreFX.Windows.issues.json @@ -775,6 +775,18 @@ "namespaces": null, "classes": null, "methods": [ + { + "name": "System.Tests.TupleTests.CompareTo", + "reason": "https://github.com/dotnet/corert/issues/6015" + }, + { + "name": "System.Tests.TupleTests.Equals_GetHashCode", + "reason": "https://github.com/dotnet/corert/issues/6015" + }, + { + "name": "System.Tests.ArrayTests.Sort_Array_Array_NonGeneric", + "reason": "https://github.com/dotnet/corert/issues/6016" + }, { "name": "System.Reflection.Tests.MethodInfoTests.TestEquality2", "reason": "Xunit.Sdk.EqualException" From 5ddf79df02b8be670dc977b5af41b93e65890ad0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michal=20Strehovsk=C3=BD?= Date: Tue, 26 Jun 2018 16:17:53 +0200 Subject: [PATCH 21/69] Fix bogus assert in ArraySortHelper (#6018) Fixes #6016. Resolves #6015. --- .../System/Collections/Generic/ArraySortHelper.cs | 6 +++--- tests/TopN.CoreFX.Windows.issues.json | 12 ------------ 2 files changed, 3 insertions(+), 15 deletions(-) diff --git a/src/System.Private.CoreLib/shared/System/Collections/Generic/ArraySortHelper.cs b/src/System.Private.CoreLib/shared/System/Collections/Generic/ArraySortHelper.cs index b717bd76219..03b9865044f 100644 --- a/src/System.Private.CoreLib/shared/System/Collections/Generic/ArraySortHelper.cs +++ b/src/System.Private.CoreLib/shared/System/Collections/Generic/ArraySortHelper.cs @@ -654,10 +654,10 @@ public void Sort(TKey[] keys, TValue[] values, int index, int length, IComparer< private static void SwapIfGreaterWithItems(TKey[] keys, TValue[] values, IComparer comparer, int a, int b) { Debug.Assert(keys != null); - Debug.Assert(values != null && values.Length >= keys.Length); + Debug.Assert(values != null); Debug.Assert(comparer != null); - Debug.Assert(0 <= a && a < keys.Length); - Debug.Assert(0 <= b && b < keys.Length); + Debug.Assert(0 <= a && a < keys.Length && a < values.Length); + Debug.Assert(0 <= b && b < keys.Length && b < values.Length); if (a != b) { diff --git a/tests/TopN.CoreFX.Windows.issues.json b/tests/TopN.CoreFX.Windows.issues.json index 87b9bd16205..c1511d85bff 100644 --- a/tests/TopN.CoreFX.Windows.issues.json +++ b/tests/TopN.CoreFX.Windows.issues.json @@ -775,18 +775,6 @@ "namespaces": null, "classes": null, "methods": [ - { - "name": "System.Tests.TupleTests.CompareTo", - "reason": "https://github.com/dotnet/corert/issues/6015" - }, - { - "name": "System.Tests.TupleTests.Equals_GetHashCode", - "reason": "https://github.com/dotnet/corert/issues/6015" - }, - { - "name": "System.Tests.ArrayTests.Sort_Array_Array_NonGeneric", - "reason": "https://github.com/dotnet/corert/issues/6016" - }, { "name": "System.Reflection.Tests.MethodInfoTests.TestEquality2", "reason": "Xunit.Sdk.EqualException" From 5036cc85f0d0706023dfde16810efd24166c2132 Mon Sep 17 00:00:00 2001 From: Stephen Toub Date: Mon, 25 Jun 2018 19:54:41 -0400 Subject: [PATCH 22/69] Simplify built-in types across corefx (dotnet/corefx#30656) Signed-off-by: dotnet-bot --- .../Unix/System.Globalization.Native/Interop.Locale.cs | 2 +- .../shared/System/Globalization/CalendarData.Unix.cs | 2 +- .../shared/System/Globalization/CompareInfo.Unix.cs | 2 +- .../shared/System/Globalization/CultureData.Unix.cs | 10 +++++----- .../System/Globalization/JapaneseCalendar.WinRT.cs | 2 +- 5 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Locale.cs b/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Locale.cs index 9ef41dedf2e..b6f5fbec1ca 100644 --- a/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Locale.cs +++ b/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Locale.cs @@ -35,6 +35,6 @@ internal static partial class Globalization internal static extern unsafe bool GetLocaleInfoGroupingSizes(string localeName, uint localeGroupingData, ref int primaryGroupSize, ref int secondaryGroupSize); [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_GetLocales")] - internal static extern unsafe int GetLocales([Out] Char[] value, int valueLength); + internal static extern unsafe int GetLocales([Out] char[] value, int valueLength); } } diff --git a/src/System.Private.CoreLib/shared/System/Globalization/CalendarData.Unix.cs b/src/System.Private.CoreLib/shared/System/Globalization/CalendarData.Unix.cs index 1d37926b421..61e06914c07 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/CalendarData.Unix.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/CalendarData.Unix.cs @@ -32,7 +32,7 @@ internal enum CalendarDataType internal partial class CalendarData { - private bool LoadCalendarDataFromSystem(String localeName, CalendarId calendarId) + private bool LoadCalendarDataFromSystem(string localeName, CalendarId calendarId) { bool result = true; result &= GetCalendarInfo(localeName, calendarId, CalendarDataType.NativeName, out this.sNativeName); diff --git a/src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.Unix.cs b/src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.Unix.cs index 2c4684342e4..90e9eba0bbe 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.Unix.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.Unix.cs @@ -722,7 +722,7 @@ private unsafe bool EndsWithOrdinalHelper(ReadOnlySpan source, ReadOnlySpa } } - private unsafe SortKey CreateSortKey(String source, CompareOptions options) + private unsafe SortKey CreateSortKey(string source, CompareOptions options) { Debug.Assert(!_invariantMode); diff --git a/src/System.Private.CoreLib/shared/System/Globalization/CultureData.Unix.cs b/src/System.Private.CoreLib/shared/System/Globalization/CultureData.Unix.cs index 933087d3b45..4b21f2e7d3d 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/CultureData.Unix.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/CultureData.Unix.cs @@ -227,19 +227,19 @@ private int GetFirstDayOfWeek() return this.GetLocaleInfo(LocaleNumberData.FirstDayOfWeek); } - private String[] GetTimeFormats() + private string[] GetTimeFormats() { string format = GetTimeFormatString(false); return new string[] { format }; } - private String[] GetShortTimeFormats() + private string[] GetShortTimeFormats() { string format = GetTimeFormatString(true); return new string[] { format }; } - private static CultureData GetCultureDataFromRegionName(String regionName) + private static CultureData GetCultureDataFromRegionName(string regionName) { // no support to lookup by region name, other than the hard-coded list in CultureData return null; @@ -371,7 +371,7 @@ private static CultureInfo[] EnumCultures(CultureTypes types) return Array.Empty(); } - Char [] chars = new Char[bufferLength]; + char [] chars = new char[bufferLength]; bufferLength = Interop.Globalization.GetLocales(chars, bufferLength); if (bufferLength <= 0) @@ -394,7 +394,7 @@ private static CultureInfo[] EnumCultures(CultureTypes types) int length = (int) chars[index++]; if (index + length <= bufferLength) { - CultureInfo ci = CultureInfo.GetCultureInfo(new String(chars, index, length)); + CultureInfo ci = CultureInfo.GetCultureInfo(new string(chars, index, length)); if ((enumNeutrals && ci.IsNeutralCulture) || (enumSpecificss && !ci.IsNeutralCulture)) { list.Add(ci); diff --git a/src/System.Private.CoreLib/shared/System/Globalization/JapaneseCalendar.WinRT.cs b/src/System.Private.CoreLib/shared/System/Globalization/JapaneseCalendar.WinRT.cs index 6a9df972009..818cb5b427d 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/JapaneseCalendar.WinRT.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/JapaneseCalendar.WinRT.cs @@ -46,7 +46,7 @@ private static EraInfo[] GetJapaneseEras() // PAL Layer ends here - private static string[] JapaneseErasEnglishNames = new String[] { "M", "T", "S", "H" }; + private static string[] JapaneseErasEnglishNames = new string[] { "M", "T", "S", "H" }; private static string GetJapaneseEnglishEraName(int era) { From 8cf35760e53826be484cd3d963e692e71b454ee3 Mon Sep 17 00:00:00 2001 From: Marek Safar Date: Wed, 27 Jun 2018 15:53:24 +0200 Subject: [PATCH 23/69] Removes duplicate attributes (dotnet/coreclr#18668) Signed-off-by: dotnet-bot --- src/System.Private.CoreLib/shared/System/ReadOnlySpan.Fast.cs | 2 -- src/System.Private.CoreLib/shared/System/Span.Fast.cs | 2 -- 2 files changed, 4 deletions(-) diff --git a/src/System.Private.CoreLib/shared/System/ReadOnlySpan.Fast.cs b/src/System.Private.CoreLib/shared/System/ReadOnlySpan.Fast.cs index cabda7a022c..4fb039a0fc8 100644 --- a/src/System.Private.CoreLib/shared/System/ReadOnlySpan.Fast.cs +++ b/src/System.Private.CoreLib/shared/System/ReadOnlySpan.Fast.cs @@ -23,8 +23,6 @@ namespace System /// ReadOnlySpan represents a contiguous region of arbitrary memory. Unlike arrays, it can point to either managed /// or native memory, or to memory allocated on the stack. It is type- and memory-safe. /// - [DebuggerTypeProxy(typeof(SpanDebugView<>))] - [DebuggerDisplay("{ToString(),raw}")] [NonVersionable] public readonly ref partial struct ReadOnlySpan { diff --git a/src/System.Private.CoreLib/shared/System/Span.Fast.cs b/src/System.Private.CoreLib/shared/System/Span.Fast.cs index 40b461eeff5..b3cfc8daff7 100644 --- a/src/System.Private.CoreLib/shared/System/Span.Fast.cs +++ b/src/System.Private.CoreLib/shared/System/Span.Fast.cs @@ -23,8 +23,6 @@ namespace System /// Span represents a contiguous region of arbitrary memory. Unlike arrays, it can point to either managed /// or native memory, or to memory allocated on the stack. It is type- and memory-safe. /// - [DebuggerTypeProxy(typeof(SpanDebugView<>))] - [DebuggerDisplay("{ToString(),raw}")] [NonVersionable] public readonly ref partial struct Span { From 8a67e171ceab76a4d23131e51bc13c84cb2479d8 Mon Sep 17 00:00:00 2001 From: Fadi Hanna Date: Wed, 27 Jun 2018 10:26:31 -0700 Subject: [PATCH 24/69] Changing the interface method resolution logic used in building the sealed vtable and the interface dispatch map to work with type definitions instead of instantiated types, to correctly handle the cases where we get generic interface collapsing, and when the implementing method ends up in the sealed vtable (This was causing the interface resolution logic at runtime to fail). This also fixes the cases of dynamic types, since we use fully canonical instantiations as templates, and these canonical instantiations can suffer from the same generic collapsing problem. [tfs-changeset: 1705787] --- .../InterfaceDispatchMapNode.cs | 29 ++++++++++++++----- .../DependencyAnalysis/SealedVTableNode.cs | 25 ++++++++++++---- 2 files changed, 40 insertions(+), 14 deletions(-) diff --git a/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/InterfaceDispatchMapNode.cs b/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/InterfaceDispatchMapNode.cs index b631efaff13..57c4299af35 100644 --- a/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/InterfaceDispatchMapNode.cs +++ b/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/InterfaceDispatchMapNode.cs @@ -76,9 +76,9 @@ public static bool MightHaveInterfaceDispatchMap(TypeDesc type, NodeFactory fact if (!type.IsArray && !type.IsDefType) return false; - DefType defType = type.GetClosestDefType(); + TypeDesc declType = type.GetClosestDefType().GetTypeDefinition(); - foreach (DefType interfaceType in defType.RuntimeInterfaces) + foreach (DefType interfaceType in declType.RuntimeInterfaces) { IEnumerable slots; @@ -96,7 +96,7 @@ public static bool MightHaveInterfaceDispatchMap(TypeDesc type, NodeFactory fact if (declMethod.Signature.IsStatic) continue; - var implMethod = defType.ResolveInterfaceMethodToVirtualMethodOnType(declMethod); + var implMethod = declType.ResolveInterfaceMethodToVirtualMethodOnType(declMethod); if (implMethod != null) return true; } @@ -109,10 +109,15 @@ void EmitDispatchMap(ref ObjectDataBuilder builder, NodeFactory factory) { var entryCountReservation = builder.ReserveInt(); int entryCount = 0; - - for (int interfaceIndex = 0; interfaceIndex < _type.RuntimeInterfaces.Length; interfaceIndex++) + + TypeDesc declType = _type.GetClosestDefType(); + + // Catch any runtime interface collapsing. We shouldn't have any + Debug.Assert(declType.RuntimeInterfaces.Length == declType.GetTypeDefinition().RuntimeInterfaces.Length); + + for (int interfaceIndex = 0; interfaceIndex < declType.RuntimeInterfaces.Length; interfaceIndex++) { - var interfaceType = _type.RuntimeInterfaces[interfaceIndex]; + var interfaceType = declType.GetTypeDefinition().RuntimeInterfaces[interfaceIndex]; Debug.Assert(interfaceType.IsInterface); IReadOnlyList virtualSlots = factory.VTable(interfaceType).Slots; @@ -120,15 +125,23 @@ void EmitDispatchMap(ref ObjectDataBuilder builder, NodeFactory factory) for (int interfaceMethodSlot = 0; interfaceMethodSlot < virtualSlots.Count; interfaceMethodSlot++) { MethodDesc declMethod = virtualSlots[interfaceMethodSlot]; - var implMethod = _type.GetClosestDefType().ResolveInterfaceMethodToVirtualMethodOnType(declMethod); + var implMethod = declType.GetTypeDefinition().ResolveInterfaceMethodToVirtualMethodOnType(declMethod); // Interface methods first implemented by a base type in the hierarchy will return null for the implMethod (runtime interface // dispatch will walk the inheritance chain). if (implMethod != null) { + TypeDesc implType = declType; + while (!implType.HasSameTypeDefinition(implMethod.OwningType)) + implType = implType.BaseType; + + MethodDesc targetMethod = implMethod; + if (!implType.IsTypeDefinition) + targetMethod = factory.TypeSystemContext.GetMethodForInstantiatedType(implMethod.GetTypicalMethodDefinition(), (InstantiatedType)implType); + builder.EmitShort(checked((short)interfaceIndex)); builder.EmitShort(checked((short)(interfaceMethodSlot + (interfaceType.HasGenericDictionarySlot() ? 1 : 0)))); - builder.EmitShort(checked((short)VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, implMethod, _type.GetClosestDefType()))); + builder.EmitShort(checked((short)VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, targetMethod, declType))); entryCount++; } } diff --git a/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/SealedVTableNode.cs b/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/SealedVTableNode.cs index ec1dca98798..c2a79224699 100644 --- a/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/SealedVTableNode.cs +++ b/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/SealedVTableNode.cs @@ -98,27 +98,40 @@ public bool BuildSealedVTableSlots(NodeFactory factory, bool relocsOnly) for (int i = 0; i < virtualSlots.Count; i++) { - MethodDesc implMethod = _type.GetClosestDefType().FindVirtualFunctionTargetMethodOnObjectType(virtualSlots[i]); + MethodDesc implMethod = declType.FindVirtualFunctionTargetMethodOnObjectType(virtualSlots[i]); if (implMethod.CanMethodBeInSealedVTable()) _sealedVTableEntries.Add(implMethod); } - for (int interfaceIndex = 0; interfaceIndex < _type.RuntimeInterfaces.Length; interfaceIndex++) + // Catch any runtime interface collapsing. We shouldn't have any + Debug.Assert(declType.RuntimeInterfaces.Length == declType.GetTypeDefinition().RuntimeInterfaces.Length); + + for (int interfaceIndex = 0; interfaceIndex < declType.RuntimeInterfaces.Length; interfaceIndex++) { - var interfaceType = _type.RuntimeInterfaces[interfaceIndex]; + var interfaceType = declType.GetTypeDefinition().RuntimeInterfaces[interfaceIndex]; virtualSlots = factory.VTable(interfaceType).Slots; for (int interfaceMethodSlot = 0; interfaceMethodSlot < virtualSlots.Count; interfaceMethodSlot++) { MethodDesc declMethod = virtualSlots[interfaceMethodSlot]; - var implMethod = _type.GetClosestDefType().ResolveInterfaceMethodToVirtualMethodOnType(declMethod); + var implMethod = declType.GetTypeDefinition().ResolveInterfaceMethodToVirtualMethodOnType(declMethod); // Interface methods first implemented by a base type in the hierarchy will return null for the implMethod (runtime interface // dispatch will walk the inheritance chain). - if (implMethod != null && implMethod.CanMethodBeInSealedVTable() && implMethod.OwningType != _type) - _sealedVTableEntries.Add(implMethod); + if (implMethod != null && implMethod.CanMethodBeInSealedVTable() && !implMethod.OwningType.HasSameTypeDefinition(declType)) + { + TypeDesc implType = declType; + while (!implType.HasSameTypeDefinition(implMethod.OwningType)) + implType = implType.BaseType; + + MethodDesc targetMethod = implMethod; + if (!implType.IsTypeDefinition) + targetMethod = factory.TypeSystemContext.GetMethodForInstantiatedType(implMethod.GetTypicalMethodDefinition(), (InstantiatedType)implType); + + _sealedVTableEntries.Add(targetMethod); + } } } From cd717b61e0b46a112b4896695442da84c6b8deea Mon Sep 17 00:00:00 2001 From: Fei Peng Date: Tue, 26 Jun 2018 16:20:54 -0700 Subject: [PATCH 25/69] Fix Aes and Ssse3.Shuffle intrinsic APIs Signed-off-by: dotnet-bot --- .../X86/Aes.PlatformNotSupported.cs | 32 +------------------ .../System/Runtime/Intrinsics/X86/Aes.cs | 32 +------------------ .../X86/Ssse3.PlatformNotSupported.cs | 6 ++++ .../System/Runtime/Intrinsics/X86/Ssse3.cs | 6 ++++ 4 files changed, 14 insertions(+), 62 deletions(-) diff --git a/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Aes.PlatformNotSupported.cs b/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Aes.PlatformNotSupported.cs index 5df8f266dfa..c31da3964d8 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Aes.PlatformNotSupported.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Aes.PlatformNotSupported.cs @@ -15,44 +15,24 @@ public static class Aes { public static bool IsSupported { get { return false; } } - /// - /// __m128i _mm_aesdec_si128 (__m128i a, __m128i RoundKey) - /// AESDEC xmm, xmm/m128 - /// - public static Vector128 Decrypt(Vector128 value, Vector128 roundKey) { throw new PlatformNotSupportedException(); } /// /// __m128i _mm_aesdec_si128 (__m128i a, __m128i RoundKey) /// AESDEC xmm, xmm/m128 /// public static Vector128 Decrypt(Vector128 value, Vector128 roundKey) { throw new PlatformNotSupportedException(); } - /// - /// __m128i _mm_aesdeclast_si128 (__m128i a, __m128i RoundKey) - /// AESDECLAST xmm, xmm/m128 - /// - public static Vector128 DecryptLast(Vector128 value, Vector128 roundKey) { throw new PlatformNotSupportedException(); } /// /// __m128i _mm_aesdeclast_si128 (__m128i a, __m128i RoundKey) /// AESDECLAST xmm, xmm/m128 /// public static Vector128 DecryptLast(Vector128 value, Vector128 roundKey) { throw new PlatformNotSupportedException(); } - /// - /// __m128i _mm_aesenc_si128 (__m128i a, __m128i RoundKey) - /// AESENC xmm, xmm/m128 - /// - public static Vector128 Encrypt(Vector128 value, Vector128 roundKey) { throw new PlatformNotSupportedException(); } /// /// __m128i _mm_aesenc_si128 (__m128i a, __m128i RoundKey) /// AESENC xmm, xmm/m128 /// public static Vector128 Encrypt(Vector128 value, Vector128 roundKey) { throw new PlatformNotSupportedException(); } - /// - /// __m128i _mm_aesenclast_si128 (__m128i a, __m128i RoundKey) - /// AESENCLAST xmm, xmm/m128 - /// - public static Vector128 EncryptLast(Vector128 value, Vector128 roundKey) { throw new PlatformNotSupportedException(); } /// /// __m128i _mm_aesenclast_si128 (__m128i a, __m128i RoundKey) /// AESENCLAST xmm, xmm/m128 @@ -63,18 +43,8 @@ public static class Aes /// __m128i _mm_aesimc_si128 (__m128i a) /// AESIMC xmm, xmm/m128 /// - public static Vector128 InvisibleMixColumn(Vector128 value) { throw new PlatformNotSupportedException(); } - /// - /// __m128i _mm_aesimc_si128 (__m128i a) - /// AESIMC xmm, xmm/m128 - /// - public static Vector128 InvisibleMixColumn(Vector128 value) { throw new PlatformNotSupportedException(); } + public static Vector128 InverseMixColumns(Vector128 value) { throw new PlatformNotSupportedException(); } - /// - /// __m128i _mm_aeskeygenassist_si128 (__m128i a, const int imm8) - /// AESKEYGENASSIST xmm, xmm/m128, imm8 - /// - public static Vector128 KeygenAssist(Vector128 value, byte control) { throw new PlatformNotSupportedException(); } /// /// __m128i _mm_aeskeygenassist_si128 (__m128i a, const int imm8) /// AESKEYGENASSIST xmm, xmm/m128, imm8 diff --git a/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Aes.cs b/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Aes.cs index 349919a21ca..75db4b1979e 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Aes.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Aes.cs @@ -15,44 +15,24 @@ public static class Aes { public static bool IsSupported { get => IsSupported; } - /// - /// __m128i _mm_aesdec_si128 (__m128i a, __m128i RoundKey) - /// AESDEC xmm, xmm/m128 - /// - public static Vector128 Decrypt(Vector128 value, Vector128 roundKey) => Decrypt(value, roundKey); /// /// __m128i _mm_aesdec_si128 (__m128i a, __m128i RoundKey) /// AESDEC xmm, xmm/m128 /// public static Vector128 Decrypt(Vector128 value, Vector128 roundKey) => Decrypt(value, roundKey); - /// - /// __m128i _mm_aesdeclast_si128 (__m128i a, __m128i RoundKey) - /// AESDECLAST xmm, xmm/m128 - /// - public static Vector128 DecryptLast(Vector128 value, Vector128 roundKey) => DecryptLast(value, roundKey); /// /// __m128i _mm_aesdeclast_si128 (__m128i a, __m128i RoundKey) /// AESDECLAST xmm, xmm/m128 /// public static Vector128 DecryptLast(Vector128 value, Vector128 roundKey) => DecryptLast(value, roundKey); - /// - /// __m128i _mm_aesenc_si128 (__m128i a, __m128i RoundKey) - /// AESENC xmm, xmm/m128 - /// - public static Vector128 Encrypt(Vector128 value, Vector128 roundKey) => Encrypt(value, roundKey); /// /// __m128i _mm_aesenc_si128 (__m128i a, __m128i RoundKey) /// AESENC xmm, xmm/m128 /// public static Vector128 Encrypt(Vector128 value, Vector128 roundKey) => Encrypt(value, roundKey); - /// - /// __m128i _mm_aesenclast_si128 (__m128i a, __m128i RoundKey) - /// AESENCLAST xmm, xmm/m128 - /// - public static Vector128 EncryptLast(Vector128 value, Vector128 roundKey) => EncryptLast(value, roundKey); /// /// __m128i _mm_aesenclast_si128 (__m128i a, __m128i RoundKey) /// AESENCLAST xmm, xmm/m128 @@ -63,18 +43,8 @@ public static class Aes /// __m128i _mm_aesimc_si128 (__m128i a) /// AESIMC xmm, xmm/m128 /// - public static Vector128 InvisibleMixColumn(Vector128 value) => InvisibleMixColumn(value); - /// - /// __m128i _mm_aesimc_si128 (__m128i a) - /// AESIMC xmm, xmm/m128 - /// - public static Vector128 InvisibleMixColumn(Vector128 value) => InvisibleMixColumn(value); + public static Vector128 InverseMixColumns(Vector128 value) => InverseMixColumns(value); - /// - /// __m128i _mm_aeskeygenassist_si128 (__m128i a, const int imm8) - /// AESKEYGENASSIST xmm, xmm/m128, imm8 - /// - public static Vector128 KeygenAssist(Vector128 value, byte control) => KeygenAssist(value, control); /// /// __m128i _mm_aeskeygenassist_si128 (__m128i a, const int imm8) /// AESKEYGENASSIST xmm, xmm/m128, imm8 diff --git a/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Ssse3.PlatformNotSupported.cs b/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Ssse3.PlatformNotSupported.cs index 20e9bbb8b75..7a930c499a6 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Ssse3.PlatformNotSupported.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Ssse3.PlatformNotSupported.cs @@ -89,6 +89,12 @@ public static class Ssse3 /// public static Vector128 Shuffle(Vector128 value, Vector128 mask) { throw new PlatformNotSupportedException(); } + /// + /// __m128i _mm_shuffle_epi8 (__m128i a, __m128i b) + /// PSHUFB xmm, xmm/m128 + /// + public static Vector128 Shuffle(Vector128 value, Vector128 mask) { throw new PlatformNotSupportedException(); } + /// /// __m128i _mm_sign_epi8 (__m128i a, __m128i b) /// PSIGNB xmm, xmm/m128 diff --git a/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Ssse3.cs b/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Ssse3.cs index 0403a0a4e27..fc32c29496a 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Ssse3.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Ssse3.cs @@ -89,6 +89,12 @@ public static class Ssse3 /// public static Vector128 Shuffle(Vector128 value, Vector128 mask) => Shuffle(value, mask); + /// + /// __m128i _mm_shuffle_epi8 (__m128i a, __m128i b) + /// PSHUFB xmm, xmm/m128 + /// + public static Vector128 Shuffle(Vector128 value, Vector128 mask) => Shuffle(value, mask); + /// /// __m128i _mm_sign_epi8 (__m128i a, __m128i b) /// PSIGNB xmm, xmm/m128 From be76b03fbb245eedf60f5ab02caa71ddad5f1713 Mon Sep 17 00:00:00 2001 From: Phil Garcia Date: Mon, 25 Jun 2018 22:27:59 -0700 Subject: [PATCH 26/69] Changed internal value to readonly to all the primitive types Signed-off-by: dotnet-bot --- src/System.Private.CoreLib/shared/System/Boolean.cs | 4 ++-- src/System.Private.CoreLib/shared/System/Byte.cs | 4 ++-- src/System.Private.CoreLib/shared/System/Char.cs | 4 ++-- src/System.Private.CoreLib/shared/System/Double.cs | 4 ++-- src/System.Private.CoreLib/shared/System/Int16.cs | 4 ++-- src/System.Private.CoreLib/shared/System/Int32.cs | 4 ++-- src/System.Private.CoreLib/shared/System/Int64.cs | 4 ++-- src/System.Private.CoreLib/shared/System/IntPtr.cs | 4 ++-- src/System.Private.CoreLib/shared/System/SByte.cs | 4 ++-- src/System.Private.CoreLib/shared/System/Single.cs | 4 ++-- src/System.Private.CoreLib/shared/System/UInt16.cs | 4 ++-- src/System.Private.CoreLib/shared/System/UInt32.cs | 4 ++-- src/System.Private.CoreLib/shared/System/UInt64.cs | 4 ++-- src/System.Private.CoreLib/shared/System/UIntPtr.cs | 4 ++-- 14 files changed, 28 insertions(+), 28 deletions(-) diff --git a/src/System.Private.CoreLib/shared/System/Boolean.cs b/src/System.Private.CoreLib/shared/System/Boolean.cs index dbc7bd75ee5..7ec9227f1b5 100644 --- a/src/System.Private.CoreLib/shared/System/Boolean.cs +++ b/src/System.Private.CoreLib/shared/System/Boolean.cs @@ -19,12 +19,12 @@ namespace System { [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] - public struct Boolean : IComparable, IConvertible, IComparable, IEquatable + public readonly struct Boolean : IComparable, IConvertible, IComparable, IEquatable { // // Member Variables // - private bool m_value; // Do not rename (binary serialization) + private readonly bool m_value; // Do not rename (binary serialization) // The true value. // diff --git a/src/System.Private.CoreLib/shared/System/Byte.cs b/src/System.Private.CoreLib/shared/System/Byte.cs index 64512b0feed..5e8580642b0 100644 --- a/src/System.Private.CoreLib/shared/System/Byte.cs +++ b/src/System.Private.CoreLib/shared/System/Byte.cs @@ -12,9 +12,9 @@ namespace System [Serializable] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] - public struct Byte : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable + public readonly struct Byte : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable { - private byte m_value; // Do not rename (binary serialization) + private readonly byte m_value; // Do not rename (binary serialization) // The maximum value that a Byte may represent: 255. public const byte MaxValue = (byte)0xFF; diff --git a/src/System.Private.CoreLib/shared/System/Char.cs b/src/System.Private.CoreLib/shared/System/Char.cs index a3d29634020..8c743369b1e 100644 --- a/src/System.Private.CoreLib/shared/System/Char.cs +++ b/src/System.Private.CoreLib/shared/System/Char.cs @@ -21,12 +21,12 @@ namespace System [Serializable] [StructLayout(LayoutKind.Sequential)] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] - public struct Char : IComparable, IComparable, IEquatable, IConvertible + public readonly struct Char : IComparable, IComparable, IEquatable, IConvertible { // // Member Variables // - private char m_value; // Do not rename (binary serialization) + private readonly char m_value; // Do not rename (binary serialization) // // Public Constants diff --git a/src/System.Private.CoreLib/shared/System/Double.cs b/src/System.Private.CoreLib/shared/System/Double.cs index 79021f22b88..308dda5fadf 100644 --- a/src/System.Private.CoreLib/shared/System/Double.cs +++ b/src/System.Private.CoreLib/shared/System/Double.cs @@ -26,7 +26,7 @@ namespace System [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public struct Double : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable { - private double m_value; // Do not rename (binary serialization) + private readonly double m_value; // Do not rename (binary serialization) // // Public Constants @@ -226,7 +226,7 @@ public bool Equals(double obj) [MethodImpl(MethodImplOptions.AggressiveInlining)] // 64-bit constants make the IL unusually large that makes the inliner to reject the method public override int GetHashCode() { - var bits = Unsafe.As(ref m_value); + var bits = BitConverter.DoubleToInt64Bits(m_value); // Optimized check for IsNan() || IsZero() if (((bits - 1) & 0x7FFFFFFFFFFFFFFF) >= 0x7FF0000000000000) diff --git a/src/System.Private.CoreLib/shared/System/Int16.cs b/src/System.Private.CoreLib/shared/System/Int16.cs index 2993337a74e..49732997639 100644 --- a/src/System.Private.CoreLib/shared/System/Int16.cs +++ b/src/System.Private.CoreLib/shared/System/Int16.cs @@ -12,9 +12,9 @@ namespace System [Serializable] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] - public struct Int16 : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable + public readonly struct Int16 : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable { - private short m_value; // Do not rename (binary serialization) + private readonly short m_value; // Do not rename (binary serialization) public const short MaxValue = (short)0x7FFF; public const short MinValue = unchecked((short)0x8000); diff --git a/src/System.Private.CoreLib/shared/System/Int32.cs b/src/System.Private.CoreLib/shared/System/Int32.cs index 5c40812c0aa..1d0aefe73cb 100644 --- a/src/System.Private.CoreLib/shared/System/Int32.cs +++ b/src/System.Private.CoreLib/shared/System/Int32.cs @@ -12,9 +12,9 @@ namespace System [Serializable] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] - public struct Int32 : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable + public readonly struct Int32 : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable { - private int m_value; // Do not rename (binary serialization) + private readonly int m_value; // Do not rename (binary serialization) public const int MaxValue = 0x7fffffff; public const int MinValue = unchecked((int)0x80000000); diff --git a/src/System.Private.CoreLib/shared/System/Int64.cs b/src/System.Private.CoreLib/shared/System/Int64.cs index 29198781d7a..62c9ffd4fe6 100644 --- a/src/System.Private.CoreLib/shared/System/Int64.cs +++ b/src/System.Private.CoreLib/shared/System/Int64.cs @@ -12,9 +12,9 @@ namespace System [Serializable] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] - public struct Int64 : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable + public readonly struct Int64 : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable { - private long m_value; // Do not rename (binary serialization) + private readonly long m_value; // Do not rename (binary serialization) public const long MaxValue = 0x7fffffffffffffffL; public const long MinValue = unchecked((long)0x8000000000000000L); diff --git a/src/System.Private.CoreLib/shared/System/IntPtr.cs b/src/System.Private.CoreLib/shared/System/IntPtr.cs index c5419a96e02..f79334a96be 100644 --- a/src/System.Private.CoreLib/shared/System/IntPtr.cs +++ b/src/System.Private.CoreLib/shared/System/IntPtr.cs @@ -17,13 +17,13 @@ namespace System { [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] - public struct IntPtr : IEquatable, ISerializable + public readonly struct IntPtr : IEquatable, ISerializable { // WARNING: We allow diagnostic tools to directly inspect this member (_value). // See https://github.com/dotnet/corert/blob/master/Documentation/design-docs/diagnostics/diagnostics-tools-contract.md for more details. // Please do not change the type, the name, or the semantic usage of this member without understanding the implication for tools. // Get in touch with the diagnostics team if you have questions. - private unsafe void* _value; // Do not rename (binary serialization) + private readonly unsafe void* _value; // Do not rename (binary serialization) [Intrinsic] public static readonly IntPtr Zero; diff --git a/src/System.Private.CoreLib/shared/System/SByte.cs b/src/System.Private.CoreLib/shared/System/SByte.cs index e3c6d170a1d..e347e3b3230 100644 --- a/src/System.Private.CoreLib/shared/System/SByte.cs +++ b/src/System.Private.CoreLib/shared/System/SByte.cs @@ -12,9 +12,9 @@ namespace System [Serializable] [CLSCompliant(false)] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] - public struct SByte : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable + public readonly struct SByte : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable { - private sbyte m_value; // Do not rename (binary serialization) + private readonly sbyte m_value; // Do not rename (binary serialization) // The maximum value that a Byte may represent: 127. public const sbyte MaxValue = (sbyte)0x7F; diff --git a/src/System.Private.CoreLib/shared/System/Single.cs b/src/System.Private.CoreLib/shared/System/Single.cs index 1a778c957c0..d62ff9ceea6 100644 --- a/src/System.Private.CoreLib/shared/System/Single.cs +++ b/src/System.Private.CoreLib/shared/System/Single.cs @@ -25,7 +25,7 @@ namespace System [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public struct Single : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable { - private float m_value; // Do not rename (binary serialization) + private readonly float m_value; // Do not rename (binary serialization) // // Public constants @@ -217,7 +217,7 @@ public bool Equals(float obj) public override int GetHashCode() { - var bits = Unsafe.As(ref m_value); + var bits = BitConverter.SingleToInt32Bits(m_value); // Optimized check for IsNan() || IsZero() if (((bits - 1) & 0x7FFFFFFF) >= 0x7F800000) diff --git a/src/System.Private.CoreLib/shared/System/UInt16.cs b/src/System.Private.CoreLib/shared/System/UInt16.cs index cd09894c626..f9ef1f6a624 100644 --- a/src/System.Private.CoreLib/shared/System/UInt16.cs +++ b/src/System.Private.CoreLib/shared/System/UInt16.cs @@ -13,9 +13,9 @@ namespace System [CLSCompliant(false)] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] - public struct UInt16 : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable + public readonly struct UInt16 : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable { - private ushort m_value; // Do not rename (binary serialization) + private readonly ushort m_value; // Do not rename (binary serialization) public const ushort MaxValue = (ushort)0xFFFF; public const ushort MinValue = 0; diff --git a/src/System.Private.CoreLib/shared/System/UInt32.cs b/src/System.Private.CoreLib/shared/System/UInt32.cs index d72a0a19562..5ed193e9562 100644 --- a/src/System.Private.CoreLib/shared/System/UInt32.cs +++ b/src/System.Private.CoreLib/shared/System/UInt32.cs @@ -13,9 +13,9 @@ namespace System [CLSCompliant(false)] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] - public struct UInt32 : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable + public readonly struct UInt32 : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable { - private uint m_value; // Do not rename (binary serialization) + private readonly uint m_value; // Do not rename (binary serialization) public const uint MaxValue = (uint)0xffffffff; public const uint MinValue = 0U; diff --git a/src/System.Private.CoreLib/shared/System/UInt64.cs b/src/System.Private.CoreLib/shared/System/UInt64.cs index 3b1010a51f4..6abd76da21f 100644 --- a/src/System.Private.CoreLib/shared/System/UInt64.cs +++ b/src/System.Private.CoreLib/shared/System/UInt64.cs @@ -13,9 +13,9 @@ namespace System [CLSCompliant(false)] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] - public struct UInt64 : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable + public readonly struct UInt64 : IComparable, IConvertible, IFormattable, IComparable, IEquatable, ISpanFormattable { - private ulong m_value; // Do not rename (binary serialization) + private readonly ulong m_value; // Do not rename (binary serialization) public const ulong MaxValue = (ulong)0xffffffffffffffffL; public const ulong MinValue = 0x0; diff --git a/src/System.Private.CoreLib/shared/System/UIntPtr.cs b/src/System.Private.CoreLib/shared/System/UIntPtr.cs index 484eef4b61b..9534f4f8728 100644 --- a/src/System.Private.CoreLib/shared/System/UIntPtr.cs +++ b/src/System.Private.CoreLib/shared/System/UIntPtr.cs @@ -18,9 +18,9 @@ namespace System [Serializable] [CLSCompliant(false)] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] - public struct UIntPtr : IEquatable, ISerializable + public readonly struct UIntPtr : IEquatable, ISerializable { - private unsafe void* _value; // Do not rename (binary serialization) + private readonly unsafe void* _value; // Do not rename (binary serialization) [Intrinsic] public static readonly UIntPtr Zero; From 7b2766c8fd6a9ce000ece4187cd23379daf444e8 Mon Sep 17 00:00:00 2001 From: Phil Garcia Date: Tue, 26 Jun 2018 22:03:49 -0700 Subject: [PATCH 27/69] Applying PR feedback Signed-off-by: dotnet-bot --- .../Internal/Runtime/CompilerServices/Unsafe.cs | 11 +++++++++++ src/System.Private.CoreLib/shared/System/Double.cs | 2 +- src/System.Private.CoreLib/shared/System/Single.cs | 2 +- 3 files changed, 13 insertions(+), 2 deletions(-) diff --git a/src/System.Private.CoreLib/shared/Internal/Runtime/CompilerServices/Unsafe.cs b/src/System.Private.CoreLib/shared/Internal/Runtime/CompilerServices/Unsafe.cs index aeff3ce2ca0..03d3f852117 100644 --- a/src/System.Private.CoreLib/shared/Internal/Runtime/CompilerServices/Unsafe.cs +++ b/src/System.Private.CoreLib/shared/Internal/Runtime/CompilerServices/Unsafe.cs @@ -357,6 +357,17 @@ public static void Write(ref byte destination, T value) return ref Unsafe.As(ref *(byte*)source); } + /// + /// Reinterprets the given location as a reference to a value of type . + /// + [Intrinsic] + [NonVersionable] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ref T AsRef(in T source) + { + throw new PlatformNotSupportedException(); + } + /// /// Determines the byte offset from origin to target from the given references. /// diff --git a/src/System.Private.CoreLib/shared/System/Double.cs b/src/System.Private.CoreLib/shared/System/Double.cs index 308dda5fadf..69da2e34b7d 100644 --- a/src/System.Private.CoreLib/shared/System/Double.cs +++ b/src/System.Private.CoreLib/shared/System/Double.cs @@ -226,7 +226,7 @@ public bool Equals(double obj) [MethodImpl(MethodImplOptions.AggressiveInlining)] // 64-bit constants make the IL unusually large that makes the inliner to reject the method public override int GetHashCode() { - var bits = BitConverter.DoubleToInt64Bits(m_value); + var bits = Unsafe.As(ref Unsafe.AsRef(in m_value)); // Optimized check for IsNan() || IsZero() if (((bits - 1) & 0x7FFFFFFFFFFFFFFF) >= 0x7FF0000000000000) diff --git a/src/System.Private.CoreLib/shared/System/Single.cs b/src/System.Private.CoreLib/shared/System/Single.cs index d62ff9ceea6..7dddb029a85 100644 --- a/src/System.Private.CoreLib/shared/System/Single.cs +++ b/src/System.Private.CoreLib/shared/System/Single.cs @@ -217,7 +217,7 @@ public bool Equals(float obj) public override int GetHashCode() { - var bits = BitConverter.SingleToInt32Bits(m_value); + var bits = Unsafe.As(ref Unsafe.AsRef(in m_value)); // Optimized check for IsNan() || IsZero() if (((bits - 1) & 0x7FFFFFFF) >= 0x7F800000) From f8a484a831c4abc070d105b683f8e3b33f91e99e Mon Sep 17 00:00:00 2001 From: Anirudh Agnihotry Date: Wed, 27 Jun 2018 11:36:42 -0700 Subject: [PATCH 28/69] Moved SafeWaitHandle and cancellationToken to shared (dotnet/coreclr#18662) * Moving SafeWaitHandle to shared * Moved CancellationToken to shared * _ remove from variable names * Default change to Default(Token) and minor changes * Fixing coreclr unix build * moving semaphoreSlim to shared * splitting safeWaitHandle to .windows and .unix Signed-off-by: dotnet-bot --- .../Windows/Kernel32/Interop.CloseHandle.cs | 1 - .../SafeHandles/SafeWaitHandle.Windows.cs | 11 + .../Win32/SafeHandles/SafeWaitHandle.cs | 21 + .../System.Private.CoreLib.Shared.projitems | 6 +- .../System/Threading/CancellationToken.cs | 340 +++++++ .../shared/System/Threading/SemaphoreSlim.cs | 946 ++++++++++++++++++ 6 files changed, 1323 insertions(+), 2 deletions(-) create mode 100644 src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeWaitHandle.Windows.cs create mode 100644 src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeWaitHandle.cs create mode 100644 src/System.Private.CoreLib/shared/System/Threading/CancellationToken.cs create mode 100644 src/System.Private.CoreLib/shared/System/Threading/SemaphoreSlim.cs diff --git a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.CloseHandle.cs b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.CloseHandle.cs index 96ed922a846..ff41f939f1c 100644 --- a/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.CloseHandle.cs +++ b/src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.CloseHandle.cs @@ -10,7 +10,6 @@ internal partial class Interop internal partial class Kernel32 { [DllImport(Libraries.Kernel32, SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool CloseHandle(IntPtr handle); } } diff --git a/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeWaitHandle.Windows.cs b/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeWaitHandle.Windows.cs new file mode 100644 index 00000000000..66f17f0af70 --- /dev/null +++ b/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeWaitHandle.Windows.cs @@ -0,0 +1,11 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +namespace Microsoft.Win32.SafeHandles +{ + public sealed partial class SafeWaitHandle : SafeHandleZeroOrMinusOneIsInvalid + { + protected override bool ReleaseHandle() => Interop.Kernel32.CloseHandle(handle); + } +} diff --git a/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeWaitHandle.cs b/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeWaitHandle.cs new file mode 100644 index 00000000000..edb0cdfcafe --- /dev/null +++ b/src/System.Private.CoreLib/shared/Microsoft/Win32/SafeHandles/SafeWaitHandle.cs @@ -0,0 +1,21 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; + +namespace Microsoft.Win32.SafeHandles +{ + public sealed partial class SafeWaitHandle : SafeHandleZeroOrMinusOneIsInvalid + { + // Called by P/Invoke marshaler + private SafeWaitHandle() : base(true) + { + } + + public SafeWaitHandle(IntPtr existingHandle, bool ownsHandle) : base(ownsHandle) + { + SetHandle(existingHandle); + } + } +} diff --git a/src/System.Private.CoreLib/shared/System.Private.CoreLib.Shared.projitems b/src/System.Private.CoreLib/shared/System.Private.CoreLib.Shared.projitems index da36623eaff..59a3074ab8b 100644 --- a/src/System.Private.CoreLib/shared/System.Private.CoreLib.Shared.projitems +++ b/src/System.Private.CoreLib/shared/System.Private.CoreLib.Shared.projitems @@ -26,6 +26,7 @@ + @@ -580,6 +581,7 @@ + @@ -594,6 +596,7 @@ + @@ -724,7 +727,6 @@ - @@ -810,6 +812,8 @@ + + diff --git a/src/System.Private.CoreLib/shared/System/Threading/CancellationToken.cs b/src/System.Private.CoreLib/shared/System/Threading/CancellationToken.cs new file mode 100644 index 00000000000..68e6971a542 --- /dev/null +++ b/src/System.Private.CoreLib/shared/System/Threading/CancellationToken.cs @@ -0,0 +1,340 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Diagnostics; +using System.Runtime.CompilerServices; + +namespace System.Threading +{ + /// + /// Propagates notification that operations should be canceled. + /// + /// + /// + /// A may be created directly in an unchangeable canceled or non-canceled state + /// using the CancellationToken's constructors. However, to have a CancellationToken that can change + /// from a non-canceled to a canceled state, + /// CancellationTokenSource must be used. + /// CancellationTokenSource exposes the associated CancellationToken that may be canceled by the source through its + /// Token property. + /// + /// + /// Once canceled, a token may not transition to a non-canceled state, and a token whose + /// is false will never change to one that can be canceled. + /// + /// + /// All members of this struct are thread-safe and may be used concurrently from multiple threads. + /// + /// + [DebuggerDisplay("IsCancellationRequested = {IsCancellationRequested}")] + public readonly struct CancellationToken + { + // The backing TokenSource. + // if null, it implicitly represents the same thing as new CancellationToken(false). + // When required, it will be instantiated to reflect this. + private readonly CancellationTokenSource _source; + //!! warning. If more fields are added, the assumptions in CreateLinkedToken may no longer be valid + + private readonly static Action s_actionToActionObjShunt = obj => ((Action)obj)(); + + /// + /// Returns an empty CancellationToken value. + /// + /// + /// The value returned by this property will be non-cancelable by default. + /// + public static CancellationToken None => default; + + /// + /// Gets whether cancellation has been requested for this token. + /// + /// Whether cancellation has been requested for this token. + /// + /// + /// This property indicates whether cancellation has been requested for this token, + /// either through the token initially being constructed in a canceled state, or through + /// calling Cancel + /// on the token's associated . + /// + /// + /// If this property is true, it only guarantees that cancellation has been requested. + /// It does not guarantee that every registered handler + /// has finished executing, nor that cancellation requests have finished propagating + /// to all registered handlers. Additional synchronization may be required, + /// particularly in situations where related objects are being canceled concurrently. + /// + /// + public bool IsCancellationRequested => _source != null && _source.IsCancellationRequested; + + /// + /// Gets whether this token is capable of being in the canceled state. + /// + /// + /// If CanBeCanceled returns false, it is guaranteed that the token will never transition + /// into a canceled state, meaning that will never + /// return true. + /// + public bool CanBeCanceled => _source != null; + + /// + /// Gets a that is signaled when the token is canceled. + /// + /// Accessing this property causes a WaitHandle + /// to be instantiated. It is preferable to only use this property when necessary, and to then + /// dispose the associated instance at the earliest opportunity (disposing + /// the source will dispose of this allocated handle). The handle should not be closed or disposed directly. + /// + /// The associated CancellationTokenSource has been disposed. + public WaitHandle WaitHandle => (_source ?? CancellationTokenSource.s_neverCanceledSource).WaitHandle; + + // public CancellationToken() + // this constructor is implicit for structs + // -> this should behaves exactly as for new CancellationToken(false) + + /// + /// Internal constructor only a CancellationTokenSource should create a CancellationToken + /// + internal CancellationToken(CancellationTokenSource source) => _source = source; + + /// + /// Initializes the CancellationToken. + /// + /// + /// The canceled state for the token. + /// + /// + /// Tokens created with this constructor will remain in the canceled state specified + /// by the parameter. If is false, + /// both and will be false. + /// If is true, + /// both and will be true. + /// + public CancellationToken(bool canceled) : this(canceled ? CancellationTokenSource.s_canceledSource : null) + { + } + + /// + /// Registers a delegate that will be called when this CancellationToken is canceled. + /// + /// + /// + /// If this token is already in the canceled state, the + /// delegate will be run immediately and synchronously. Any exception the delegate generates will be + /// propagated out of this method call. + /// + /// + /// The current ExecutionContext, if one exists, will be captured + /// along with the delegate and will be used when executing it. + /// + /// + /// The delegate to be executed when the CancellationToken is canceled. + /// The instance that can + /// be used to unregister the callback. + /// is null. + public CancellationTokenRegistration Register(Action callback) => + Register( + s_actionToActionObjShunt, + callback ?? throw new ArgumentNullException(nameof(callback)), + useSynchronizationContext: false, + useExecutionContext: true); + + /// + /// Registers a delegate that will be called when this + /// CancellationToken is canceled. + /// + /// + /// + /// If this token is already in the canceled state, the + /// delegate will be run immediately and synchronously. Any exception the delegate generates will be + /// propagated out of this method call. + /// + /// + /// The current ExecutionContext, if one exists, will be captured + /// along with the delegate and will be used when executing it. + /// + /// + /// The delegate to be executed when the CancellationToken is canceled. + /// A Boolean value that indicates whether to capture + /// the current SynchronizationContext and use it + /// when invoking the . + /// The instance that can + /// be used to unregister the callback. + /// is null. + public CancellationTokenRegistration Register(Action callback, bool useSynchronizationContext) => + Register( + s_actionToActionObjShunt, + callback ?? throw new ArgumentNullException(nameof(callback)), + useSynchronizationContext, + useExecutionContext: true); + + /// + /// Registers a delegate that will be called when this + /// CancellationToken is canceled. + /// + /// + /// + /// If this token is already in the canceled state, the + /// delegate will be run immediately and synchronously. Any exception the delegate generates will be + /// propagated out of this method call. + /// + /// + /// The current ExecutionContext, if one exists, will be captured + /// along with the delegate and will be used when executing it. + /// + /// + /// The delegate to be executed when the CancellationToken is canceled. + /// The state to pass to the when the delegate is invoked. This may be null. + /// The instance that can + /// be used to unregister the callback. + /// is null. + public CancellationTokenRegistration Register(Action callback, object state) => + Register(callback, state, useSynchronizationContext: false, useExecutionContext: true); + + /// + /// Registers a delegate that will be called when this + /// CancellationToken is canceled. + /// + /// + /// + /// If this token is already in the canceled state, the + /// delegate will be run immediately and synchronously. Any exception the delegate generates will be + /// propagated out of this method call. + /// + /// + /// The current ExecutionContext, if one exists, + /// will be captured along with the delegate and will be used when executing it. + /// + /// + /// The delegate to be executed when the CancellationToken is canceled. + /// The state to pass to the when the delegate is invoked. This may be null. + /// A Boolean value that indicates whether to capture + /// the current SynchronizationContext and use it + /// when invoking the . + /// The instance that can + /// be used to unregister the callback. + /// is null. + /// The associated CancellationTokenSource has been disposed. + public CancellationTokenRegistration Register(Action callback, object state, bool useSynchronizationContext) => + Register(callback, state, useSynchronizationContext, 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 callback, object state) => + Register(callback, state, useSynchronizationContext: false, useExecutionContext: false); + + /// + /// Registers a delegate that will be called when this + /// CancellationToken is canceled. + /// + /// + /// + /// If this token is already in the canceled state, the + /// delegate will be run immediately and synchronously. Any exception the delegate generates will be + /// propagated out of this method call. + /// + /// + /// The delegate to be executed when the CancellationToken is canceled. + /// The state to pass to the when the delegate is invoked. This may be null. + /// A Boolean value that indicates whether to capture + /// the current SynchronizationContext and use it + /// when invoking the . + /// The instance that can + /// be used to unregister the callback. + /// is null. + /// The associated CancellationTokenSource has been disposed. +#if CORECLR + private +#else + [MethodImpl(MethodImplOptions.NoInlining)] + public +#endif + CancellationTokenRegistration Register(Action callback, object state, bool useSynchronizationContext, bool useExecutionContext) + { + if (callback == null) + throw new ArgumentNullException(nameof(callback)); + + CancellationTokenSource source = _source; + return source != null ? + source.InternalRegister(callback, state, useSynchronizationContext ? SynchronizationContext.Current : null, useExecutionContext ? ExecutionContext.Capture() : null) : + default; // Nothing to do for tokens than can never reach the canceled state. Give back a dummy registration. + } + + /// + /// Determines whether the current CancellationToken instance is equal to the + /// specified token. + /// + /// The other CancellationToken to which to compare this + /// instance. + /// True if the instances are equal; otherwise, false. Two tokens are equal if they are associated + /// with the same CancellationTokenSource or if they were both constructed + /// from public CancellationToken constructors and their values are equal. + public bool Equals(CancellationToken other) => _source == other._source; + + /// + /// Determines whether the current CancellationToken instance is equal to the + /// specified . + /// + /// The other object to which to compare this instance. + /// True if is a CancellationToken + /// and if the two instances are equal; otherwise, false. Two tokens are equal if they are associated + /// with the same CancellationTokenSource or if they were both constructed + /// from public CancellationToken constructors and their values are equal. + /// An associated CancellationTokenSource has been disposed. + public override bool Equals(object other) => other is CancellationToken && Equals((CancellationToken)other); + + /// + /// Serves as a hash function for a CancellationToken. + /// + /// A hash code for the current CancellationToken instance. + public override int GetHashCode() => (_source ?? CancellationTokenSource.s_neverCanceledSource).GetHashCode(); + + /// + /// Determines whether two CancellationToken instances are equal. + /// + /// The first instance. + /// The second instance. + /// True if the instances are equal; otherwise, false. + /// An associated CancellationTokenSource has been disposed. + public static bool operator ==(CancellationToken left, CancellationToken right) => left.Equals(right); + + /// + /// Determines whether two CancellationToken instances are not equal. + /// + /// The first instance. + /// The second instance. + /// True if the instances are not equal; otherwise, false. + /// An associated CancellationTokenSource has been disposed. + public static bool operator !=(CancellationToken left, CancellationToken right) => !left.Equals(right); + + /// + /// Throws a OperationCanceledException if + /// this token has had cancellation requested. + /// + /// + /// This method provides functionality equivalent to: + /// + /// if (token.IsCancellationRequested) + /// throw new OperationCanceledException(token); + /// + /// + /// The token has had cancellation requested. + /// The associated CancellationTokenSource has been disposed. + public void ThrowIfCancellationRequested() + { + if (IsCancellationRequested) + ThrowOperationCanceledException(); + } + + // Throws an OCE; separated out to enable better inlining of ThrowIfCancellationRequested + private void ThrowOperationCanceledException() => + throw new OperationCanceledException(SR.OperationCanceled, this); + } +} diff --git a/src/System.Private.CoreLib/shared/System/Threading/SemaphoreSlim.cs b/src/System.Private.CoreLib/shared/System/Threading/SemaphoreSlim.cs new file mode 100644 index 00000000000..6dca573ef99 --- /dev/null +++ b/src/System.Private.CoreLib/shared/System/Threading/SemaphoreSlim.cs @@ -0,0 +1,946 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Threading.Tasks; + +namespace System.Threading +{ + /// + /// Limits the number of threads that can access a resource or pool of resources concurrently. + /// + /// + /// + /// The provides a lightweight semaphore class that doesn't + /// use Windows kernel semaphores. + /// + /// + /// All public and protected members of are thread-safe and may be used + /// concurrently from multiple threads, with the exception of Dispose, which + /// must only be used when all other operations on the have + /// completed. + /// + /// + [DebuggerDisplay("Current Count = {m_currentCount}")] + public class SemaphoreSlim : IDisposable + { + #region Private Fields + + // The semaphore count, initialized in the constructor to the initial value, every release call incremetns it + // and every wait call decrements it as long as its value is positive otherwise the wait will block. + // Its value must be between the maximum semaphore value and zero + private volatile int m_currentCount; + + // The maximum semaphore value, it is initialized to Int.MaxValue if the client didn't specify it. it is used + // to check if the count excceeded the maxi value or not. + private readonly int m_maxCount; + + // The number of synchronously waiting threads, it is set to zero in the constructor and increments before blocking the + // threading and decrements it back after that. It is used as flag for the release call to know if there are + // waiting threads in the monitor or not. + private int m_waitCount; + + /// + /// This is used to help prevent waking more waiters than necessary. It's not perfect and sometimes more waiters than + /// necessary may still be woken, see . + /// + private int m_countOfWaitersPulsedToWake; + + // Dummy object used to in lock statements to protect the semaphore count, wait handle and cancelation + private object m_lockObj; + + // Act as the semaphore wait handle, it's lazily initialized if needed, the first WaitHandle call initialize it + // and wait an release sets and resets it respectively as long as it is not null + private volatile ManualResetEvent m_waitHandle; + + // Head of list representing asynchronous waits on the semaphore. + private TaskNode m_asyncHead; + + // Tail of list representing asynchronous waits on the semaphore. + private TaskNode m_asyncTail; + + // A pre-completed task with Result==true + private static readonly Task s_trueTask = + new Task(false, true, (TaskCreationOptions)InternalTaskOptions.DoNotDispose, default); + // A pre-completed task with Result==false + private readonly static Task s_falseTask = + new Task(false, false, (TaskCreationOptions)InternalTaskOptions.DoNotDispose, default); + + // No maximum constant + private const int NO_MAXIMUM = int.MaxValue; + + // Task in a linked list of asynchronous waiters + private sealed class TaskNode : Task, IThreadPoolWorkItem + { + internal TaskNode Prev, Next; + internal TaskNode() : base() { } + + void IThreadPoolWorkItem.ExecuteWorkItem() + { + bool setSuccessfully = TrySetResult(true); + Debug.Assert(setSuccessfully, "Should have been able to complete task"); + } +#if CORECLR + void IThreadPoolWorkItem.MarkAborted(ThreadAbortException tae) { /* nop */ } +#endif + } + #endregion + + #region Public properties + + /// + /// Gets the current count of the . + /// + /// The current count of the . + public int CurrentCount + { + get { return m_currentCount; } + } + + /// + /// Returns a that can be used to wait on the semaphore. + /// + /// A that can be used to wait on the + /// semaphore. + /// + /// A successful wait on the does not imply a successful wait on + /// the itself, nor does it decrement the semaphore's + /// count. exists to allow a thread to block waiting on multiple + /// semaphores, but such a wait should be followed by a true wait on the target semaphore. + /// + /// The has been disposed. + public WaitHandle AvailableWaitHandle + { + get + { + CheckDispose(); + + // Return it directly if it is not null + if (m_waitHandle != null) + return m_waitHandle; + + //lock the count to avoid multiple threads initializing the handle if it is null + lock (m_lockObj) + { + if (m_waitHandle == null) + { + // The initial state for the wait handle is true if the count is greater than zero + // false otherwise + m_waitHandle = new ManualResetEvent(m_currentCount != 0); + } + } + return m_waitHandle; + } + } + + #endregion + + #region Constructors + /// + /// Initializes a new instance of the class, specifying + /// the initial number of requests that can be granted concurrently. + /// + /// The initial number of requests for the semaphore that can be granted + /// concurrently. + /// + /// is less than 0. + public SemaphoreSlim(int initialCount) + : this(initialCount, NO_MAXIMUM) + { + } + + /// + /// Initializes a new instance of the class, specifying + /// the initial and maximum number of requests that can be granted concurrently. + /// + /// The initial number of requests for the semaphore that can be granted + /// concurrently. + /// The maximum number of requests for the semaphore that can be granted + /// concurrently. + /// + /// is less than 0. -or- + /// is greater than . -or- + /// is less than 0. + public SemaphoreSlim(int initialCount, int maxCount) + { + if (initialCount < 0 || initialCount > maxCount) + { + throw new ArgumentOutOfRangeException( + nameof(initialCount), initialCount, SR.SemaphoreSlim_ctor_InitialCountWrong); + } + + //validate input + if (maxCount <= 0) + { + throw new ArgumentOutOfRangeException(nameof(maxCount), maxCount, SR.SemaphoreSlim_ctor_MaxCountWrong); + } + + m_maxCount = maxCount; + m_lockObj = new object(); + m_currentCount = initialCount; + } + + #endregion + + #region Methods + /// + /// Blocks the current thread until it can enter the . + /// + /// The current instance has already been + /// disposed. + public void Wait() + { + // Call wait with infinite timeout + Wait(Timeout.Infinite, new CancellationToken()); + } + + /// + /// Blocks the current thread until it can enter the , while observing a + /// . + /// + /// The token to + /// observe. + /// was + /// canceled. + /// The current instance has already been + /// disposed. + public void Wait(CancellationToken cancellationToken) + { + // Call wait with infinite timeout + Wait(Timeout.Infinite, cancellationToken); + } + + /// + /// Blocks the current thread until it can enter the , using a to measure the time interval. + /// + /// A that represents the number of milliseconds + /// to wait, or a that represents -1 milliseconds to wait indefinitely. + /// + /// true if the current thread successfully entered the ; + /// otherwise, false. + /// is a negative + /// number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater + /// than . + public bool Wait(TimeSpan timeout) + { + // Validate the timeout + long totalMilliseconds = (long)timeout.TotalMilliseconds; + if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue) + { + throw new System.ArgumentOutOfRangeException( + nameof(timeout), timeout, SR.SemaphoreSlim_Wait_TimeoutWrong); + } + + // Call wait with the timeout milliseconds + return Wait((int)timeout.TotalMilliseconds, new CancellationToken()); + } + + /// + /// Blocks the current thread until it can enter the , using a to measure the time interval, while observing a . + /// + /// A that represents the number of milliseconds + /// to wait, or a that represents -1 milliseconds to wait indefinitely. + /// + /// The to + /// observe. + /// true if the current thread successfully entered the ; + /// otherwise, false. + /// is a negative + /// number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater + /// than . + /// was canceled. + public bool Wait(TimeSpan timeout, CancellationToken cancellationToken) + { + // Validate the timeout + long totalMilliseconds = (long)timeout.TotalMilliseconds; + if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue) + { + throw new System.ArgumentOutOfRangeException( + nameof(timeout), timeout, SR.SemaphoreSlim_Wait_TimeoutWrong); + } + + // Call wait with the timeout milliseconds + return Wait((int)timeout.TotalMilliseconds, cancellationToken); + } + + /// + /// Blocks the current thread until it can enter the , using a 32-bit + /// signed integer to measure the time interval. + /// + /// The number of milliseconds to wait, or (-1) to wait indefinitely. + /// true if the current thread successfully entered the ; + /// otherwise, false. + /// is a + /// negative number other than -1, which represents an infinite time-out. + public bool Wait(int millisecondsTimeout) + { + return Wait(millisecondsTimeout, new CancellationToken()); + } + + + /// + /// Blocks the current thread until it can enter the , + /// using a 32-bit signed integer to measure the time interval, + /// while observing a . + /// + /// The number of milliseconds to wait, or (-1) to + /// wait indefinitely. + /// The to observe. + /// true if the current thread successfully entered the ; otherwise, false. + /// is a negative number other than -1, + /// which represents an infinite time-out. + /// was canceled. + public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken) + { + CheckDispose(); + + // Validate input + if (millisecondsTimeout < -1) + { + throw new ArgumentOutOfRangeException( + nameof(millisecondsTimeout), millisecondsTimeout, SR.SemaphoreSlim_Wait_TimeoutWrong); + } + + cancellationToken.ThrowIfCancellationRequested(); + + // Perf: Check the stack timeout parameter before checking the volatile count + if (millisecondsTimeout == 0 && m_currentCount == 0) + { + // Pessimistic fail fast, check volatile count outside lock (only when timeout is zero!) + return false; + } + + uint startTime = 0; + if (millisecondsTimeout != Timeout.Infinite && millisecondsTimeout > 0) + { + startTime = TimeoutHelper.GetTime(); + } + + bool waitSuccessful = false; + Task asyncWaitTask = null; + bool lockTaken = false; + + //Register for cancellation outside of the main lock. + //NOTE: Register/unregister inside the lock can deadlock as different lock acquisition orders could + // occur for (1)this.m_lockObj and (2)cts.internalLock + CancellationTokenRegistration cancellationTokenRegistration = cancellationToken.InternalRegisterWithoutEC(s_cancellationTokenCanceledEventHandler, this); + try + { + // Perf: first spin wait for the count to be positive. + // This additional amount of spinwaiting in addition + // to Monitor.Enter()’s spinwaiting has shown measurable perf gains in test scenarios. + if (m_currentCount == 0) + { + // Monitor.Enter followed by Monitor.Wait is much more expensive than waiting on an event as it involves another + // spin, contention, etc. The usual number of spin iterations that would otherwise be used here is increased to + // lessen that extra expense of doing a proper wait. + int spinCount = SpinWait.SpinCountforSpinBeforeWait * 4; + const int Sleep1Threshold = SpinWait.Sleep1ThresholdForSpinBeforeWait * 4; + + var spinner = new SpinWait(); + while (spinner.Count < spinCount) + { + spinner.SpinOnce(Sleep1Threshold); + + if (m_currentCount != 0) + { + break; + } + } + } + // entering the lock and incrementing waiters must not suffer a thread-abort, else we cannot + // clean up m_waitCount correctly, which may lead to deadlock due to non-woken waiters. + try { } + finally + { + Monitor.Enter(m_lockObj, ref lockTaken); + if (lockTaken) + { + m_waitCount++; + } + } + + // If there are any async waiters, for fairness we'll get in line behind + // then by translating our synchronous wait into an asynchronous one that we + // then block on (once we've released the lock). + if (m_asyncHead != null) + { + 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. + else + { + // If the count > 0 we are good to move on. + // If not, then wait if we were given allowed some wait duration + + OperationCanceledException oce = null; + + if (m_currentCount == 0) + { + if (millisecondsTimeout == 0) + { + return false; + } + + // Prepare for the main wait... + // wait until the count become greater than zero or the timeout is expired + try + { + waitSuccessful = WaitUntilCountOrTimeout(millisecondsTimeout, startTime, cancellationToken); + } + catch (OperationCanceledException e) { oce = e; } + } + + // Now try to acquire. We prioritize acquisition over cancellation/timeout so that we don't + // lose any counts when there are asynchronous waiters in the mix. Asynchronous waiters + // 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, + "If the wait was successful, there should be count available."); + if (m_currentCount > 0) + { + waitSuccessful = true; + m_currentCount--; + } + else if (oce != null) + { + throw oce; + } + + // Exposing wait handle which is lazily initialized if needed + if (m_waitHandle != null && m_currentCount == 0) + { + m_waitHandle.Reset(); + } + } + } + finally + { + // Release the lock + if (lockTaken) + { + m_waitCount--; + Monitor.Exit(m_lockObj); + } + + // Unregister the cancellation callback. + cancellationTokenRegistration.Dispose(); + } + + // If we had to fall back to asynchronous waiting, block on it + // here now that we've released the lock, and return its + // result when available. Otherwise, this was a synchronous + // wait, and whether we successfully acquired the semaphore is + // stored in waitSuccessful. + + return (asyncWaitTask != null) ? asyncWaitTask.GetAwaiter().GetResult() : waitSuccessful; + } + + /// + /// Local helper function, waits on the monitor until the monitor receives signal or the + /// timeout is expired + /// + /// The maximum timeout + /// The start ticks to calculate the elapsed time + /// The CancellationToken to observe. + /// true if the monitor received a signal, false if the timeout expired + private bool WaitUntilCountOrTimeout(int millisecondsTimeout, uint startTime, CancellationToken cancellationToken) + { + int remainingWaitMilliseconds = Timeout.Infinite; + + //Wait on the monitor as long as the count is zero + while (m_currentCount == 0) + { + // If cancelled, we throw. Trying to wait could lead to deadlock. + cancellationToken.ThrowIfCancellationRequested(); + + if (millisecondsTimeout != Timeout.Infinite) + { + remainingWaitMilliseconds = TimeoutHelper.UpdateTimeOut(startTime, millisecondsTimeout); + if (remainingWaitMilliseconds <= 0) + { + // The thread has expires its timeout + return false; + } + } + // ** the actual wait ** + bool waitSuccessful = Monitor.Wait(m_lockObj, remainingWaitMilliseconds); + + // This waiter has woken up and this needs to be reflected in the count of waiters pulsed to wake. Since we + // don't have thread-specific pulse state, there is not enough information to tell whether this thread woke up + // because it was pulsed. For instance, this thread may have timed out and may have been waiting to reacquire + // the lock before returning from Monitor.Wait, in which case we don't know whether this thread got pulsed. So + // in any woken case, decrement the count if possible. As such, timeouts could cause more waiters to wake than + // necessary. + if (m_countOfWaitersPulsedToWake != 0) + { + --m_countOfWaitersPulsedToWake; + } + + if (!waitSuccessful) + { + return false; + } + } + + return true; + } + + /// + /// Asynchronously waits to enter the . + /// + /// A task that will complete when the semaphore has been entered. + public Task WaitAsync() + { + return WaitAsync(Timeout.Infinite, default); + } + + /// + /// Asynchronously waits to enter the , while observing a + /// . + /// + /// A task that will complete when the semaphore has been entered. + /// + /// The token to observe. + /// + /// + /// The current instance has already been disposed. + /// + public Task WaitAsync(CancellationToken cancellationToken) + { + return WaitAsync(Timeout.Infinite, cancellationToken); + } + + /// + /// Asynchronously waits to enter the , + /// using a 32-bit signed integer to measure the time interval. + /// + /// + /// The number of milliseconds to wait, or (-1) to wait indefinitely. + /// + /// + /// A task that will complete with a result of true if the current thread successfully entered + /// the , otherwise with a result of false. + /// + /// The current instance has already been + /// disposed. + /// is a negative number other than -1, + /// which represents an infinite time-out. + /// + public Task WaitAsync(int millisecondsTimeout) + { + return WaitAsync(millisecondsTimeout, default); + } + + /// + /// Asynchronously waits to enter the , using a to measure the time interval, while observing a + /// . + /// + /// + /// A that represents the number of milliseconds + /// to wait, or a that represents -1 milliseconds to wait indefinitely. + /// + /// + /// The token to observe. + /// + /// + /// A task that will complete with a result of true if the current thread successfully entered + /// the , otherwise with a result of false. + /// + /// + /// The current instance has already been disposed. + /// + /// + /// is a negative number other than -1 milliseconds, which represents + /// an infinite time-out -or- timeout is greater than . + /// + public Task WaitAsync(TimeSpan timeout) + { + return WaitAsync(timeout, default); + } + + /// + /// Asynchronously waits to enter the , using a to measure the time interval. + /// + /// + /// A that represents the number of milliseconds + /// to wait, or a that represents -1 milliseconds to wait indefinitely. + /// + /// + /// A task that will complete with a result of true if the current thread successfully entered + /// the , otherwise with a result of false. + /// + /// + /// is a negative number other than -1 milliseconds, which represents + /// an infinite time-out -or- timeout is greater than . + /// + public Task WaitAsync(TimeSpan timeout, CancellationToken cancellationToken) + { + // Validate the timeout + long totalMilliseconds = (long)timeout.TotalMilliseconds; + if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue) + { + throw new System.ArgumentOutOfRangeException( + nameof(timeout), timeout, SR.SemaphoreSlim_Wait_TimeoutWrong); + } + + // Call wait with the timeout milliseconds + return WaitAsync((int)timeout.TotalMilliseconds, cancellationToken); + } + + /// + /// Asynchronously waits to enter the , + /// using a 32-bit signed integer to measure the time interval, + /// while observing a . + /// + /// + /// The number of milliseconds to wait, or (-1) to wait indefinitely. + /// + /// The to observe. + /// + /// A task that will complete with a result of true if the current thread successfully entered + /// the , otherwise with a result of false. + /// + /// The current instance has already been + /// disposed. + /// is a negative number other than -1, + /// which represents an infinite time-out. + /// + public Task WaitAsync(int millisecondsTimeout, CancellationToken cancellationToken) + { + CheckDispose(); + + // Validate input + if (millisecondsTimeout < -1) + { + throw new ArgumentOutOfRangeException( + nameof(millisecondsTimeout), millisecondsTimeout, SR.SemaphoreSlim_Wait_TimeoutWrong); + } + + // Bail early for cancellation + if (cancellationToken.IsCancellationRequested) + return Task.FromCanceled(cancellationToken); + + lock (m_lockObj) + { + // If there are counts available, allow this waiter to succeed. + if (m_currentCount > 0) + { + --m_currentCount; + if (m_waitHandle != null && m_currentCount == 0) m_waitHandle.Reset(); + return s_trueTask; + } + else if (millisecondsTimeout == 0) + { + // 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. + else + { + Debug.Assert(m_currentCount == 0, "m_currentCount should never be negative"); + var asyncWaiter = CreateAndAddAsyncWaiter(); + return (millisecondsTimeout == Timeout.Infinite && !cancellationToken.CanBeCanceled) ? + asyncWaiter : + WaitUntilCountOrTimeoutAsync(asyncWaiter, millisecondsTimeout, cancellationToken); + } + } + } + + /// Creates a new task and stores it into the async waiters list. + /// The created task. + private TaskNode CreateAndAddAsyncWaiter() + { + Debug.Assert(Monitor.IsEntered(m_lockObj), "Requires the lock be held"); + + // Create the task + var task = new TaskNode(); + + // Add it to the linked list + if (m_asyncHead == null) + { + Debug.Assert(m_asyncTail == null, "If head is null, so too should be tail"); + m_asyncHead = task; + m_asyncTail = task; + } + else + { + Debug.Assert(m_asyncTail != null, "If head is not null, neither should be tail"); + m_asyncTail.Next = task; + task.Prev = m_asyncTail; + m_asyncTail = task; + } + + // Hand it back + return task; + } + + /// Removes the waiter task from the linked list. + /// The task to remove. + /// true if the waiter was in the list; otherwise, false. + private bool RemoveAsyncWaiter(TaskNode task) + { + Debug.Assert(task != null, "Expected non-null task"); + Debug.Assert(Monitor.IsEntered(m_lockObj), "Requires the lock be held"); + + // Is the task in the list? To be in the list, either it's the head or it has a predecessor that's in the list. + bool wasInList = m_asyncHead == task || task.Prev != null; + + // Remove it from the linked list + if (task.Next != null) task.Next.Prev = task.Prev; + if (task.Prev != null) task.Prev.Next = task.Next; + if (m_asyncHead == task) m_asyncHead = task.Next; + if (m_asyncTail == task) m_asyncTail = task.Prev; + Debug.Assert((m_asyncHead == null) == (m_asyncTail == null), "Head is null iff tail is null"); + + // Make sure not to leak + task.Next = task.Prev = null; + + // Return whether the task was in the list + return wasInList; + } + + /// Performs the asynchronous wait. + /// The timeout. + /// The cancellation token. + /// The task to return to the caller. + private async Task WaitUntilCountOrTimeoutAsync(TaskNode asyncWaiter, int millisecondsTimeout, CancellationToken cancellationToken) + { + Debug.Assert(asyncWaiter != null, "Waiter should have been constructed"); + Debug.Assert(Monitor.IsEntered(m_lockObj), "Requires the lock be held"); + + // Wait until either the task is completed, timeout occurs, or cancellation is requested. + // We need to ensure that the Task.Delay task is appropriately cleaned up if the await + // completes due to the asyncWaiter completing, so we use our own token that we can explicitly + // cancel, and we chain the caller's supplied token into it. + using (var cts = cancellationToken.CanBeCanceled ? + CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, default) : + new CancellationTokenSource()) + { + var waitCompleted = Task.WhenAny(asyncWaiter, Task.Delay(millisecondsTimeout, cts.Token)); + if (asyncWaiter == await waitCompleted.ConfigureAwait(false)) + { + cts.Cancel(); // ensure that the Task.Delay task is cleaned up + return true; // successfully acquired + } + } + + // If we get here, the wait has timed out or been canceled. + + // If the await completed synchronously, we still hold the lock. If it didn't, + // we no longer hold the lock. As such, acquire it. + lock (m_lockObj) + { + // Remove the task from the list. If we're successful in doing so, + // we know that no one else has tried to complete this waiter yet, + // so we can safely cancel or timeout. + if (RemoveAsyncWaiter(asyncWaiter)) + { + cancellationToken.ThrowIfCancellationRequested(); // cancellation occurred + return false; // timeout occurred + } + } + + // The waiter had already been removed, which means it's already completed or is about to + // complete, so let it, and don't return until it does. + return await asyncWaiter.ConfigureAwait(false); + } + + /// + /// Exits the once. + /// + /// The previous count of the . + /// The current instance has already been + /// disposed. + public int Release() + { + return Release(1); + } + + /// + /// Exits the a specified number of times. + /// + /// The number of times to exit the semaphore. + /// The previous count of the . + /// is less + /// than 1. + /// The has + /// already reached its maximum size. + /// The current instance has already been + /// disposed. + public int Release(int releaseCount) + { + CheckDispose(); + + // Validate input + if (releaseCount < 1) + { + throw new ArgumentOutOfRangeException( + nameof(releaseCount), releaseCount, SR.SemaphoreSlim_Release_CountWrong); + } + int returnCount; + + lock (m_lockObj) + { + // Read the m_currentCount into a local variable to avoid unnecessary volatile accesses inside the lock. + int currentCount = m_currentCount; + returnCount = currentCount; + + // If the release count would result exceeding the maximum count, throw SemaphoreFullException. + if (m_maxCount - currentCount < releaseCount) + { + throw new SemaphoreFullException(); + } + + // Increment the count by the actual release count + currentCount += releaseCount; + + // Signal to any synchronous waiters, taking into account how many waiters have previously been pulsed to wake + // but have not yet woken + int waitCount = m_waitCount; + Debug.Assert(m_countOfWaitersPulsedToWake <= waitCount); + int waitersToNotify = Math.Min(currentCount, waitCount) - m_countOfWaitersPulsedToWake; + if (waitersToNotify > 0) + { + // Ideally, limiting to a maximum of releaseCount would not be necessary and could be an assert instead, but + // since WaitUntilCountOrTimeout() does not have enough information to tell whether a woken thread was + // pulsed, it's possible for m_countOfWaitersPulsedToWake to be less than the number of threads that have + // actually been pulsed to wake. + if (waitersToNotify > releaseCount) + { + waitersToNotify = releaseCount; + } + + m_countOfWaitersPulsedToWake += waitersToNotify; + for (int i = 0; i < waitersToNotify; i++) + { + Monitor.Pulse(m_lockObj); + } + } + + // Now signal to any asynchronous waiters, if there are any. While we've already + // signaled the synchronous waiters, we still hold the lock, and thus + // they won't have had an opportunity to acquire this yet. So, when releasing + // asynchronous waiters, we assume that all synchronous waiters will eventually + // acquire the semaphore. That could be a faulty assumption if those synchronous + // waits are canceled, but the wait code path will handle that. + if (m_asyncHead != null) + { + Debug.Assert(m_asyncTail != null, "tail should not be null if head isn't null"); + int maxAsyncToRelease = currentCount - waitCount; + while (maxAsyncToRelease > 0 && m_asyncHead != null) + { + --currentCount; + --maxAsyncToRelease; + + // Get the next async waiter to release and queue it to be completed + var waiterTask = m_asyncHead; + RemoveAsyncWaiter(waiterTask); // ensures waiterTask.Next/Prev are null + QueueWaiterTask(waiterTask); + } + } + m_currentCount = currentCount; + + // Exposing wait handle if it is not null + if (m_waitHandle != null && returnCount == 0 && currentCount > 0) + { + m_waitHandle.Set(); + } + } + + // And return the count + return returnCount; + } + + /// + /// Queues a waiter task to the ThreadPool. We use this small helper method so that + /// the larger Release(count) method does not need to be SecuritySafeCritical. + /// + private static void QueueWaiterTask(TaskNode waiterTask) + { + ThreadPool.UnsafeQueueCustomWorkItem(waiterTask, forceGlobal: false); + } + + /// + /// Releases all resources used by the current instance of . + /// + /// + /// Unlike most of the members of , is not + /// thread-safe and may not be used concurrently with other members of this instance. + /// + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + /// + /// When overridden in a derived class, releases the unmanaged resources used by the + /// , and optionally releases the managed resources. + /// + /// true to release both managed and unmanaged resources; + /// false to release only unmanaged resources. + /// + /// Unlike most of the members of , is not + /// thread-safe and may not be used concurrently with other members of this instance. + /// + protected virtual void Dispose(bool disposing) + { + if (disposing) + { + if (m_waitHandle != null) + { + m_waitHandle.Dispose(); + m_waitHandle = null; + } + m_lockObj = null; + m_asyncHead = null; + m_asyncTail = null; + } + } + + /// + /// Private helper method to wake up waiters when a cancellationToken gets canceled. + /// + private static Action s_cancellationTokenCanceledEventHandler = new Action(CancellationTokenCanceledEventHandler); + private static void CancellationTokenCanceledEventHandler(object obj) + { + SemaphoreSlim semaphore = obj as SemaphoreSlim; + Debug.Assert(semaphore != null, "Expected a SemaphoreSlim"); + lock (semaphore.m_lockObj) + { + Monitor.PulseAll(semaphore.m_lockObj); //wake up all waiters. + } + } + + /// + /// Checks the dispose status by checking the lock object, if it is null means that object + /// has been disposed and throw ObjectDisposedException + /// + private void CheckDispose() + { + if (m_lockObj == null) + { + throw new ObjectDisposedException(null, SR.SemaphoreSlim_Disposed); + } + } + #endregion + } +} From 9ffbd3db2f45402060a9a33b47245c86024c19db Mon Sep 17 00:00:00 2001 From: Anipik Date: Wed, 27 Jun 2018 13:40:54 -0700 Subject: [PATCH 29/69] Non Shared Changes --- .../Win32/SafeHandles/SafeWaitHandle.Unix.cs | 17 + .../Win32/SafeHandles/SafeWaitHandle.cs | 47 - .../src/System.Private.CoreLib.csproj | 6 +- .../src/System/Threading/CancellationToken.cs | 478 --------- .../Threading/CancellationTokenSource.cs | 350 +++---- .../src/System/Threading/SemaphoreSlim.cs | 916 ------------------ 6 files changed, 158 insertions(+), 1656 deletions(-) create mode 100644 src/System.Private.CoreLib/src/Microsoft/Win32/SafeHandles/SafeWaitHandle.Unix.cs delete mode 100644 src/System.Private.CoreLib/src/Microsoft/Win32/SafeHandles/SafeWaitHandle.cs delete mode 100644 src/System.Private.CoreLib/src/System/Threading/CancellationToken.cs delete mode 100644 src/System.Private.CoreLib/src/System/Threading/SemaphoreSlim.cs diff --git a/src/System.Private.CoreLib/src/Microsoft/Win32/SafeHandles/SafeWaitHandle.Unix.cs b/src/System.Private.CoreLib/src/Microsoft/Win32/SafeHandles/SafeWaitHandle.Unix.cs new file mode 100644 index 00000000000..35e464b6731 --- /dev/null +++ b/src/System.Private.CoreLib/src/Microsoft/Win32/SafeHandles/SafeWaitHandle.Unix.cs @@ -0,0 +1,17 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Threading; + +namespace Microsoft.Win32.SafeHandles +{ + public sealed partial class SafeWaitHandle : SafeHandleZeroOrMinusOneIsInvalid + { + protected override bool ReleaseHandle() + { + WaitSubsystem.DeleteHandle(handle); + return true; + } + } +} diff --git a/src/System.Private.CoreLib/src/Microsoft/Win32/SafeHandles/SafeWaitHandle.cs b/src/System.Private.CoreLib/src/Microsoft/Win32/SafeHandles/SafeWaitHandle.cs deleted file mode 100644 index 7527395fe25..00000000000 --- a/src/System.Private.CoreLib/src/Microsoft/Win32/SafeHandles/SafeWaitHandle.cs +++ /dev/null @@ -1,47 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -/*============================================================ -** -** -** -** A wrapper for Win32 events (mutexes, auto reset events, and -** manual reset events). Used by WaitHandle. -** -** -===========================================================*/ - -using System; -using System.Security; -using System.Runtime.InteropServices; -using System.Runtime.CompilerServices; -using System.Runtime.Versioning; -using Microsoft.Win32; -using System.Threading; - -namespace Microsoft.Win32.SafeHandles -{ - public sealed class SafeWaitHandle : SafeHandleZeroOrMinusOneIsInvalid - { - // Called by P/Invoke marshaler - private SafeWaitHandle() : base(true) - { - } - - public SafeWaitHandle(IntPtr existingHandle, bool ownsHandle) : base(ownsHandle) - { - SetHandle(existingHandle); - } - - protected override bool ReleaseHandle() - { -#if PLATFORM_UNIX - WaitSubsystem.DeleteHandle(handle); -#else - Interop.Kernel32.CloseHandle(handle); -#endif - return true; - } - } -} diff --git a/src/System.Private.CoreLib/src/System.Private.CoreLib.csproj b/src/System.Private.CoreLib/src/System.Private.CoreLib.csproj index f7618ebe1ba..7b15dd84722 100644 --- a/src/System.Private.CoreLib/src/System.Private.CoreLib.csproj +++ b/src/System.Private.CoreLib/src/System.Private.CoreLib.csproj @@ -148,7 +148,6 @@ - @@ -295,7 +294,6 @@ - @@ -311,7 +309,6 @@ - @@ -555,6 +552,7 @@ + @@ -753,4 +751,4 @@ - + \ No newline at end of file diff --git a/src/System.Private.CoreLib/src/System/Threading/CancellationToken.cs b/src/System.Private.CoreLib/src/System/Threading/CancellationToken.cs deleted file mode 100644 index ee7d8bf90f7..00000000000 --- a/src/System.Private.CoreLib/src/System/Threading/CancellationToken.cs +++ /dev/null @@ -1,478 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -// - -//////////////////////////////////////////////////////////////////////////////// - -#pragma warning disable 0420 // turn off 'a reference to a volatile field will not be treated as volatile' during CAS. - - -using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Runtime.CompilerServices; - -namespace System.Threading -{ - /// - /// Propagates notification that operations should be canceled. - /// - /// - /// - /// A may be created directly in an unchangeable canceled or non-canceled state - /// using the CancellationToken's constructors. However, to have a CancellationToken that can change - /// from a non-canceled to a canceled state, - /// CancellationTokenSource must be used. - /// CancellationTokenSource exposes the associated CancellationToken that may be canceled by the source through its - /// Token property. - /// - /// - /// Once canceled, a token may not transition to a non-canceled state, and a token whose - /// is false will never change to one that can be canceled. - /// - /// - /// All members of this struct are thread-safe and may be used concurrently from multiple threads. - /// - /// - [DebuggerDisplay("IsCancellationRequested = {IsCancellationRequested}")] - public readonly struct CancellationToken - { - // The backing TokenSource. - // if null, it implicitly represents the same thing as new CancellationToken(false). - // When required, it will be instantiated to reflect this. - private readonly CancellationTokenSource m_source; - //!! warning. If more fields are added, the assumptions in CreateLinkedToken may no longer be valid - - /* Properties */ - - /// - /// Returns an empty CancellationToken value. - /// - /// - /// The value returned by this property will be non-cancelable by default. - /// - public static CancellationToken None - { - get { return default(CancellationToken); } - } - - /// - /// Gets whether cancellation has been requested for this token. - /// - /// Whether cancellation has been requested for this token. - /// - /// - /// This property indicates whether cancellation has been requested for this token, - /// either through the token initially being construted in a canceled state, or through - /// calling Cancel - /// on the token's associated . - /// - /// - /// If this property is true, it only guarantees that cancellation has been requested. - /// It does not guarantee that every registered handler - /// has finished executing, nor that cancellation requests have finished propagating - /// to all registered handlers. Additional synchronization may be required, - /// particularly in situations where related objects are being canceled concurrently. - /// - /// - public bool IsCancellationRequested - { - get - { - return m_source != null && m_source.IsCancellationRequested; - } - } - - /// - /// Gets whether this token is capable of being in the canceled state. - /// - /// - /// If CanBeCanceled returns false, it is guaranteed that the token will never transition - /// into a canceled state, meaning that will never - /// return true. - /// - public bool CanBeCanceled - { - get - { - return m_source != null && m_source.CanBeCanceled; - } - } - - /// - /// Gets a that is signaled when the token is canceled. - /// - /// Accessing this property causes a WaitHandle - /// to be instantiated. It is preferable to only use this property when necessary, and to then - /// dispose the associated instance at the earliest opportunity (disposing - /// the source will dispose of this allocated handle). The handle should not be closed or disposed directly. - /// - /// The associated CancellationTokenSource has been disposed. - public WaitHandle WaitHandle => (m_source ?? CancellationTokenSource.InternalGetStaticSource(false)).WaitHandle; - - // public CancellationToken() - // this constructor is implicit for structs - // -> this should behaves exactly as for new CancellationToken(false) - - /// - /// Internal constructor only a CancellationTokenSource should create a CancellationToken - /// - internal CancellationToken(CancellationTokenSource source) - { - m_source = source; - } - - /// - /// Initializes the CancellationToken. - /// - /// - /// The canceled state for the token. - /// - /// - /// Tokens created with this constructor will remain in the canceled state specified - /// by the parameter. If is false, - /// both and will be false. - /// If is true, - /// both and will be true. - /// - public CancellationToken(bool canceled) : - this() - { - if (canceled) - m_source = CancellationTokenSource.InternalGetStaticSource(canceled); - } - - /* Methods */ - - - private static readonly Action s_ActionToActionObjShunt = new Action(ActionToActionObjShunt); - private static void ActionToActionObjShunt(object obj) - { - Action action = obj as Action; - Debug.Assert(action != null, "Expected an Action here"); - action(); - } - - /// - /// Registers a delegate that will be called when this CancellationToken is canceled. - /// - /// - /// - /// If this token is already in the canceled state, the - /// delegate will be run immediately and synchronously. Any exception the delegate generates will be - /// propagated out of this method call. - /// - /// - /// The delegate to be executed when the CancellationToken is canceled. - /// The instance that can - /// be used to unregister the callback. - /// is null. - /// The associated CancellationTokenSource has been disposed. - public CancellationTokenRegistration Register(Action callback) - { - if (callback == null) - throw new ArgumentNullException(nameof(callback)); - - return Register( - s_ActionToActionObjShunt, - callback, - false, // useSync=false - true // useExecutionContext=true - ); - } - - /// - /// Registers a delegate that will be called when this - /// CancellationToken is canceled. - /// - /// - /// - /// If this token is already in the canceled state, the - /// delegate will be run immediately and synchronously. Any exception the delegate generates will be - /// propagated out of this method call. - /// - /// - /// The delegate to be executed when the CancellationToken is canceled. - /// A Boolean value that indicates whether to capture - /// the current SynchronizationContext and use it - /// when invoking the . - /// The instance that can - /// be used to unregister the callback. - /// is null. - public CancellationTokenRegistration Register(Action callback, bool useSynchronizationContext) - { - if (callback == null) - throw new ArgumentNullException(nameof(callback)); - - return Register( - s_ActionToActionObjShunt, - callback, - useSynchronizationContext, - true // useExecutionContext=true - ); - } - - /// - /// Registers a delegate that will be called when this - /// CancellationToken is canceled. - /// - /// - /// - /// If this token is already in the canceled state, the - /// delegate will be run immediately and synchronously. Any exception the delegate generates will be - /// propagated out of this method call. - /// - /// - /// The delegate to be executed when the CancellationToken is canceled. - /// The state to pass to the when the delegate is invoked. This may be null. - /// The instance that can - /// be used to unregister the callback. - /// is null. - public CancellationTokenRegistration Register(Action callback, object state) - { - if (callback == null) - throw new ArgumentNullException(nameof(callback)); - - return Register( - callback, - state, - false, // useSync=false - true // useExecutionContext=true - ); - } - - /// - /// Registers a delegate that will be called when this - /// CancellationToken is canceled. - /// - /// - /// - /// If this token is already in the canceled state, the - /// delegate will be run immediately and synchronously. Any exception the delegate generates will be - /// propagated out of this method call. - /// - /// - /// The current ExecutionContext, if one exists, - /// will be captured along with the delegate and will be used when executing it. - /// - /// - /// The delegate to be executed when the CancellationToken is canceled. - /// The state to pass to the when the delegate is invoked. This may be null. - /// A Boolean value that indicates whether to capture - /// the current SynchronizationContext and use it - /// when invoking the . - /// The instance that can - /// be used to unregister the callback. - /// is null. - /// The associated CancellationTokenSource has been disposed. - public CancellationTokenRegistration Register(Action callback, object state, bool useSynchronizationContext) - { - return Register( - callback, - state, - useSynchronizationContext, - 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 callback, object state) - { - return Register( - callback, - state, - false, // useSyncContext=false - false // useExecutionContext=false - ); - } - - /// - /// Registers a delegate that will be called when this - /// CancellationToken is canceled. - /// - /// - /// - /// If this token is already in the canceled state, the - /// delegate will be run immediately and synchronously. Any exception the delegate generates will be - /// propagated out of this method call. - /// - /// - /// The delegate to be executed when the CancellationToken is canceled. - /// The state to pass to the when the delegate is invoked. This may be null. - /// A Boolean value that indicates whether to capture - /// the current SynchronizationContext and use it - /// when invoking the . - /// The instance that can - /// be used to unregister the callback. - /// is null. - /// The associated CancellationTokenSource has been disposed. - [MethodImpl(MethodImplOptions.NoInlining)] - public CancellationTokenRegistration Register(Action callback, object state, bool useSynchronizationContext, bool useExecutionContext) - { - if (callback == null) - throw new ArgumentNullException(nameof(callback)); - - if (CanBeCanceled == false) - { - return new CancellationTokenRegistration(); // nothing to do for tokens than can never reach the canceled state. Give them a dummy registration. - } - - // Capture sync/execution contexts if required. - // Note: Only capture sync/execution contexts if IsCancellationRequested = false - // as we know that if it is true that the callback will just be called synchronously. - - SynchronizationContext capturedSyncContext = null; - ExecutionContext capturedExecutionContext = null; - if (!IsCancellationRequested) - { - if (useSynchronizationContext) - capturedSyncContext = SynchronizationContext.Current; - if (useExecutionContext) - capturedExecutionContext = ExecutionContext.Capture(); - } - - // Register the callback with the source. - return m_source.InternalRegister(callback, state, capturedSyncContext, capturedExecutionContext); - } - - /// - /// Determines whether the current CancellationToken instance is equal to the - /// specified token. - /// - /// The other CancellationToken to which to compare this - /// instance. - /// True if the instances are equal; otherwise, false. Two tokens are equal if they are associated - /// with the same CancellationTokenSource or if they were both constructed - /// from public CancellationToken constructors and their values are equal. - public bool Equals(CancellationToken other) - { - //if both sources are null, then both tokens represent the Empty token. - if (m_source == null && other.m_source == null) - { - return true; - } - - // one is null but other has inflated the default source - // these are only equal if the inflated one is the staticSource(false) - if (m_source == null) - { - 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; - } - - /// - /// Determines whether the current CancellationToken instance is equal to the - /// specified . - /// - /// The other object to which to compare this instance. - /// True if is a CancellationToken - /// and if the two instances are equal; otherwise, false. Two tokens are equal if they are associated - /// with the same CancellationTokenSource or if they were both constructed - /// from public CancellationToken constructors and their values are equal. - /// An associated CancellationTokenSource has been disposed. - public override bool Equals(object other) - { - if (other is CancellationToken) - { - return Equals((CancellationToken)other); - } - - return false; - } - - /// - /// Serves as a hash function for a CancellationToken. - /// - /// A hash code for the current CancellationToken instance. - public override int GetHashCode() - { - if (m_source == null) - { - // link to the common source so that we have a source to interrogate. - return CancellationTokenSource.InternalGetStaticSource(false).GetHashCode(); - } - - return m_source.GetHashCode(); - } - - /// - /// Determines whether two CancellationToken instances are equal. - /// - /// The first instance. - /// The second instance. - /// True if the instances are equal; otherwise, false. - /// An associated CancellationTokenSource has been disposed. - public static bool operator ==(CancellationToken left, CancellationToken right) - { - return left.Equals(right); - } - - /// - /// Determines whether two CancellationToken instances are not equal. - /// - /// The first instance. - /// The second instance. - /// True if the instances are not equal; otherwise, false. - /// An associated CancellationTokenSource has been disposed. - public static bool operator !=(CancellationToken left, CancellationToken right) - { - return !left.Equals(right); - } - - /// - /// Throws a OperationCanceledException if - /// this token has had cancellation requested. - /// - /// - /// This method provides functionality equivalent to: - /// - /// if (token.IsCancellationRequested) - /// throw new OperationCanceledException(token); - /// - /// - /// The token has had cancellation requested. - /// The associated CancellationTokenSource has been disposed. - public void ThrowIfCancellationRequested() - { - if (IsCancellationRequested) - ThrowOperationCanceledException(); - } - - // Throw an ODE if this CancellationToken's source is disposed. - internal void ThrowIfSourceDisposed() - { - if ((m_source != null) && m_source.IsDisposed) - ThrowObjectDisposedException(); - } - - // Throws an OCE; separated out to enable better inlining of ThrowIfCancellationRequested - private void ThrowOperationCanceledException() - { - throw new OperationCanceledException(SR.OperationCanceled, this); - } - - private static void ThrowObjectDisposedException() - { - throw new ObjectDisposedException(null, SR.CancellationToken_SourceDisposed); - } - } -} diff --git a/src/System.Private.CoreLib/src/System/Threading/CancellationTokenSource.cs b/src/System.Private.CoreLib/src/System/Threading/CancellationTokenSource.cs index 8a2e15b88f4..9dbc0db084d 100644 --- a/src/System.Private.CoreLib/src/System/Threading/CancellationTokenSource.cs +++ b/src/System.Private.CoreLib/src/System/Threading/CancellationTokenSource.cs @@ -1,15 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -#pragma warning disable 0420 - -// - -//////////////////////////////////////////////////////////////////////////////// using System.Collections.Generic; using System.Diagnostics; -using System.Runtime.InteropServices; namespace System.Threading { @@ -33,46 +27,44 @@ namespace System.Threading /// public class CancellationTokenSource : IDisposable { - //static sources that can be used as the backing source for 'fixed' CancellationTokens that never change state. - private static readonly CancellationTokenSource _staticSource_Set = new CancellationTokenSource(true); - private static readonly CancellationTokenSource _staticSource_NotCancelable = new CancellationTokenSource(false); + // static sources that can be used as the backing source for 'fixed' CancellationTokens that never change state. + internal static readonly CancellationTokenSource s_canceledSource = new CancellationTokenSource() { _state = NotifyingCompleteState }; + internal static readonly CancellationTokenSource s_neverCanceledSource = new CancellationTokenSource() { _state = CannotBeCanceled }; - //Note: the callback lists array is only created on first registration. - // 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 + // Note: the callback lists array is only created on first registration. + // 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 volatile ManualResetEvent m_kernelEvent; //lazily initialized if required. + private volatile ManualResetEvent _kernelEvent; //lazily initialized if required. - private volatile SparselyPopulatedArray[] m_registeredCallbacksLists; + private volatile SparselyPopulatedArray[] _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; + // legal values for _state + private const int CannotBeCanceled = 0; + private const int NotCanceledState = 1; + private const int NotifyingState = 2; + private const int NotifyingCompleteState = 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; + //_state uses the pattern "volatile int32 reads, with cmpxch writes" which is safe for updates and cannot suffer torn reads. + private volatile int _state; + /// The ID of the thread currently executing the main body of CTS.Cancel() + /// + /// This helps us to know if a call to ctr.Dispose() is running 'within' a cancellation callback. + /// This is updated as we move between the main thread calling cts.Cancel() and any syncContexts + /// that are used to actually run the callbacks. + /// + private volatile int _threadIDExecutingCallbacks = -1; - /// The ID of the thread currently executing the main body of CTS.Cancel() - /// this helps us to know if a call to ctr.Dispose() is running 'within' a cancellation callback. - /// This is updated as we move between the main thread calling cts.Cancel() and any syncContexts that are used to - /// actually run the callbacks. - private volatile int m_threadIDExecutingCallbacks = -1; - - private bool m_disposed; + private bool _disposed; // we track the running callback to assist ctr.Dispose() to wait for the target callback to complete. - private volatile CancellationCallbackInfo m_executingCallback; + private volatile CancellationCallbackInfo _executingCallback; // provided for CancelAfter and timer-related constructors - private volatile Timer m_timer; - - // ---------------------- - // ** public properties + private volatile Timer _timer; /// /// Gets whether cancellation has been requested for this /// - public bool IsCancellationRequested - { - get { return m_state >= NOTIFYING; } - } + public bool IsCancellationRequested => _state >= NotifyingState; /// /// A simple helper to determine whether cancellation has finished. /// - internal bool IsCancellationCompleted - { - get { return m_state == NOTIFYINGCOMPLETE; } - } + internal bool IsCancellationCompleted => _state == NotifyingCompleteState; /// /// A simple helper to determine whether disposal has occurred. /// - internal bool IsDisposed - { - get { return m_disposed; } - } + internal bool IsDisposed => _disposed; /// /// The ID of the thread that is running callbacks. /// internal int ThreadIDExecutingCallbacks { - set { m_threadIDExecutingCallbacks = value; } - get { return m_threadIDExecutingCallbacks; } + get => _threadIDExecutingCallbacks; + set => _threadIDExecutingCallbacks = value; } /// @@ -140,36 +123,25 @@ public CancellationToken Token return new CancellationToken(this); } } - - // ---------------------- - // ** internal and private properties. - - /// - /// - /// internal bool CanBeCanceled { - get { return m_state != CANNOT_BE_CANCELED; } + get { return _state != CannotBeCanceled; } } - - /// - /// - /// internal WaitHandle WaitHandle { get { ThrowIfDisposed(); - // fast path if already allocated. - if (m_kernelEvent != null) - return m_kernelEvent; + // Return the handle if it was already allocated. + if (_kernelEvent != null) + return _kernelEvent; - // lazy-init the mre. + // Lazily-initialize the handle. ManualResetEvent mre = new ManualResetEvent(false); - if (Interlocked.CompareExchange(ref m_kernelEvent, mre, null) != null) + if (Interlocked.CompareExchange(ref _kernelEvent, mre, null) != null) { - ((IDisposable)mre).Dispose(); + mre.Dispose(); } // There is a race condition between checking IsCancellationRequested and setting the event. @@ -177,9 +149,9 @@ internal WaitHandle WaitHandle // 1. if IsCancellationRequested = true, then we will call Set() // 2. if IsCancellationRequested = false, then NotifyCancellation will see that the event exists, and will call Set(). if (IsCancellationRequested) - m_kernelEvent.Set(); + _kernelEvent.Set(); - return m_kernelEvent; + return _kernelEvent; } } @@ -187,10 +159,7 @@ internal WaitHandle WaitHandle /// /// The currently executing callback /// - internal CancellationCallbackInfo ExecutingCallback - { - get { return m_executingCallback; } - } + internal CancellationCallbackInfo ExecutingCallback => _executingCallback; #if DEBUG /// @@ -202,7 +171,7 @@ private int CallbackCount { get { - SparselyPopulatedArray[] callbackLists = m_registeredCallbacksLists; + SparselyPopulatedArray[] callbackLists = _registeredCallbacksLists; if (callbackLists == null) return 0; @@ -227,23 +196,10 @@ private int CallbackCount } #endif - // ** Public Constructors - /// /// Initializes the . /// - public CancellationTokenSource() - { - m_state = NOT_CANCELED; - } - - // ** Private constructors for static sources. - // set=false ==> cannot be canceled. - // set=true ==> is canceled. - private CancellationTokenSource(bool set) - { - m_state = set ? NOTIFYINGCOMPLETE : CANNOT_BE_CANCELED; - } + public CancellationTokenSource() => _state = NotCanceledState; /// /// Constructs a that will be canceled after a specified time span. @@ -307,12 +263,10 @@ public CancellationTokenSource(int millisecondsDelay) // Common initialization logic when constructing a CTS with a delay parameter private void InitializeWithTimer(int millisecondsDelay) { - m_state = NOT_CANCELED; - m_timer = new Timer(s_timerCallback, this, millisecondsDelay, -1); + _state = NotCanceledState; + _timer = new Timer(s_timerCallback, this, millisecondsDelay, -1); } - // ** Public Methods - /// /// Communicates a request for cancellation. /// @@ -334,10 +288,7 @@ private void InitializeWithTimer(int millisecondsDelay) /// by the registered callbacks on the associated . /// This has been disposed. - public void Cancel() - { - Cancel(false); - } + public void Cancel() => Cancel(false); /// /// Communicates a request for cancellation. @@ -391,8 +342,7 @@ public void Cancel(bool throwOnFirstException) /// /// /// Subsequent calls to CancelAfter will reset the delay for this - /// , if it has not been - /// canceled already. + /// , if it has not been canceled already. /// /// public void CancelAfter(TimeSpan delay) @@ -439,7 +389,10 @@ public void CancelAfter(int millisecondsDelay) throw new ArgumentOutOfRangeException(nameof(millisecondsDelay)); } - if (IsCancellationRequested) return; + if (IsCancellationRequested) + { + return; + } // There is a race condition here as a Cancel could occur between the check of // IsCancellationRequested and the creation of the timer. This is benign; in the @@ -450,26 +403,25 @@ public void CancelAfter(int millisecondsDelay) // expired and Disposed itself). But this would be considered bad behavior, as // Dispose() is not thread-safe and should not be called concurrently with CancelAfter(). - if (m_timer == null) + if (_timer == null) { // Lazily initialize the timer in a thread-safe fashion. // Initially set to "never go off" because we don't want to take a // chance on a timer "losing" the initialization and then // cancelling the token before it (the timer) can be disposed. Timer newTimer = new Timer(s_timerCallback, this, -1, -1); - if (Interlocked.CompareExchange(ref m_timer, newTimer, null) != null) + if (Interlocked.CompareExchange(ref _timer, newTimer, null) != null) { // We did not initialize the timer. Dispose the new timer. newTimer.Dispose(); } } - - // It is possible that m_timer has already been disposed, so we must do + // It is possible that _timer has already been disposed, so we must do // the following in a try/catch block. try { - m_timer.Change(millisecondsDelay, -1); + _timer.Change(millisecondsDelay, -1); } catch (ObjectDisposedException) { @@ -495,7 +447,7 @@ private static void TimerCallbackLogic(object obj) // against this race condition. try { - cts.Cancel(); // will take care of disposing of m_timer + cts.Cancel(); // will take care of disposing of _timer } catch (ObjectDisposedException) { @@ -523,9 +475,7 @@ public void Dispose() /// true to release both managed and unmanaged resources; false to release only unmanaged resources. protected virtual void Dispose(bool disposing) { - // There is nothing to do if disposing=false because the CancellationTokenSource holds no unmanaged resources. - - if (disposing && !m_disposed) + if (disposing && !_disposed) { //NOTE: We specifically tolerate that a callback can be unregistered // after the CTS has been disposed and/or concurrently with cts.Dispose(). @@ -535,8 +485,8 @@ protected virtual void Dispose(bool disposing) // // We also tolerate that a callback can be registered after the CTS has been // disposed. This is safe without locks because InternalRegister is tolerant - // of m_registeredCallbacksLists becoming null during its execution. However, - // we run the acceptable risk of m_registeredCallbacksLists getting reinitialized + // of _registeredCallbacksLists becoming null during its execution. However, + // we run the acceptable risk of _registeredCallbacksLists getting reinitialized // to non-null if there is a race between Dispose and Register, in which case this // instance may unnecessarily hold onto a registered callback. But that's no worse // than if Dispose wasn't safe to use concurrently, as Dispose would never be called, @@ -549,57 +499,43 @@ protected virtual void Dispose(bool disposing) // internal source of cancellation, then Disposes of that linked source, which could // happen at the same time the external entity is requesting cancellation). - m_timer?.Dispose(); // Timer.Dispose is thread-safe + _timer?.Dispose(); // Timer.Dispose is thread-safe // registered callbacks are now either complete or will never run, due to guarantees made by ctr.Dispose() // so we can now perform main disposal work without risk of linking callbacks trying to use this CTS. - m_registeredCallbacksLists = null; // free for GC; Cancel correctly handles a null field + _registeredCallbacksLists = null; // free for GC; Cancel correctly handles a null field // If a kernel event was created via WaitHandle, we'd like to Dispose of it. However, // we only want to do so if it's not being used by Cancel concurrently. First, we // interlocked exchange it to be null, and then we check whether cancellation is currently // in progress. NotifyCancellation will only try to set the event if it exists after it's - // transitioned to and while it's in the NOTIFYING state. - if (m_kernelEvent != null) + // transitioned to and while it's in the NotifyingState. + if (_kernelEvent != null) { - ManualResetEvent mre = Interlocked.Exchange(ref m_kernelEvent, null); - if (mre != null && m_state != NOTIFYING) + ManualResetEvent mre = Interlocked.Exchange(ref _kernelEvent, null); + if (mre != null && _state != NotifyingState) { mre.Dispose(); } } - m_disposed = true; + _disposed = true; } } - // -- Internal methods. - /// /// Throws an exception if the source has been disposed. /// internal void ThrowIfDisposed() { - if (m_disposed) + if (_disposed) ThrowObjectDisposedException(); } - // separation enables inlining of ThrowIfDisposed - private static void ThrowObjectDisposedException() - { + /// Throws an . Separated out from ThrowIfDisposed to help with inlining. + private static void ThrowObjectDisposedException() => throw new ObjectDisposedException(null, SR.CancellationTokenSource_Disposed); - } - - /// - /// InternalGetStaticSource() - /// - /// Whether the source should be set. - /// A static source to be shared among multiple tokens. - internal static CancellationTokenSource InternalGetStaticSource(bool set) - { - return set ? _staticSource_Set : _staticSource_NotCancelable; - } /// /// Registers a callback object. If cancellation has already occurred, the @@ -625,11 +561,11 @@ internal static CancellationTokenSource InternalGetStaticSource(bool set) // while at the same time not paying any non-negligible overhead. The simple compromise // is to check whether we're disposed (not volatile), and if we see we are, to return an empty // registration, just as if CanBeCanceled was false for the check made in CancellationToken.Register. - // If there's a race and m_disposed is false even though it's been disposed, or if the disposal request - // comes in after this line, we simply run the minor risk of having m_registeredCallbacksLists reinitialized + // If there's a race and _disposed is false even though it's been disposed, or if the disposal request + // comes in after this line, we simply run the minor risk of having _registeredCallbacksLists reinitialized // (after it was cleared to null during Dispose). - if (m_disposed) + if (_disposed) return new CancellationTokenRegistration(); int myIndex = Environment.CurrentManagedThreadId % s_nLists; @@ -639,11 +575,11 @@ internal static CancellationTokenSource InternalGetStaticSource(bool set) new CancellationCallbackInfo(callback, stateForCallback, executionContext, this); //allocate the callback list array - var registeredCallbacksLists = m_registeredCallbacksLists; + var registeredCallbacksLists = _registeredCallbacksLists; if (registeredCallbacksLists == null) { SparselyPopulatedArray[] list = new SparselyPopulatedArray[s_nLists]; - registeredCallbacksLists = Interlocked.CompareExchange(ref m_registeredCallbacksLists, list, null); + registeredCallbacksLists = Interlocked.CompareExchange(ref _registeredCallbacksLists, list, null); if (registeredCallbacksLists == null) registeredCallbacksLists = list; } @@ -681,29 +617,22 @@ internal static CancellationTokenSource InternalGetStaticSource(bool set) return new CancellationTokenRegistration(); } - /// - /// - /// private void NotifyCancellation(bool throwOnFirstException) { - // fast-path test to check if Notify has been called previously - if (IsCancellationRequested) - return; - // If we're the first to signal cancellation, do the main extra work. - if (Interlocked.CompareExchange(ref m_state, NOTIFYING, NOT_CANCELED) == NOT_CANCELED) + if (!IsCancellationRequested && Interlocked.CompareExchange(ref _state, NotifyingState, NotCanceledState) == NotCanceledState) { // Dispose of the timer, if any. Dispose may be running concurrently here, but Timer.Dispose is thread-safe. - m_timer?.Dispose(); + _timer?.Dispose(); // Record the threadID being used for running the callbacks. ThreadIDExecutingCallbacks = Environment.CurrentManagedThreadId; // 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 + // be running concurrently, in which case either it'll have set _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, // leaving cleanup to finalization. - m_kernelEvent?.Set(); // update the MRE value. + _kernelEvent?.Set(); // update the MRE value. // - late enlisters to the Canceled event will have their callbacks called immediately in the Register() methods. // - Callbacks are not called inside a lock. @@ -728,13 +657,13 @@ private void ExecuteCallbackHandlers(bool throwOnFirstException) // Design decision: call the delegates in LIFO order so that callbacks fire 'deepest first'. // This is intended to help with nesting scenarios so that child enlisters cancel before their parents. LowLevelListWithIList exceptionList = null; - SparselyPopulatedArray[] callbackLists = m_registeredCallbacksLists; + SparselyPopulatedArray[] callbackLists = _registeredCallbacksLists; // If there are no callbacks to run, we can safely exit. Any race conditions to lazy initialize it // will see IsCancellationRequested and will then run the callback themselves. if (callbackLists == null) { - Interlocked.Exchange(ref m_state, NOTIFYINGCOMPLETE); + Interlocked.Exchange(ref _state, NotifyingCompleteState); return; } @@ -758,8 +687,8 @@ private void ExecuteCallbackHandlers(bool throwOnFirstException) // 3. execute the callback // re:#2 we do the remove on the syncCtx so that we can be sure we have control of the syncCtx before // grabbing the callback. This prevents a deadlock if ctr.Dispose() might run on the syncCtx too. - m_executingCallback = currArrayFragment[i]; - if (m_executingCallback != null) + _executingCallback = currArrayFragment[i]; + if (_executingCallback != null) { //Transition to the target sync context (if necessary), and continue our work there. CancellationCallbackCoreWorkArguments args = new CancellationCallbackCoreWorkArguments(currArrayFragment, i); @@ -768,7 +697,7 @@ private void ExecuteCallbackHandlers(bool throwOnFirstException) // We assume that syncCtx.Send() has forwarded on user exceptions when appropriate. try { - var wsc = m_executingCallback as CancellationCallbackInfo.WithSyncContext; + var wsc = _executingCallback as CancellationCallbackInfo.WithSyncContext; if (wsc != null) { Debug.Assert(wsc.TargetSyncContext != null, "Should only have derived CCI if non-null SyncCtx"); @@ -801,14 +730,14 @@ private void ExecuteCallbackHandlers(bool throwOnFirstException) } finally { - m_state = NOTIFYINGCOMPLETE; - m_executingCallback = null; + _state = NotifyingCompleteState; + _executingCallback = null; Interlocked.MemoryBarrier(); // for safety, prevent reorderings crossing this point and seeing inconsistent state. } if (exceptionList != null) { - Debug.Assert(exceptionList.Count > 0, "Expected exception count > 0"); + Debug.Assert(exceptionList.Count > 0, $"Expected {exceptionList.Count} > 0"); throw new AggregateException(exceptionList); } } @@ -823,15 +752,14 @@ private void CancellationCallbackCoreWork(CancellationCallbackCoreWorkArguments { // remove the intended callback..and ensure that it worked. // otherwise the callback has disappeared in the interim and we can immediately return. - CancellationCallbackInfo callback = args.m_currArrayFragment.SafeAtomicRemove(args.m_currArrayIndex, m_executingCallback); - if (callback == m_executingCallback) + CancellationCallbackInfo callback = args._currArrayFragment.SafeAtomicRemove(args._currArrayIndex, _executingCallback); + if (callback == _executingCallback) { callback.CancellationTokenSource.ThreadIDExecutingCallbacks = Environment.CurrentManagedThreadId; callback.ExecuteCallback(); } } - /// /// Creates a CancellationTokenSource that will be in the canceled state /// when any of the source tokens are in the canceled state. @@ -906,7 +834,7 @@ internal Linked1CancellationTokenSource(CancellationToken token1) protected override void Dispose(bool disposing) { - if (!disposing || m_disposed) return; + if (!disposing || _disposed) return; _reg1.Dispose(); base.Dispose(disposing); } @@ -925,7 +853,7 @@ internal Linked2CancellationTokenSource(CancellationToken token1, CancellationTo protected override void Dispose(bool disposing) { - if (!disposing || m_disposed) return; + if (!disposing || _disposed) return; _reg1.Dispose(); _reg2.Dispose(); base.Dispose(disposing); @@ -936,17 +864,17 @@ private sealed class LinkedNCancellationTokenSource : CancellationTokenSource { internal static readonly Action s_linkedTokenCancelDelegate = s => ((CancellationTokenSource)s).NotifyCancellation(throwOnFirstException: false); // skip ThrowIfDisposed() check in Cancel() - private CancellationTokenRegistration[] m_linkingRegistrations; + private CancellationTokenRegistration[] _linkingRegistrations; internal LinkedNCancellationTokenSource(params CancellationToken[] tokens) { - m_linkingRegistrations = new CancellationTokenRegistration[tokens.Length]; + _linkingRegistrations = new CancellationTokenRegistration[tokens.Length]; for (int i = 0; i < tokens.Length; i++) { if (tokens[i].CanBeCanceled) { - m_linkingRegistrations[i] = tokens[i].InternalRegisterWithoutEC(s_linkedTokenCancelDelegate, this); + _linkingRegistrations[i] = tokens[i].InternalRegisterWithoutEC(s_linkedTokenCancelDelegate, this); } // Empty slots in the array will be default(CancellationTokenRegistration), which are nops to Dispose. // Based on usage patterns, such occurrences should also be rare, such that it's not worth resizing @@ -956,13 +884,13 @@ internal LinkedNCancellationTokenSource(params CancellationToken[] tokens) protected override void Dispose(bool disposing) { - if (!disposing || m_disposed) + if (!disposing || _disposed) return; - CancellationTokenRegistration[] linkingRegistrations = m_linkingRegistrations; + CancellationTokenRegistration[] linkingRegistrations = _linkingRegistrations; if (linkingRegistrations != null) { - m_linkingRegistrations = null; // release for GC once we're done enumerating + _linkingRegistrations = null; // release for GC once we're done enumerating for (int i = 0; i < linkingRegistrations.Length; i++) { linkingRegistrations[i].Dispose(); @@ -980,13 +908,13 @@ protected override void Dispose(bool disposing) // Helper struct for passing data to the target sync context internal struct CancellationCallbackCoreWorkArguments { - internal SparselyPopulatedArrayFragment m_currArrayFragment; - internal int m_currArrayIndex; + internal SparselyPopulatedArrayFragment _currArrayFragment; + internal int _currArrayIndex; public CancellationCallbackCoreWorkArguments(SparselyPopulatedArrayFragment currArrayFragment, int currArrayIndex) { - m_currArrayFragment = currArrayFragment; - m_currArrayIndex = currArrayIndex; + _currArrayFragment = currArrayFragment; + _currArrayIndex = currArrayIndex; } } @@ -1078,8 +1006,8 @@ private static void ExecutionContextCallback(object obj) /// The kind of elements contained within. internal class SparselyPopulatedArray where T : class { - private readonly SparselyPopulatedArrayFragment m_head; - private volatile SparselyPopulatedArrayFragment m_tail; + private readonly SparselyPopulatedArrayFragment _head; + private volatile SparselyPopulatedArrayFragment _tail; /// /// Allocates a new array with the given initial size. @@ -1087,7 +1015,7 @@ internal class SparselyPopulatedArray where T : class /// How many array slots to pre-allocate. internal SparselyPopulatedArray(int initialSize) { - m_head = m_tail = new SparselyPopulatedArrayFragment(initialSize); + _head = _tail = new SparselyPopulatedArrayFragment(initialSize); } #if DEBUG @@ -1097,7 +1025,7 @@ internal SparselyPopulatedArray(int initialSize) /// internal SparselyPopulatedArrayFragment Head { - get { return m_head; } + get { return _head; } } #endif @@ -1106,7 +1034,7 @@ internal SparselyPopulatedArrayFragment Head /// internal SparselyPopulatedArrayFragment Tail { - get { return m_tail; } + get { return _tail; } } /// @@ -1120,30 +1048,30 @@ internal SparselyPopulatedArrayAddInfo Add(T element) while (true) { // Get the tail, and ensure it's up to date. - SparselyPopulatedArrayFragment tail = m_tail; - while (tail.m_next != null) - m_tail = (tail = tail.m_next); + SparselyPopulatedArrayFragment tail = _tail; + while (tail._next != null) + _tail = (tail = tail._next); // Search for a free index, starting from the tail. SparselyPopulatedArrayFragment curr = tail; while (curr != null) { const int RE_SEARCH_THRESHOLD = -10; // Every 10 skips, force a search. - if (curr.m_freeCount < 1) - --curr.m_freeCount; + if (curr._freeCount < 1) + --curr._freeCount; - if (curr.m_freeCount > 0 || curr.m_freeCount < RE_SEARCH_THRESHOLD) + if (curr._freeCount > 0 || curr._freeCount < RE_SEARCH_THRESHOLD) { int c = curr.Length; // We'll compute a start offset based on how many free slots we think there // are. This optimizes for ordinary the LIFO unregistration pattern, and is // far from perfect due to the non-threadsafe ++ and -- of the free counter. - int start = ((c - curr.m_freeCount) % c); + int start = ((c - curr._freeCount) % c); if (start < 0) { start = 0; - curr.m_freeCount--; // Too many free elements; fix up. + curr._freeCount--; // Too many free elements; fix up. } Debug.Assert(start >= 0 && start < c, "start is outside of bounds"); @@ -1152,29 +1080,29 @@ internal SparselyPopulatedArrayAddInfo Add(T element) { // 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"); + Debug.Assert(tryIndex >= 0 && tryIndex < curr._elements.Length, "tryIndex is outside of bounds"); - if (curr.m_elements[tryIndex] == null && Interlocked.CompareExchange(ref curr.m_elements[tryIndex], element, null) == null) + if (curr._elements[tryIndex] == null && Interlocked.CompareExchange(ref curr._elements[tryIndex], element, null) == null) { // We adjust the free count by --. Note: if this drops to 0, we will skip // the fragment on the next search iteration. Searching threads will -- the // count and force a search every so often, just in case fragmentation occurs. - int newFreeCount = curr.m_freeCount - 1; - curr.m_freeCount = newFreeCount > 0 ? newFreeCount : 0; + int newFreeCount = curr._freeCount - 1; + curr._freeCount = newFreeCount > 0 ? newFreeCount : 0; return new SparselyPopulatedArrayAddInfo(curr, tryIndex); } } } - curr = curr.m_prev; + curr = curr._prev; } // If we got here, we need to add a new chunk to the tail and try again. SparselyPopulatedArrayFragment newTail = new SparselyPopulatedArrayFragment( - tail.m_elements.Length == 4096 ? 4096 : tail.m_elements.Length * 2, tail); - if (Interlocked.CompareExchange(ref tail.m_next, newTail, null) == null) + tail._elements.Length == 4096 ? 4096 : tail._elements.Length * 2, tail); + if (Interlocked.CompareExchange(ref tail._next, newTail, null) == null) { - m_tail = newTail; + _tail = newTail; } } } @@ -1186,25 +1114,25 @@ internal SparselyPopulatedArrayAddInfo Add(T element) /// internal struct SparselyPopulatedArrayAddInfo where T : class { - private SparselyPopulatedArrayFragment m_source; - private int m_index; + private SparselyPopulatedArrayFragment _source; + private int _index; internal SparselyPopulatedArrayAddInfo(SparselyPopulatedArrayFragment source, int index) { Debug.Assert(source != null); Debug.Assert(index >= 0 && index < source.Length); - m_source = source; - m_index = index; + _source = source; + _index = index; } internal SparselyPopulatedArrayFragment Source { - get { return m_source; } + get { return _source; } } internal int Index { - get { return m_index; } + get { return _index; } } } @@ -1214,10 +1142,10 @@ internal int Index /// The kind of elements contained within. internal class SparselyPopulatedArrayFragment where T : class { - internal readonly T[] m_elements; // The contents, sparsely populated (with nulls). - internal volatile int m_freeCount; // A hint of the number of free elements. - internal volatile SparselyPopulatedArrayFragment m_next; // The next fragment in the chain. - internal volatile SparselyPopulatedArrayFragment m_prev; // The previous fragment in the chain. + internal readonly T[] _elements; // The contents, sparsely populated (with nulls). + internal volatile int _freeCount; // A hint of the number of free elements. + internal volatile SparselyPopulatedArrayFragment _next; // The next fragment in the chain. + internal volatile SparselyPopulatedArrayFragment _prev; // The previous fragment in the chain. internal SparselyPopulatedArrayFragment(int size) : this(size, null) { @@ -1225,31 +1153,31 @@ internal SparselyPopulatedArrayFragment(int size) : this(size, null) internal SparselyPopulatedArrayFragment(int size, SparselyPopulatedArrayFragment prev) { - m_elements = new T[size]; - m_freeCount = size; - m_prev = prev; + _elements = new T[size]; + _freeCount = size; + _prev = prev; } internal T this[int index] { - get { return Volatile.Read(ref m_elements[index]); } + get { return Volatile.Read(ref _elements[index]); } } internal int Length { - get { return m_elements.Length; } + get { return _elements.Length; } } #if DEBUG // Used in DEBUG mode by CancellationTokenSource.CallbackCount internal SparselyPopulatedArrayFragment Next { - get { return m_next; } + get { return _next; } } #endif internal SparselyPopulatedArrayFragment Prev { - get { return m_prev; } + get { return _prev; } } // only removes the item at the specified index if it is still the expected one. @@ -1258,9 +1186,9 @@ internal SparselyPopulatedArrayFragment Prev // otherwise the remove did not occur. internal T SafeAtomicRemove(int index, T expectedElement) { - T prevailingValue = Interlocked.CompareExchange(ref m_elements[index], null, expectedElement); + T prevailingValue = Interlocked.CompareExchange(ref _elements[index], null, expectedElement); if (prevailingValue != null) - ++m_freeCount; + ++_freeCount; return prevailingValue; } } diff --git a/src/System.Private.CoreLib/src/System/Threading/SemaphoreSlim.cs b/src/System.Private.CoreLib/src/System/Threading/SemaphoreSlim.cs deleted file mode 100644 index 0fa2606025b..00000000000 --- a/src/System.Private.CoreLib/src/System/Threading/SemaphoreSlim.cs +++ /dev/null @@ -1,916 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ -// -// - -// -// A lightweight semahore class that contains the basic semaphore functions plus some useful functions like interrupt -// and wait handle exposing to allow waiting on multiple semaphores. -// -// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- - -using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Threading.Tasks; - -// The class will be part of the current System.Threading namespace - -namespace System.Threading -{ - /// - /// Limits the number of threads that can access a resource or pool of resources concurrently. - /// - /// - /// - /// The provides a lightweight semaphore class that doesn't - /// use Windows kernel semaphores. - /// - /// - /// All public and protected members of are thread-safe and may be used - /// concurrently from multiple threads, with the exception of Dispose, which - /// must only be used when all other operations on the have - /// completed. - /// - /// - [DebuggerDisplay("Current Count = {m_currentCount}")] - public class SemaphoreSlim : IDisposable - { - #region Private Fields - - // The semaphore count, initialized in the constructor to the initial value, every release call incremetns it - // and every wait call decrements it as long as its value is positive otherwise the wait will block. - // Its value must be between the maximum semaphore value and zero - private volatile int m_currentCount; - - // The maximum semaphore value, it is initialized to Int.MaxValue if the client didn't specify it. it is used - // to check if the count excceeded the maxi value or not. - private readonly int m_maxCount; - - // The number of synchronously waiting threads, it is set to zero in the constructor and increments before blocking the - // threading and decrements it back after that. It is used as flag for the release call to know if there are - // waiting threads in the monitor or not. - private volatile int m_waitCount; - - // Dummy object used to in lock statements to protect the semaphore count, wait handle and cancelation - private Lock m_lock; - private Condition m_condition; - - // Act as the semaphore wait handle, it's lazily initialized if needed, the first WaitHandle call initialize it - // and wait an release sets and resets it respectively as long as it is not null - private volatile ManualResetEvent m_waitHandle; - - // Head of list representing asynchronous waits on the semaphore. - private TaskNode m_asyncHead; - - // Tail of list representing asynchronous waits on the semaphore. - private TaskNode m_asyncTail; - - // A pre-completed task with Result==true - private static readonly Task s_trueTask = - new Task(false, true, (TaskCreationOptions)InternalTaskOptions.DoNotDispose, default(CancellationToken)); - // A pre-completed task with Result==false - private readonly static Task s_falseTask = - new Task(false, false, (TaskCreationOptions)InternalTaskOptions.DoNotDispose, default(CancellationToken)); - - // No maximum constant - private const int NO_MAXIMUM = int.MaxValue; - - // Task in a linked list of asynchronous waiters - private sealed class TaskNode : Task, IThreadPoolWorkItem - { - internal TaskNode Prev, Next; - internal TaskNode() : base() { } - - void IThreadPoolWorkItem.ExecuteWorkItem() - { - bool setSuccessfully = TrySetResult(true); - Debug.Assert(setSuccessfully, "Should have been able to complete task"); - } - } - #endregion - - #region Public properties - - /// - /// Gets the current count of the . - /// - /// The current count of the . - public int CurrentCount - { - get { return m_currentCount; } - } - - /// - /// Returns a that can be used to wait on the semaphore. - /// - /// A that can be used to wait on the - /// semaphore. - /// - /// A successful wait on the does not imply a successful wait on - /// the itself, nor does it decrement the semaphore's - /// count. exists to allow a thread to block waiting on multiple - /// semaphores, but such a wait should be followed by a true wait on the target semaphore. - /// - /// The has been disposed. - public WaitHandle AvailableWaitHandle - { - get - { - CheckDispose(); - - // Return it directly if it is not null - if (m_waitHandle != null) - return m_waitHandle; - - //lock the count to avoid multiple threads initializing the handle if it is null - using (LockHolder.Hold(m_lock)) - { - if (m_waitHandle == null) - { - // The initial state for the wait handle is true if the count is greater than zero - // false otherwise - m_waitHandle = new ManualResetEvent(m_currentCount != 0); - } - } - return m_waitHandle; - } - } - - #endregion - - #region Constructors - /// - /// Initializes a new instance of the class, specifying - /// the initial number of requests that can be granted concurrently. - /// - /// The initial number of requests for the semaphore that can be granted - /// concurrently. - /// - /// is less than 0. - public SemaphoreSlim(int initialCount) - : this(initialCount, NO_MAXIMUM) - { - } - - /// - /// Initializes a new instance of the class, specifying - /// the initial and maximum number of requests that can be granted concurrently. - /// - /// The initial number of requests for the semaphore that can be granted - /// concurrently. - /// The maximum number of requests for the semaphore that can be granted - /// concurrently. - /// - /// is less than 0. -or- - /// is greater than . -or- - /// is less than 0. - public SemaphoreSlim(int initialCount, int maxCount) - { - if (initialCount < 0 || initialCount > maxCount) - { - throw new ArgumentOutOfRangeException( - nameof(initialCount), initialCount, SR.SemaphoreSlim_ctor_InitialCountWrong); - } - - //validate input - if (maxCount <= 0) - { - throw new ArgumentOutOfRangeException(nameof(maxCount), maxCount, SR.SemaphoreSlim_ctor_MaxCountWrong); - } - - m_maxCount = maxCount; - m_lock = new Lock(); - m_condition = new Condition(m_lock); - m_currentCount = initialCount; - } - - #endregion - - #region Methods - /// - /// Blocks the current thread until it can enter the . - /// - /// The current instance has already been - /// disposed. - public void Wait() - { - // Call wait with infinite timeout - Wait(Timeout.Infinite, new CancellationToken()); - } - - /// - /// Blocks the current thread until it can enter the , while observing a - /// . - /// - /// The token to - /// observe. - /// was - /// canceled. - /// The current instance has already been - /// disposed. - public void Wait(CancellationToken cancellationToken) - { - // Call wait with infinite timeout - Wait(Timeout.Infinite, cancellationToken); - } - - /// - /// Blocks the current thread until it can enter the , using a to measure the time interval. - /// - /// A that represents the number of milliseconds - /// to wait, or a that represents -1 milliseconds to wait indefinitely. - /// - /// true if the current thread successfully entered the ; - /// otherwise, false. - /// is a negative - /// number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater - /// than . - public bool Wait(TimeSpan timeout) - { - // Validate the timeout - long totalMilliseconds = (long)timeout.TotalMilliseconds; - if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue) - { - throw new System.ArgumentOutOfRangeException( - nameof(timeout), timeout, SR.SemaphoreSlim_Wait_TimeoutWrong); - } - - // Call wait with the timeout milliseconds - return Wait((int)timeout.TotalMilliseconds, new CancellationToken()); - } - - /// - /// Blocks the current thread until it can enter the , using a to measure the time interval, while observing a . - /// - /// A that represents the number of milliseconds - /// to wait, or a that represents -1 milliseconds to wait indefinitely. - /// - /// The to - /// observe. - /// true if the current thread successfully entered the ; - /// otherwise, false. - /// is a negative - /// number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater - /// than . - /// was canceled. - public bool Wait(TimeSpan timeout, CancellationToken cancellationToken) - { - // Validate the timeout - long totalMilliseconds = (long)timeout.TotalMilliseconds; - if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue) - { - throw new System.ArgumentOutOfRangeException( - nameof(timeout), timeout, SR.SemaphoreSlim_Wait_TimeoutWrong); - } - - // Call wait with the timeout milliseconds - return Wait((int)timeout.TotalMilliseconds, cancellationToken); - } - - /// - /// Blocks the current thread until it can enter the , using a 32-bit - /// signed integer to measure the time interval. - /// - /// The number of milliseconds to wait, or (-1) to wait indefinitely. - /// true if the current thread successfully entered the ; - /// otherwise, false. - /// is a - /// negative number other than -1, which represents an infinite time-out. - public bool Wait(int millisecondsTimeout) - { - return Wait(millisecondsTimeout, new CancellationToken()); - } - - - /// - /// Blocks the current thread until it can enter the , - /// using a 32-bit signed integer to measure the time interval, - /// while observing a . - /// - /// The number of milliseconds to wait, or (-1) to - /// wait indefinitely. - /// The to observe. - /// true if the current thread successfully entered the ; otherwise, false. - /// is a negative number other than -1, - /// which represents an infinite time-out. - /// was canceled. - public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken) - { - CheckDispose(); - - // Validate input - if (millisecondsTimeout < -1) - { - throw new ArgumentOutOfRangeException( - nameof(millisecondsTimeout), millisecondsTimeout, SR.SemaphoreSlim_Wait_TimeoutWrong); - } - - cancellationToken.ThrowIfCancellationRequested(); - - // Perf: Check the stack timeout parameter before checking the volatile count - if (millisecondsTimeout == 0 && m_currentCount == 0) - { - // Pessimistic fail fast, check volatile count outside lock (only when timeout is zero!) - return false; - } - - uint startTime = 0; - if (millisecondsTimeout != Timeout.Infinite && millisecondsTimeout > 0) - { - startTime = TimeoutHelper.GetTime(); - } - - bool waitSuccessful = false; - Task asyncWaitTask = null; - bool lockTaken = false; - - //Register for cancellation outside of the main lock. - //NOTE: Register/unregister inside the lock can deadlock as different lock acquisition orders could - // occur for (1)this.m_lockObj and (2)cts.internalLock - CancellationTokenRegistration cancellationTokenRegistration = cancellationToken.InternalRegisterWithoutEC(s_cancellationTokenCanceledEventHandler, this); - try - { - // Perf: first spin wait for the count to be positive, but only up to the first planned yield. - // This additional amount of spinwaiting in addition - // to Monitor.Enter()’s spinwaiting has shown measurable perf gains in test scenarios. - // - SpinWait spin = new SpinWait(); - while (m_currentCount == 0 && !spin.NextSpinWillYield) - { - spin.SpinOnce(); - } - // entering the lock and incrementing waiters must not suffer a thread-abort, else we cannot - // clean up m_waitCount correctly, which may lead to deadlock due to non-woken waiters. - try { } - finally - { - m_lock.Acquire(); - lockTaken = true; - if (lockTaken) - { - m_waitCount++; - } - } - - // If there are any async waiters, for fairness we'll get in line behind - // then by translating our synchronous wait into an asynchronous one that we - // then block on (once we've released the lock). - if (m_asyncHead != null) - { - 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. - else - { - // If the count > 0 we are good to move on. - // If not, then wait if we were given allowed some wait duration - - OperationCanceledException oce = null; - - if (m_currentCount == 0) - { - if (millisecondsTimeout == 0) - { - return false; - } - - // Prepare for the main wait... - // wait until the count become greater than zero or the timeout is expired - try - { - waitSuccessful = WaitUntilCountOrTimeout(millisecondsTimeout, startTime, cancellationToken); - } - catch (OperationCanceledException e) { oce = e; } - } - - // Now try to acquire. We prioritize acquisition over cancellation/timeout so that we don't - // lose any counts when there are asynchronous waiters in the mix. Asynchronous waiters - // 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, - "If the wait was successful, there should be count available."); - if (m_currentCount > 0) - { - waitSuccessful = true; - m_currentCount--; - } - else if (oce != null) - { - throw oce; - } - - // Exposing wait handle which is lazily initialized if needed - if (m_waitHandle != null && m_currentCount == 0) - { - m_waitHandle.Reset(); - } - } - } - finally - { - // Release the lock - if (lockTaken) - { - m_waitCount--; - m_lock.Release(); - } - - // Unregister the cancellation callback. - cancellationTokenRegistration.Dispose(); - } - - // If we had to fall back to asynchronous waiting, block on it - // here now that we've released the lock, and return its - // result when available. Otherwise, this was a synchronous - // wait, and whether we successfully acquired the semaphore is - // stored in waitSuccessful. - - return (asyncWaitTask != null) ? asyncWaitTask.GetAwaiter().GetResult() : waitSuccessful; - } - - /// - /// Local helper function, waits on the monitor until the monitor recieves signal or the - /// timeout is expired - /// - /// The maximum timeout - /// The start ticks to calculate the elapsed time - /// The CancellationToken to observe. - /// true if the monitor recieved a signal, false if the timeout expired - private bool WaitUntilCountOrTimeout(int millisecondsTimeout, uint startTime, CancellationToken cancellationToken) - { - int remainingWaitMilliseconds = Timeout.Infinite; - - //Wait on the monitor as long as the count is zero - while (m_currentCount == 0) - { - // If cancelled, we throw. Trying to wait could lead to deadlock. - cancellationToken.ThrowIfCancellationRequested(); - - if (millisecondsTimeout != Timeout.Infinite) - { - remainingWaitMilliseconds = TimeoutHelper.UpdateTimeOut(startTime, millisecondsTimeout); - if (remainingWaitMilliseconds <= 0) - { - // The thread has expires its timeout - return false; - } - } - // ** the actual wait ** - if (!m_condition.Wait(remainingWaitMilliseconds)) - { - return false; - } - } - - return true; - } - - /// - /// Asynchronously waits to enter the . - /// - /// A task that will complete when the semaphore has been entered. - public Task WaitAsync() - { - return WaitAsync(Timeout.Infinite, default(CancellationToken)); - } - - /// - /// Asynchronously waits to enter the , while observing a - /// . - /// - /// A task that will complete when the semaphore has been entered. - /// - /// The token to observe. - /// - /// - /// The current instance has already been disposed. - /// - public Task WaitAsync(CancellationToken cancellationToken) - { - return WaitAsync(Timeout.Infinite, cancellationToken); - } - - /// - /// Asynchronously waits to enter the , - /// using a 32-bit signed integer to measure the time interval. - /// - /// - /// The number of milliseconds to wait, or (-1) to wait indefinitely. - /// - /// - /// A task that will complete with a result of true if the current thread successfully entered - /// the , otherwise with a result of false. - /// - /// The current instance has already been - /// disposed. - /// is a negative number other than -1, - /// which represents an infinite time-out. - /// - public Task WaitAsync(int millisecondsTimeout) - { - return WaitAsync(millisecondsTimeout, default(CancellationToken)); - } - - /// - /// Asynchronously waits to enter the , using a to measure the time interval, while observing a - /// . - /// - /// - /// A that represents the number of milliseconds - /// to wait, or a that represents -1 milliseconds to wait indefinitely. - /// - /// - /// The token to observe. - /// - /// - /// A task that will complete with a result of true if the current thread successfully entered - /// the , otherwise with a result of false. - /// - /// - /// The current instance has already been disposed. - /// - /// - /// is a negative number other than -1 milliseconds, which represents - /// an infinite time-out -or- timeout is greater than . - /// - public Task WaitAsync(TimeSpan timeout) - { - return WaitAsync(timeout, default(CancellationToken)); - } - - /// - /// Asynchronously waits to enter the , using a to measure the time interval. - /// - /// - /// A that represents the number of milliseconds - /// to wait, or a that represents -1 milliseconds to wait indefinitely. - /// - /// - /// A task that will complete with a result of true if the current thread successfully entered - /// the , otherwise with a result of false. - /// - /// - /// is a negative number other than -1 milliseconds, which represents - /// an infinite time-out -or- timeout is greater than . - /// - public Task WaitAsync(TimeSpan timeout, CancellationToken cancellationToken) - { - // Validate the timeout - long totalMilliseconds = (long)timeout.TotalMilliseconds; - if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue) - { - throw new System.ArgumentOutOfRangeException( - nameof(timeout), timeout, SR.SemaphoreSlim_Wait_TimeoutWrong); - } - - // Call wait with the timeout milliseconds - return WaitAsync((int)timeout.TotalMilliseconds, cancellationToken); - } - - /// - /// Asynchronously waits to enter the , - /// using a 32-bit signed integer to measure the time interval, - /// while observing a . - /// - /// - /// The number of milliseconds to wait, or (-1) to wait indefinitely. - /// - /// The to observe. - /// - /// A task that will complete with a result of true if the current thread successfully entered - /// the , otherwise with a result of false. - /// - /// The current instance has already been - /// disposed. - /// is a negative number other than -1, - /// which represents an infinite time-out. - /// - public Task WaitAsync(int millisecondsTimeout, CancellationToken cancellationToken) - { - CheckDispose(); - - // Validate input - if (millisecondsTimeout < -1) - { - throw new ArgumentOutOfRangeException( - nameof(millisecondsTimeout), millisecondsTimeout, SR.SemaphoreSlim_Wait_TimeoutWrong); - } - - // Bail early for cancellation - if (cancellationToken.IsCancellationRequested) - return Task.FromCancellation(cancellationToken); - - using (LockHolder.Hold(m_lock)) - { - // If there are counts available, allow this waiter to succeed. - if (m_currentCount > 0) - { - --m_currentCount; - if (m_waitHandle != null && m_currentCount == 0) m_waitHandle.Reset(); - return s_trueTask; - } - else if (millisecondsTimeout == 0) - { - // 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. - else - { - Debug.Assert(m_currentCount == 0, "m_currentCount should never be negative"); - var asyncWaiter = CreateAndAddAsyncWaiter(); - return (millisecondsTimeout == Timeout.Infinite && !cancellationToken.CanBeCanceled) ? - asyncWaiter : - WaitUntilCountOrTimeoutAsync(asyncWaiter, millisecondsTimeout, cancellationToken); - } - } - } - - /// Creates a new task and stores it into the async waiters list. - /// The created task. - private TaskNode CreateAndAddAsyncWaiter() - { - Debug.Assert(m_lock.IsAcquired, "Requires the lock be held"); - - // Create the task - var task = new TaskNode(); - - // Add it to the linked list - if (m_asyncHead == null) - { - Debug.Assert(m_asyncTail == null, "If head is null, so too should be tail"); - m_asyncHead = task; - m_asyncTail = task; - } - else - { - Debug.Assert(m_asyncTail != null, "If head is not null, neither should be tail"); - m_asyncTail.Next = task; - task.Prev = m_asyncTail; - m_asyncTail = task; - } - - // Hand it back - return task; - } - - /// Removes the waiter task from the linked list. - /// The task to remove. - /// true if the waiter was in the list; otherwise, false. - private bool RemoveAsyncWaiter(TaskNode task) - { - Debug.Assert(task != null, "Expected non-null task"); - Debug.Assert(m_lock.IsAcquired, "Requires the lock be held"); - - // Is the task in the list? To be in the list, either it's the head or it has a predecessor that's in the list. - bool wasInList = m_asyncHead == task || task.Prev != null; - - // Remove it from the linked list - if (task.Next != null) task.Next.Prev = task.Prev; - if (task.Prev != null) task.Prev.Next = task.Next; - if (m_asyncHead == task) m_asyncHead = task.Next; - if (m_asyncTail == task) m_asyncTail = task.Prev; - Debug.Assert((m_asyncHead == null) == (m_asyncTail == null), "Head is null iff tail is null"); - - // Make sure not to leak - task.Next = task.Prev = null; - - // Return whether the task was in the list - return wasInList; - } - - /// Performs the asynchronous wait. - /// The timeout. - /// The cancellation token. - /// The task to return to the caller. - private async Task WaitUntilCountOrTimeoutAsync(TaskNode asyncWaiter, int millisecondsTimeout, CancellationToken cancellationToken) - { - Debug.Assert(asyncWaiter != null, "Waiter should have been constructed"); - Debug.Assert(m_lock.IsAcquired, "Requires the lock be held"); - - // Wait until either the task is completed, timeout occurs, or cancellation is requested. - // We need to ensure that the Task.Delay task is appropriately cleaned up if the await - // completes due to the asyncWaiter completing, so we use our own token that we can explicitly - // cancel, and we chain the caller's supplied token into it. - using (var cts = cancellationToken.CanBeCanceled ? - CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, default(CancellationToken)) : - new CancellationTokenSource()) - { - var waitCompleted = Task.WhenAny(asyncWaiter, Task.Delay(millisecondsTimeout, cts.Token)); - if (asyncWaiter == await waitCompleted.ConfigureAwait(false)) - { - cts.Cancel(); // ensure that the Task.Delay task is cleaned up - return true; // successfully acquired - } - } - - // If we get here, the wait has timed out or been canceled. - - // If the await completed synchronously, we still hold the lock. If it didn't, - // we no longer hold the lock. As such, acquire it. - using (LockHolder.Hold(m_lock)) - { - // Remove the task from the list. If we're successful in doing so, - // we know that no one else has tried to complete this waiter yet, - // so we can safely cancel or timeout. - if (RemoveAsyncWaiter(asyncWaiter)) - { - cancellationToken.ThrowIfCancellationRequested(); // cancellation occurred - return false; // timeout occurred - } - } - - // The waiter had already been removed, which means it's already completed or is about to - // complete, so let it, and don't return until it does. - return await asyncWaiter.ConfigureAwait(false); - } - - /// - /// Exits the once. - /// - /// The previous count of the . - /// The current instance has already been - /// disposed. - public int Release() - { - return Release(1); - } - - /// - /// Exits the a specified number of times. - /// - /// The number of times to exit the semaphore. - /// The previous count of the . - /// is less - /// than 1. - /// The has - /// already reached its maximum size. - /// The current instance has already been - /// disposed. - public int Release(int releaseCount) - { - CheckDispose(); - - // Validate input - if (releaseCount < 1) - { - throw new ArgumentOutOfRangeException( - nameof(releaseCount), releaseCount, SR.SemaphoreSlim_Release_CountWrong); - } - int returnCount; - - using (LockHolder.Hold(m_lock)) - { - // Read the m_currentCount into a local variable to avoid unnecessary volatile accesses inside the lock. - int currentCount = m_currentCount; - returnCount = currentCount; - - // If the release count would result exceeding the maximum count, throw SemaphoreFullException. - if (m_maxCount - currentCount < releaseCount) - { - throw new SemaphoreFullException(); - } - - // Increment the count by the actual release count - currentCount += releaseCount; - - // Signal to any synchronous waiters - int waitCount = m_waitCount; - - int waitersToNotify = Math.Min(releaseCount, waitCount); - for (int i = 0; i < waitersToNotify; i++) - { - m_condition.SignalOne(); - } - - // Now signal to any asynchronous waiters, if there are any. While we've already - // signaled the synchronous waiters, we still hold the lock, and thus - // they won't have had an opportunity to acquire this yet. So, when releasing - // asynchronous waiters, we assume that all synchronous waiters will eventually - // acquire the semaphore. That could be a faulty assumption if those synchronous - // waits are canceled, but the wait code path will handle that. - if (m_asyncHead != null) - { - Debug.Assert(m_asyncTail != null, "tail should not be null if head isn't null"); - int maxAsyncToRelease = currentCount - waitCount; - while (maxAsyncToRelease > 0 && m_asyncHead != null) - { - --currentCount; - --maxAsyncToRelease; - - // Get the next async waiter to release and queue it to be completed - var waiterTask = m_asyncHead; - RemoveAsyncWaiter(waiterTask); // ensures waiterTask.Next/Prev are null - QueueWaiterTask(waiterTask); - } - } - m_currentCount = currentCount; - - // Exposing wait handle if it is not null - if (m_waitHandle != null && returnCount == 0 && currentCount > 0) - { - m_waitHandle.Set(); - } - } - - // And return the count - return returnCount; - } - - /// - /// Queues a waiter task to the ThreadPool. We use this small helper method so that - /// the larger Release(count) method does not need to be SecuritySafeCritical. - /// - private static void QueueWaiterTask(TaskNode waiterTask) - { - ThreadPool.UnsafeQueueCustomWorkItem(waiterTask, forceGlobal: false); - } - - /// - /// Releases all resources used by the current instance of . - /// - /// - /// Unlike most of the members of , is not - /// thread-safe and may not be used concurrently with other members of this instance. - /// - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - /// - /// When overridden in a derived class, releases the unmanaged resources used by the - /// , and optionally releases the managed resources. - /// - /// true to release both managed and unmanaged resources; - /// false to release only unmanaged resources. - /// - /// Unlike most of the members of , is not - /// thread-safe and may not be used concurrently with other members of this instance. - /// - protected virtual void Dispose(bool disposing) - { - if (disposing) - { - if (m_waitHandle != null) - { - m_waitHandle.Dispose(); - m_waitHandle = null; - } - m_lock = null; - m_condition = null; - m_asyncHead = null; - m_asyncTail = null; - } - } - - - - /// - /// Private helper method to wake up waiters when a cancellationToken gets canceled. - /// - private static Action s_cancellationTokenCanceledEventHandler = new Action(CancellationTokenCanceledEventHandler); - private static void CancellationTokenCanceledEventHandler(object obj) - { - SemaphoreSlim semaphore = obj as SemaphoreSlim; - Debug.Assert(semaphore != null, "Expected a SemaphoreSlim"); - using (LockHolder.Hold(semaphore.m_lock)) - { - semaphore.m_condition.SignalAll(); //wake up all waiters. - } - } - - /// - /// Checks the dispose status by checking the lock object, if it is null means that object - /// has been disposed and throw ObjectDisposedException - /// - private void CheckDispose() - { - if (m_lock == null) - { - throw new ObjectDisposedException(null, SR.SemaphoreSlim_Disposed); - } - } - /// - /// local helper function to retrieve the exception string message from the resource file - /// - /// The key string - #endregion - } -} From 489106a15d399abfbb05351fe374dbef72e07977 Mon Sep 17 00:00:00 2001 From: Stephen Toub Date: Sat, 23 Jun 2018 10:20:29 -0400 Subject: [PATCH 30/69] Change string.Compare(...) == 0 occurrences to string.Equals(...) (#18616) Signed-off-by: dotnet-bot --- .../shared/System/Diagnostics/Tracing/EventSource.cs | 2 +- src/System.Private.CoreLib/shared/System/StringComparer.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventSource.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventSource.cs index f03a55fc102..e76653215e6 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventSource.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventSource.cs @@ -3254,7 +3254,7 @@ private static bool RemoveFirstArgIfRelatedActivityId(ref ParameterInfo[] args) { // If the first parameter is (case insensitive) 'relatedActivityId' then skip it. if (args.Length > 0 && args[0].ParameterType == typeof(Guid) && - string.Compare(args[0].Name, "relatedActivityId", StringComparison.OrdinalIgnoreCase) == 0) + string.Equals(args[0].Name, "relatedActivityId", StringComparison.OrdinalIgnoreCase)) { var newargs = new ParameterInfo[args.Length - 1]; Array.Copy(args, 1, newargs, 0, args.Length - 1); diff --git a/src/System.Private.CoreLib/shared/System/StringComparer.cs b/src/System.Private.CoreLib/shared/System/StringComparer.cs index 8cd8f3756e5..47731cb7826 100644 --- a/src/System.Private.CoreLib/shared/System/StringComparer.cs +++ b/src/System.Private.CoreLib/shared/System/StringComparer.cs @@ -293,7 +293,7 @@ public override bool Equals(string x, string y) { return false; } - return (string.Compare(x, y, StringComparison.OrdinalIgnoreCase) == 0); + return string.Equals(x, y, StringComparison.OrdinalIgnoreCase); } return x.Equals(y); } From 8df841f1c1235ba161efae95677b62443cb5736d Mon Sep 17 00:00:00 2001 From: John Doe Date: Thu, 28 Jun 2018 03:03:49 -0700 Subject: [PATCH 31/69] Typo (#6029) * aggresively -> aggressively * algortithm -> algorithm * anindex -> an index * antecendent -> antecedent * barnching -> branching * becauase -> because * behaivor -> behavior * Boolen -> Boolean * Browing -> Browsing * calander -> calendar --- .../src/Compiler/CompilerTypeSystemContext.cs | 2 +- .../shared/System/Globalization/HebrewCalendar.cs | 2 +- .../shared/System/Runtime/CompilerServices/TaskAwaiter.cs | 2 +- .../src/System/Threading/ManualResetEventSlim.cs | 2 +- src/System.Private.CoreLib/src/System/Threading/SpinLock.cs | 2 +- src/System.Private.Interop/src/Shared/StringPool.cs | 2 +- src/System.Private.Interop/src/Shared/__ComObject.cs | 2 +- .../WindowsRuntime/EventRegistrationTokenTable.cs | 2 +- .../Runtime/BindingFlagSupport/QueriedMemberList.cs | 4 ++-- .../src/Internal/Runtime/TypeLoader/CallingConventions.cs | 2 +- 10 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/ILCompiler.Compiler/src/Compiler/CompilerTypeSystemContext.cs b/src/ILCompiler.Compiler/src/Compiler/CompilerTypeSystemContext.cs index 4feb7a58243..9b822d89bc3 100644 --- a/src/ILCompiler.Compiler/src/Compiler/CompilerTypeSystemContext.cs +++ b/src/ILCompiler.Compiler/src/Compiler/CompilerTypeSystemContext.cs @@ -505,7 +505,7 @@ public SharedGenericsConfiguration() UniversalCanonGVMDepthHeuristic_NonCanonDepth = 2; UniversalCanonGVMDepthHeuristic_CanonDepth = 1; - // Unlike the GVM heuristics which are intended to kick in aggresively + // Unlike the GVM heuristics which are intended to kick in aggressively // this heuristic exists to make it so that a fair amount of generic // expansion is allowed. Numbers are chosen to allow a fairly large // amount of generic expansion before trimming. diff --git a/src/System.Private.CoreLib/shared/System/Globalization/HebrewCalendar.cs b/src/System.Private.CoreLib/shared/System/Globalization/HebrewCalendar.cs index 51749927022..06807811e2b 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/HebrewCalendar.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/HebrewCalendar.cs @@ -100,7 +100,7 @@ public class HebrewCalendar : Calendar A 99 means the year is not supported for translation. for convenience the table was defined for 750 year, but only 640 years are supported. (from 1583 to 2239) - the years before 1582 (starting of Georgian calander) + the years before 1582 (starting of Georgian calendar) and after 2239, are filled with 99. Greogrian January 1st falls usually in Tevet (4th month). Tevet has always 29 days. diff --git a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/TaskAwaiter.cs b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/TaskAwaiter.cs index 493d984155f..030278dcf50 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/TaskAwaiter.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/CompilerServices/TaskAwaiter.cs @@ -318,7 +318,7 @@ private static Action OutputWaitEtwEvents(Task task, Action continuation) innerTask.Id); // Ensure the continuation runs under the activity ID of the task that completed for the - // case the antecendent is a promise (in the other cases this is already the case). + // case the antecedent is a promise (in the other cases this is already the case). if (innerEtwLog.TasksSetActivityIds && (innerTask.Options & (TaskCreationOptions)InternalTaskOptions.PromiseTask) != 0) EventSource.SetCurrentThreadActivityId(TplEtwProvider.CreateGuidForTaskID(innerTask.Id), out prevActivityId); } diff --git a/src/System.Private.CoreLib/src/System/Threading/ManualResetEventSlim.cs b/src/System.Private.CoreLib/src/System/Threading/ManualResetEventSlim.cs index 8153e3f907f..faa5f2482a5 100644 --- a/src/System.Private.CoreLib/src/System/Threading/ManualResetEventSlim.cs +++ b/src/System.Private.CoreLib/src/System/Threading/ManualResetEventSlim.cs @@ -185,7 +185,7 @@ public ManualResetEventSlim() /// /// Initializes a new instance of the - /// class with a Boolen value indicating whether to set the intial state to signaled. + /// class with a Boolean value indicating whether to set the intial state to signaled. /// /// true to set the initial state signaled; false to set the initial state /// to nonsignaled. diff --git a/src/System.Private.CoreLib/src/System/Threading/SpinLock.cs b/src/System.Private.CoreLib/src/System/Threading/SpinLock.cs index 1c6c570b1f9..7f3cb120ba4 100644 --- a/src/System.Private.CoreLib/src/System/Threading/SpinLock.cs +++ b/src/System.Private.CoreLib/src/System/Threading/SpinLock.cs @@ -541,7 +541,7 @@ public void Exit() public void Exit(bool useMemoryBarrier) { // This is the fast path for the thread tracking is diabled and not to use memory barrier, otherwise go to the slow path - // The reason not to add else statement if the usememorybarrier is that it will add more barnching in the code and will prevent + // The reason not to add else statement if the usememorybarrier is that it will add more branching in the code and will prevent // method inlining, so this is optimized for useMemoryBarrier=false and Exit() overload optimized for useMemoryBarrier=true. int tmpOwner = m_owner; if ((tmpOwner & LOCK_ID_DISABLE_MASK) != 0 & !useMemoryBarrier) diff --git a/src/System.Private.Interop/src/Shared/StringPool.cs b/src/System.Private.Interop/src/Shared/StringPool.cs index d78fdedd7a5..eea2db4a666 100644 --- a/src/System.Private.Interop/src/Shared/StringPool.cs +++ b/src/System.Private.Interop/src/Shared/StringPool.cs @@ -19,7 +19,7 @@ namespace System.Runtime.InteropServices /// Functions: /// 1. GetString converts compressed string represented by an index to original System.String /// 2. StableStringHash computes hash code without decoding to System.String - /// 3. IsStringEqual compares compressed string represented by anindex with System.String + /// 3. IsStringEqual compares compressed string represented by an index with System.String /// /// TODO: /// 1. More string reuse diff --git a/src/System.Private.Interop/src/Shared/__ComObject.cs b/src/System.Private.Interop/src/Shared/__ComObject.cs index b68a81e0b13..0efd00ae2b5 100644 --- a/src/System.Private.Interop/src/Shared/__ComObject.cs +++ b/src/System.Private.Interop/src/Shared/__ComObject.cs @@ -1174,7 +1174,7 @@ internal ComObjectFlags Flags /// /// Slow path of QueryInterface that does not look at any cache. - /// NOTE: MethodImpl(NoInlining) is necessary becauase Bartok is trying to be "helpful" by inlining + /// NOTE: MethodImpl(NoInlining) is necessary because Bartok is trying to be "helpful" by inlining /// these calls while in other cases it does not inline when it should. /// [MethodImpl(MethodImplOptions.NoInlining)] diff --git a/src/System.Private.Interop/src/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationTokenTable.cs b/src/System.Private.Interop/src/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationTokenTable.cs index c89fe9e292d..002bdf888e0 100644 --- a/src/System.Private.Interop/src/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationTokenTable.cs +++ b/src/System.Private.Interop/src/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationTokenTable.cs @@ -185,7 +185,7 @@ public void RemoveEventHandler(EventRegistrationToken token) public void RemoveEventHandler(T handler) { - // To match the Windows Runtime behaivor when adding a null handler, removing one is a no-op + // To match the Windows Runtime behavior when adding a null handler, removing one is a no-op if (handler == null) { return; diff --git a/src/System.Private.Reflection.Core/src/System/Reflection/Runtime/BindingFlagSupport/QueriedMemberList.cs b/src/System.Private.Reflection.Core/src/System/Reflection/Runtime/BindingFlagSupport/QueriedMemberList.cs index c8e7d3a2367..2da7ffe58cf 100644 --- a/src/System.Private.Reflection.Core/src/System/Reflection/Runtime/BindingFlagSupport/QueriedMemberList.cs +++ b/src/System.Private.Reflection.Core/src/System/Reflection/Runtime/BindingFlagSupport/QueriedMemberList.cs @@ -30,13 +30,13 @@ private QueriedMemberList() _allFlagsThatMustMatch = new BindingFlags[Grow]; } - private QueriedMemberList(int totalCount, int declaredOnlyCount, M[] members, BindingFlags[] allFlagsThatMustMatch, RuntimeTypeInfo typeThatBlockedBrowing) + private QueriedMemberList(int totalCount, int declaredOnlyCount, M[] members, BindingFlags[] allFlagsThatMustMatch, RuntimeTypeInfo typeThatBlockedBrowsing) { _totalCount = totalCount; _declaredOnlyCount = declaredOnlyCount; _members = members; _allFlagsThatMustMatch = allFlagsThatMustMatch; - _typeThatBlockedBrowsing = typeThatBlockedBrowing; + _typeThatBlockedBrowsing = typeThatBlockedBrowsing; } /// diff --git a/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallingConventions.cs b/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallingConventions.cs index f40dedb4677..939017568e3 100644 --- a/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallingConventions.cs +++ b/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallingConventions.cs @@ -837,7 +837,7 @@ public unsafe int GetNextOffset() #if !_TARGET_X86_ numRegistersUsed++; #else - // DESKTOP BEHAVIOR is to do nothing here, as ret buf is never reached by the scan algortithm that walks backwards + // DESKTOP BEHAVIOR is to do nothing here, as ret buf is never reached by the scan algorithm that walks backwards // but in .NET Native, the x86 argument scan is a forward scan, so we need to skip the ret buf arg (which is always // on the stack) initialArgOffset = IntPtr.Size; From 1ad2cda8054c93194dd1cd39ed9ff87b24f86965 Mon Sep 17 00:00:00 2001 From: Petr Bred Date: Thu, 28 Jun 2018 16:10:12 +0300 Subject: [PATCH 32/69] [32BIT] Fix cpp codegen (#6028) - delete cpp64 arch Signed-off-by: Petr Bred --- src/Common/src/TypeSystem/Common/TargetDetails.cs | 3 --- src/ILCompiler/src/Program.cs | 2 -- 2 files changed, 5 deletions(-) diff --git a/src/Common/src/TypeSystem/Common/TargetDetails.cs b/src/Common/src/TypeSystem/Common/TargetDetails.cs index b7fc058bf62..b3be7aff09a 100644 --- a/src/Common/src/TypeSystem/Common/TargetDetails.cs +++ b/src/Common/src/TypeSystem/Common/TargetDetails.cs @@ -16,7 +16,6 @@ public enum TargetArchitecture ARM, ARMEL, ARM64, - Cpp64, X64, X86, Wasm32, @@ -91,7 +90,6 @@ public int PointerSize { case TargetArchitecture.ARM64: case TargetArchitecture.X64: - case TargetArchitecture.Cpp64: return 8; case TargetArchitecture.ARM: case TargetArchitecture.ARMEL: @@ -235,7 +233,6 @@ public LayoutInt GetObjectAlignment(LayoutInt fieldAlignment) return new LayoutInt(8); case TargetArchitecture.X64: case TargetArchitecture.ARM64: - case TargetArchitecture.Cpp64: return new LayoutInt(8); case TargetArchitecture.X86: case TargetArchitecture.Wasm32: diff --git a/src/ILCompiler/src/Program.cs b/src/ILCompiler/src/Program.cs index 235ebe64785..234ca9aed81 100644 --- a/src/ILCompiler/src/Program.cs +++ b/src/ILCompiler/src/Program.cs @@ -268,8 +268,6 @@ private int Run(string[] args) if (_isWasmCodegen) _targetArchitecture = TargetArchitecture.Wasm32; - else if (_isCppCodegen) - _targetArchitecture = TargetArchitecture.Cpp64; // // Initialize type system context From fb30371ea3318bb5e48212c23560664afa7bbe83 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michal=20Strehovsk=C3=BD?= Date: Fri, 29 Jun 2018 10:37:08 +0200 Subject: [PATCH 33/69] Make emission of managed resources controlled by a policy (#6031) This makes it possible for the compiler to filter what managed resources should be included in the executable image. I'm implementing a RESX blocking policy for framework assemblies. This will be used to block emission of framework exception messages. I'm planning to use this from the ProjectX side. Eventually, I would also like to expose this on the CoreRT compiler side. Submitting through git because it's just a better way to do development. I'll follow up on the TFS side and pipe it through NUTC. --- .../Compiler/AnalysisBasedMetadataManager.cs | 3 +- .../DependencyAnalysis/ResourceDataNode.cs | 5 + .../DependencyAnalysis/UtcNodeFactory.cs | 2 +- .../src/Compiler/EmptyMetadataManager.cs | 10 +- .../FrameworkStringResourceBlockingPolicy.cs | 91 +++++++++++++++++++ .../src/Compiler/GeneratingMetadataManager.cs | 4 +- .../ManifestResourceBlockingPolicy.cs | 21 +++++ .../src/Compiler/MetadataManager.cs | 9 +- .../NoManifestResourceBlockingPolicy.cs | 19 ++++ ...gPolicy.cs => NoMetadataBlockingPolicy.cs} | 2 +- .../Compiler/PrecomputedMetadataManager.cs | 5 +- .../src/Compiler/UsageBasedMetadataManager.cs | 5 +- .../src/ILCompiler.Compiler.csproj | 5 +- src/ILCompiler/src/Program.cs | 5 +- 14 files changed, 173 insertions(+), 13 deletions(-) create mode 100644 src/ILCompiler.Compiler/src/Compiler/FrameworkStringResourceBlockingPolicy.cs create mode 100644 src/ILCompiler.Compiler/src/Compiler/ManifestResourceBlockingPolicy.cs create mode 100644 src/ILCompiler.Compiler/src/Compiler/NoManifestResourceBlockingPolicy.cs rename src/ILCompiler.Compiler/src/Compiler/{NoBlockingPolicy.cs => NoMetadataBlockingPolicy.cs} (96%) diff --git a/src/ILCompiler.Compiler/src/Compiler/AnalysisBasedMetadataManager.cs b/src/ILCompiler.Compiler/src/Compiler/AnalysisBasedMetadataManager.cs index 64b2b33adfb..a484a4f9bee 100644 --- a/src/ILCompiler.Compiler/src/Compiler/AnalysisBasedMetadataManager.cs +++ b/src/ILCompiler.Compiler/src/Compiler/AnalysisBasedMetadataManager.cs @@ -27,13 +27,14 @@ public sealed class AnalysisBasedMetadataManager : GeneratingMetadataManager, IC public AnalysisBasedMetadataManager( CompilerTypeSystemContext typeSystemContext, MetadataBlockingPolicy blockingPolicy, + ManifestResourceBlockingPolicy resourceBlockingPolicy, string logFile, StackTraceEmissionPolicy stackTracePolicy, IEnumerable modulesWithMetadata, IEnumerable> reflectableTypes, IEnumerable> reflectableMethods, IEnumerable> reflectableFields) - : base(typeSystemContext, blockingPolicy, logFile, stackTracePolicy) + : base(typeSystemContext, blockingPolicy, resourceBlockingPolicy, logFile, stackTracePolicy) { _modulesWithMetadata = new List(modulesWithMetadata); diff --git a/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ResourceDataNode.cs b/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ResourceDataNode.cs index cc9dd6a2ce0..683343ffeb2 100644 --- a/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ResourceDataNode.cs +++ b/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/ResourceDataNode.cs @@ -98,6 +98,11 @@ public IReadOnlyList GetOrCreateIndexData(NodeFactory factory } string resourceName = module.MetadataReader.GetString(resource.Name); + + // Check if emitting the manifest resource is blocked by policy. + if (factory.MetadataManager.IsManifestResourceBlocked(module, resourceName)) + continue; + string assemblyName = module.GetName().FullName; BlobReader reader = resourceDirectory.GetReader((int)resource.Offset, resourceDirectory.Length - (int)resource.Offset); int length = (int)reader.ReadUInt32(); diff --git a/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/UtcNodeFactory.cs b/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/UtcNodeFactory.cs index 490fcf30925..f9226fe986c 100644 --- a/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/UtcNodeFactory.cs +++ b/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/UtcNodeFactory.cs @@ -67,7 +67,7 @@ private static MetadataManager PickMetadataManager(CompilerTypeSystemContext con } else { - return new PrecomputedMetadataManager(compilationModuleGroup, context, FindMetadataDescribingModuleInInputSet(inputModules), inputModules, inputMetadataOnlyAssemblies, ReadBytesFromFile(metadataFile), new UtcStackTraceEmissionPolicy()); + return new PrecomputedMetadataManager(compilationModuleGroup, context, FindMetadataDescribingModuleInInputSet(inputModules), inputModules, inputMetadataOnlyAssemblies, ReadBytesFromFile(metadataFile), new UtcStackTraceEmissionPolicy(), new NoManifestResourceBlockingPolicy()); } } diff --git a/src/ILCompiler.Compiler/src/Compiler/EmptyMetadataManager.cs b/src/ILCompiler.Compiler/src/Compiler/EmptyMetadataManager.cs index 2ae05366914..5217ec93584 100644 --- a/src/ILCompiler.Compiler/src/Compiler/EmptyMetadataManager.cs +++ b/src/ILCompiler.Compiler/src/Compiler/EmptyMetadataManager.cs @@ -17,7 +17,7 @@ public class EmptyMetadataManager : MetadataManager public override bool SupportsReflection => false; public EmptyMetadataManager(CompilerTypeSystemContext typeSystemContext) - : base(typeSystemContext, new FullyBlockedMetadataPolicy()) + : base(typeSystemContext, new FullyBlockedMetadataPolicy(), new FullyBlockedManifestResourcePolicy()) { } @@ -108,5 +108,13 @@ public override bool IsBlocked(FieldDesc field) return true; } } + + private sealed class FullyBlockedManifestResourcePolicy : ManifestResourceBlockingPolicy + { + public override bool IsManifestResourceBlocked(ModuleDesc module, string resourceName) + { + return true; + } + } } } diff --git a/src/ILCompiler.Compiler/src/Compiler/FrameworkStringResourceBlockingPolicy.cs b/src/ILCompiler.Compiler/src/Compiler/FrameworkStringResourceBlockingPolicy.cs new file mode 100644 index 00000000000..dd53aa02425 --- /dev/null +++ b/src/ILCompiler.Compiler/src/Compiler/FrameworkStringResourceBlockingPolicy.cs @@ -0,0 +1,91 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .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.Metadata; +using System.Reflection.PortableExecutable; + +using Internal.TypeSystem; +using Internal.TypeSystem.Ecma; + +namespace ILCompiler +{ + /// + /// A resource blocking policy that blocks RESX resources in framework assemblies. + /// This is useful for size-conscious scenarios where the conveniece of having + /// proper exception messages in framework-throw exceptions is not important. + /// + public sealed class FrameworkStringResourceBlockingPolicy : ManifestResourceBlockingPolicy + { + public override bool IsManifestResourceBlocked(ModuleDesc module, string resourceName) + { + // The embedded RESX files all have names that end with .resources, so use that as the initial filter. + if (!resourceName.EndsWith(".resources", StringComparison.OrdinalIgnoreCase)) + return false; + + // Assuming multimodule and non-ecma assemblies are unsupported + EcmaModule ecmaModule = (EcmaModule)module; + + // If this is not a framework assembly, no resources are blocked + if (!IsFrameworkAssembly(ecmaModule)) + return false; + + MetadataReader reader = ecmaModule.MetadataReader; + + // We have a resource in the framework assembly. Now check if this is a RESX + foreach (ManifestResourceHandle resourceHandle in reader.ManifestResources) + { + ManifestResource resource = reader.GetManifestResource(resourceHandle); + if (reader.StringComparer.Equals(resource.Name, resourceName) && + resource.Implementation.IsNil) + { + PEMemoryBlock resourceDirectory = + ecmaModule.PEReader.GetSectionData(ecmaModule.PEReader.PEHeaders.CorHeader.ResourcesDirectory.RelativeVirtualAddress); + BlobReader blob = resourceDirectory.GetReader((int)resource.Offset, resourceDirectory.Length - (int)resource.Offset); + int length = (int)blob.ReadUInt32(); + if (length > 4) + { + // Check for magic bytes that correspond to RESX + if (blob.ReadUInt32() == 0xBEEFCACE) + return true; + } + } + } + + return false; + } + + /// + /// Gets a value indicating whether '' is a framework assembly. + /// + private static bool IsFrameworkAssembly(EcmaModule module) + { + MetadataReader reader = module.MetadataReader; + + // We look for [assembly:AssemblyMetadata(".NETFrameworkAssembly", "")] + + foreach (CustomAttributeHandle attributeHandle in reader.GetAssemblyDefinition().GetCustomAttributes()) + { + if (!reader.GetAttributeNamespaceAndName(attributeHandle, out StringHandle namespaceHandle, out StringHandle nameHandle)) + continue; + + if (!reader.StringComparer.Equals(namespaceHandle, "System.Reflection") || + !reader.StringComparer.Equals(nameHandle, "AssemblyMetadataAttribute")) + continue; + + var attributeTypeProvider = new CustomAttributeTypeProvider(module); + CustomAttribute attribute = reader.GetCustomAttribute(attributeHandle); + CustomAttributeValue decodedAttribute = attribute.DecodeValue(attributeTypeProvider); + + if (decodedAttribute.FixedArguments.Length != 2) + continue; + + if (decodedAttribute.FixedArguments[0].Value is string s && s == ".NETFrameworkAssembly") + return true; + } + + return false; + } + } +} diff --git a/src/ILCompiler.Compiler/src/Compiler/GeneratingMetadataManager.cs b/src/ILCompiler.Compiler/src/Compiler/GeneratingMetadataManager.cs index c4216775c28..03879ed0b62 100644 --- a/src/ILCompiler.Compiler/src/Compiler/GeneratingMetadataManager.cs +++ b/src/ILCompiler.Compiler/src/Compiler/GeneratingMetadataManager.cs @@ -27,8 +27,8 @@ public abstract class GeneratingMetadataManager : MetadataManager protected readonly StackTraceEmissionPolicy _stackTraceEmissionPolicy; private readonly ModuleDesc _generatedAssembly; - public GeneratingMetadataManager(CompilerTypeSystemContext typeSystemContext, MetadataBlockingPolicy blockingPolicy, string logFile, StackTraceEmissionPolicy stackTracePolicy) - : base(typeSystemContext, blockingPolicy) + public GeneratingMetadataManager(CompilerTypeSystemContext typeSystemContext, MetadataBlockingPolicy blockingPolicy, ManifestResourceBlockingPolicy resourceBlockingPolicy, string logFile, StackTraceEmissionPolicy stackTracePolicy) + : base(typeSystemContext, blockingPolicy, resourceBlockingPolicy) { _metadataLogFile = logFile; _stackTraceEmissionPolicy = stackTracePolicy; diff --git a/src/ILCompiler.Compiler/src/Compiler/ManifestResourceBlockingPolicy.cs b/src/ILCompiler.Compiler/src/Compiler/ManifestResourceBlockingPolicy.cs new file mode 100644 index 00000000000..9f61db5bda8 --- /dev/null +++ b/src/ILCompiler.Compiler/src/Compiler/ManifestResourceBlockingPolicy.cs @@ -0,0 +1,21 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using Internal.TypeSystem; + +namespace ILCompiler +{ + /// + /// Represents a manifest resource blocking policy. The policy dictates whether manifest resources should + /// be generated into the executable. + /// + public abstract class ManifestResourceBlockingPolicy + { + /// + /// Returns true if manifest resource with name '' in module '' + /// is reflection blocked. + /// + public abstract bool IsManifestResourceBlocked(ModuleDesc module, string resourceName); + } +} diff --git a/src/ILCompiler.Compiler/src/Compiler/MetadataManager.cs b/src/ILCompiler.Compiler/src/Compiler/MetadataManager.cs index 301c64572f8..de199495896 100644 --- a/src/ILCompiler.Compiler/src/Compiler/MetadataManager.cs +++ b/src/ILCompiler.Compiler/src/Compiler/MetadataManager.cs @@ -42,6 +42,7 @@ public abstract class MetadataManager : ICompilationRootProvider protected readonly CompilerTypeSystemContext _typeSystemContext; protected readonly MetadataBlockingPolicy _blockingPolicy; + protected readonly ManifestResourceBlockingPolicy _resourceBlockingPolicy; private List _cctorContextsGenerated = new List(); private HashSet _typesWithEETypesGenerated = new HashSet(); @@ -55,10 +56,11 @@ public abstract class MetadataManager : ICompilationRootProvider internal DynamicInvokeTemplateDataNode DynamicInvokeTemplateData { get; private set; } public virtual bool SupportsReflection => true; - public MetadataManager(CompilerTypeSystemContext typeSystemContext, MetadataBlockingPolicy blockingPolicy) + public MetadataManager(CompilerTypeSystemContext typeSystemContext, MetadataBlockingPolicy blockingPolicy, ManifestResourceBlockingPolicy resourceBlockingPolicy) { _typeSystemContext = typeSystemContext; _blockingPolicy = blockingPolicy; + _resourceBlockingPolicy = resourceBlockingPolicy; } public void AttachToDependencyGraph(DependencyAnalyzerBase graph) @@ -657,6 +659,11 @@ public bool IsReflectionBlocked(MethodDesc method) return _blockingPolicy.IsBlocked(typicalMethodDefinition); } + public bool IsManifestResourceBlocked(ModuleDesc module, string resourceName) + { + return _resourceBlockingPolicy.IsManifestResourceBlocked(module, resourceName); + } + public bool CanGenerateMetadata(MetadataType type) { return (GetMetadataCategory(type) & MetadataCategory.Description) != 0; diff --git a/src/ILCompiler.Compiler/src/Compiler/NoManifestResourceBlockingPolicy.cs b/src/ILCompiler.Compiler/src/Compiler/NoManifestResourceBlockingPolicy.cs new file mode 100644 index 00000000000..fd58d0e5bfc --- /dev/null +++ b/src/ILCompiler.Compiler/src/Compiler/NoManifestResourceBlockingPolicy.cs @@ -0,0 +1,19 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using Internal.TypeSystem; + +namespace ILCompiler +{ + /// + /// A blocking policy that doesn't block any manifest resources. + /// + public sealed class NoManifestResourceBlockingPolicy : ManifestResourceBlockingPolicy + { + public override bool IsManifestResourceBlocked(ModuleDesc module, string resourceName) + { + return false; + } + } +} diff --git a/src/ILCompiler.Compiler/src/Compiler/NoBlockingPolicy.cs b/src/ILCompiler.Compiler/src/Compiler/NoMetadataBlockingPolicy.cs similarity index 96% rename from src/ILCompiler.Compiler/src/Compiler/NoBlockingPolicy.cs rename to src/ILCompiler.Compiler/src/Compiler/NoMetadataBlockingPolicy.cs index cca09285fe8..af0c073b9af 100644 --- a/src/ILCompiler.Compiler/src/Compiler/NoBlockingPolicy.cs +++ b/src/ILCompiler.Compiler/src/Compiler/NoMetadataBlockingPolicy.cs @@ -10,7 +10,7 @@ namespace ILCompiler /// /// Represents a metadata blocking policy that doesn't block any metadata. /// - public sealed class NoBlockingPolicy : MetadataBlockingPolicy + public sealed class NoMetadataBlockingPolicy : MetadataBlockingPolicy { public override bool IsBlocked(MetadataType type) => !(type is EcmaType); diff --git a/src/ILCompiler.Compiler/src/Compiler/PrecomputedMetadataManager.cs b/src/ILCompiler.Compiler/src/Compiler/PrecomputedMetadataManager.cs index 0e333d323db..ccb87ce2a96 100644 --- a/src/ILCompiler.Compiler/src/Compiler/PrecomputedMetadataManager.cs +++ b/src/ILCompiler.Compiler/src/Compiler/PrecomputedMetadataManager.cs @@ -62,8 +62,9 @@ class MetadataLoadedInfo IEnumerable compilationModules, IEnumerable inputMetadataOnlyAssemblies, byte[] metadataBlob, - StackTraceEmissionPolicy stackTraceEmissionPolicy) - : base(typeSystemContext, new AttributeSpecifiedBlockingPolicy()) + StackTraceEmissionPolicy stackTraceEmissionPolicy, + ManifestResourceBlockingPolicy resourceBlockingPolicy) + : base(typeSystemContext, new AttributeSpecifiedBlockingPolicy(), resourceBlockingPolicy) { _compilationModuleGroup = group; _metadataDescribingModule = metadataDescribingModule; diff --git a/src/ILCompiler.Compiler/src/Compiler/UsageBasedMetadataManager.cs b/src/ILCompiler.Compiler/src/Compiler/UsageBasedMetadataManager.cs index a9f638d7b46..3d13aa547ad 100644 --- a/src/ILCompiler.Compiler/src/Compiler/UsageBasedMetadataManager.cs +++ b/src/ILCompiler.Compiler/src/Compiler/UsageBasedMetadataManager.cs @@ -34,9 +34,10 @@ public sealed class UsageBasedMetadataManager : GeneratingMetadataManager CompilationModuleGroup group, CompilerTypeSystemContext typeSystemContext, MetadataBlockingPolicy blockingPolicy, + ManifestResourceBlockingPolicy resourceBlockingPolicy, string logFile, StackTraceEmissionPolicy stackTracePolicy) - : base(typeSystemContext, blockingPolicy, logFile, stackTracePolicy) + : base(typeSystemContext, blockingPolicy, resourceBlockingPolicy, logFile, stackTracePolicy) { // We use this to mark places that would behave differently if we tracked exact fields used. _hasPreciseFieldUsageInformation = false; @@ -354,7 +355,7 @@ public MetadataManager ToAnalysisBasedMetadataManager() } return new AnalysisBasedMetadataManager( - _typeSystemContext, _blockingPolicy, _metadataLogFile, _stackTraceEmissionPolicy, + _typeSystemContext, _blockingPolicy, _resourceBlockingPolicy, _metadataLogFile, _stackTraceEmissionPolicy, _modulesWithMetadata, reflectableTypes.ToEnumerable(), reflectableMethods.ToEnumerable(), reflectableFields.ToEnumerable()); } diff --git a/src/ILCompiler.Compiler/src/ILCompiler.Compiler.csproj b/src/ILCompiler.Compiler/src/ILCompiler.Compiler.csproj index 72c5d416f79..7b86399ea27 100644 --- a/src/ILCompiler.Compiler/src/ILCompiler.Compiler.csproj +++ b/src/ILCompiler.Compiler/src/ILCompiler.Compiler.csproj @@ -131,9 +131,12 @@ + - + + + diff --git a/src/ILCompiler/src/Program.cs b/src/ILCompiler/src/Program.cs index 234ca9aed81..4765f21da1d 100644 --- a/src/ILCompiler/src/Program.cs +++ b/src/ILCompiler/src/Program.cs @@ -408,12 +408,15 @@ private int Run(string[] args) (StackTraceEmissionPolicy)new EcmaMethodStackTraceEmissionPolicy() : new NoStackTraceEmissionPolicy(); MetadataBlockingPolicy mdBlockingPolicy = _noMetadataBlocking ? - (MetadataBlockingPolicy)new NoBlockingPolicy() : new BlockedInternalsBlockingPolicy(); + (MetadataBlockingPolicy)new NoMetadataBlockingPolicy() : new BlockedInternalsBlockingPolicy(); + + ManifestResourceBlockingPolicy resBlockingPolicy = new NoManifestResourceBlockingPolicy(); UsageBasedMetadataManager metadataManager = new UsageBasedMetadataManager( compilationGroup, typeSystemContext, mdBlockingPolicy, + resBlockingPolicy, _metadataLogFileName, stackTracePolicy); From 602a88cec072f16fbf0628a534ac218496c8e710 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michal=20Strehovsk=C3=BD?= Date: Fri, 29 Jun 2018 10:37:31 +0200 Subject: [PATCH 34/69] Fix MembersMustExist to account for dotnet/coreclr#18645 (#6030) --- src/System.Private.CoreLib/src/MembersMustExist.AnalyzerData | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/System.Private.CoreLib/src/MembersMustExist.AnalyzerData b/src/System.Private.CoreLib/src/MembersMustExist.AnalyzerData index dbb84e87371..c2c9ba98f31 100644 --- a/src/System.Private.CoreLib/src/MembersMustExist.AnalyzerData +++ b/src/System.Private.CoreLib/src/MembersMustExist.AnalyzerData @@ -215,7 +215,7 @@ public string System.IntPtr.ToString(string format) private static System.Text.StringBuilder System.Text.StringBuilderCache.t_cachedInstance private int string._stringLength private char string._firstChar -private void* System.IntPtr._value +private readonly void* System.IntPtr._value private static volatile System.Globalization.CultureInfo System.Globalization.CultureInfo.s_DefaultThreadCurrentCulture private static volatile System.Globalization.CultureInfo System.Globalization.CultureInfo.s_DefaultThreadCurrentUICulture private static readonly System.Globalization.CultureInfo System.Globalization.CultureInfo.s_InvariantCultureInfo From 053011069037aeccf11408fdacc79ddbb7f06780 Mon Sep 17 00:00:00 2001 From: Fadi Hanna Date: Fri, 29 Jun 2018 11:22:22 -0700 Subject: [PATCH 35/69] Fixing CoreRT git mirroring break. The issue here is that the code enumerates the slots of a VTable node of a runtime determined interface instantiation (declType.GetTypeDefinition().RuntimeInterfaces), and in CoreRT the vtable slots are only produced when used by the code. Given that nothing uses these method definitions, we end up empty vtables, and end up with missing entries in the dispatch map and sealed vtable. I'm rewriting the code to enumerate methods on the fully instantiated VTable, [tfs-changeset: 1706049] --- .../Compiler/DependencyAnalysis/InterfaceDispatchMapNode.cs | 6 +++++- .../src/Compiler/DependencyAnalysis/SealedVTableNode.cs | 6 +++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/InterfaceDispatchMapNode.cs b/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/InterfaceDispatchMapNode.cs index 57c4299af35..fb72c8a7cdc 100644 --- a/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/InterfaceDispatchMapNode.cs +++ b/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/InterfaceDispatchMapNode.cs @@ -117,7 +117,8 @@ void EmitDispatchMap(ref ObjectDataBuilder builder, NodeFactory factory) for (int interfaceIndex = 0; interfaceIndex < declType.RuntimeInterfaces.Length; interfaceIndex++) { - var interfaceType = declType.GetTypeDefinition().RuntimeInterfaces[interfaceIndex]; + var interfaceType = declType.RuntimeInterfaces[interfaceIndex]; + var interfaceDefinitionType = declType.GetTypeDefinition().RuntimeInterfaces[interfaceIndex]; Debug.Assert(interfaceType.IsInterface); IReadOnlyList virtualSlots = factory.VTable(interfaceType).Slots; @@ -125,6 +126,9 @@ void EmitDispatchMap(ref ObjectDataBuilder builder, NodeFactory factory) for (int interfaceMethodSlot = 0; interfaceMethodSlot < virtualSlots.Count; interfaceMethodSlot++) { MethodDesc declMethod = virtualSlots[interfaceMethodSlot]; + if(!interfaceType.IsTypeDefinition) + declMethod = factory.TypeSystemContext.GetMethodForInstantiatedType(declMethod.GetTypicalMethodDefinition(), (InstantiatedType)interfaceDefinitionType); + var implMethod = declType.GetTypeDefinition().ResolveInterfaceMethodToVirtualMethodOnType(declMethod); // Interface methods first implemented by a base type in the hierarchy will return null for the implMethod (runtime interface diff --git a/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/SealedVTableNode.cs b/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/SealedVTableNode.cs index c2a79224699..80d67a9bd9e 100644 --- a/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/SealedVTableNode.cs +++ b/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/SealedVTableNode.cs @@ -109,13 +109,17 @@ public bool BuildSealedVTableSlots(NodeFactory factory, bool relocsOnly) for (int interfaceIndex = 0; interfaceIndex < declType.RuntimeInterfaces.Length; interfaceIndex++) { - var interfaceType = declType.GetTypeDefinition().RuntimeInterfaces[interfaceIndex]; + var interfaceType = declType.RuntimeInterfaces[interfaceIndex]; + var interfaceDefinitionType = declType.GetTypeDefinition().RuntimeInterfaces[interfaceIndex]; virtualSlots = factory.VTable(interfaceType).Slots; for (int interfaceMethodSlot = 0; interfaceMethodSlot < virtualSlots.Count; interfaceMethodSlot++) { MethodDesc declMethod = virtualSlots[interfaceMethodSlot]; + if (!interfaceType.IsTypeDefinition) + declMethod = factory.TypeSystemContext.GetMethodForInstantiatedType(declMethod.GetTypicalMethodDefinition(), (InstantiatedType)interfaceDefinitionType); + var implMethod = declType.GetTypeDefinition().ResolveInterfaceMethodToVirtualMethodOnType(declMethod); // Interface methods first implemented by a base type in the hierarchy will return null for the implMethod (runtime interface From d5eaa6e14d4118621c8f5c9fa2cdc80185500225 Mon Sep 17 00:00:00 2001 From: Stephen Toub Date: Fri, 29 Jun 2018 13:31:51 -0400 Subject: [PATCH 36/69] Improve bool.TryFormat perf (dotnet/coreclr#18711) * Improve bool.TryFormat perf Improves throughput by ~50%, by avoiding AsSpan().CopyTo and just writing out the characters one-by-one. I experimented with playing the same tricks around storing the data in a ulong and blitting it out to the destination reinterpreted as a span of ulongs, but it didn't make a measurable improvement and increased the code complexity. * Update Boolean.cs Signed-off-by: dotnet-bot --- .../shared/System/Boolean.cs | 30 ++++++++++++++----- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/src/System.Private.CoreLib/shared/System/Boolean.cs b/src/System.Private.CoreLib/shared/System/Boolean.cs index 7ec9227f1b5..4daf6f3f96b 100644 --- a/src/System.Private.CoreLib/shared/System/Boolean.cs +++ b/src/System.Private.CoreLib/shared/System/Boolean.cs @@ -97,18 +97,34 @@ public string ToString(IFormatProvider provider) public bool TryFormat(Span destination, out int charsWritten) { - string s = m_value ? TrueLiteral : FalseLiteral; - - if (s.AsSpan().TryCopyTo(destination)) + if (m_value) { - charsWritten = s.Length; - return true; + if ((uint)destination.Length > 3) // uint cast, per https://github.com/dotnet/coreclr/issues/18688 + { + destination[0] = 'T'; + destination[1] = 'r'; + destination[2] = 'u'; + destination[3] = 'e'; + charsWritten = 4; + return true; + } } else { - charsWritten = 0; - return false; + if ((uint)destination.Length > 4) + { + destination[0] = 'F'; + destination[1] = 'a'; + destination[2] = 'l'; + destination[3] = 's'; + destination[4] = 'e'; + charsWritten = 5; + return true; + } } + + charsWritten = 0; + return false; } // Determines whether two Boolean objects are equal. From beac7423732f6ec1342224402d6e7f345c289216 Mon Sep 17 00:00:00 2001 From: Viktor Hofer Date: Fri, 29 Jun 2018 17:47:53 +0200 Subject: [PATCH 37/69] Regex: reduce allocation slightly, add tests, code cleanup, add parser comments (#30632) * RegexParser & optionsstack ref * Add test coverage for Group.Synchronized * Adjust options mode test case * Add inline comment '#' test branch * Add comments * Replace manual ToLower calls by Span.ToLower * Make applicable fields readonly in parser * Change to Assert to reduce an if check in one branch * Code formatting * Avoid string allocation when IgnoreCase set Prefix patterns which are passed to RegexBoyerMoore are already lowercased by the parser. Remove the redundant ToLower() call and assert the patterns lowercase state * Add surrogate pair positive & negative tests * Add test cases for rtl anchor Signed-off-by: dotnet-bot --- .../System/Collections/Generic/ValueListBuilder.cs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/System.Private.CoreLib/shared/System/Collections/Generic/ValueListBuilder.cs b/src/System.Private.CoreLib/shared/System/Collections/Generic/ValueListBuilder.cs index 72da4a9e197..aea6052f030 100644 --- a/src/System.Private.CoreLib/shared/System/Collections/Generic/ValueListBuilder.cs +++ b/src/System.Private.CoreLib/shared/System/Collections/Generic/ValueListBuilder.cs @@ -21,7 +21,16 @@ public ValueListBuilder(Span initialSpan) _pos = 0; } - public int Length => _pos; + public int Length + { + get => _pos; + set + { + Debug.Assert(value >= 0); + Debug.Assert(value <= _span.Length); + _pos = value; + } + } public ref T this[int index] { From 42d41b8cf8ea907173c3b1b84d71a349ea8cda82 Mon Sep 17 00:00:00 2001 From: Tanner Gooding Date: Fri, 29 Jun 2018 19:19:31 -0700 Subject: [PATCH 38/69] Fixing some Bmi1 HWIntrinsic method names (dotnet/coreclr#18718) Signed-off-by: dotnet-bot --- .../Intrinsics/X86/Bmi1.PlatformNotSupported.cs | 12 ++++++------ .../shared/System/Runtime/Intrinsics/X86/Bmi1.cs | 12 ++++++------ 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Bmi1.PlatformNotSupported.cs b/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Bmi1.PlatformNotSupported.cs index f74cc7b84f8..8c331bef477 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Bmi1.PlatformNotSupported.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Bmi1.PlatformNotSupported.cs @@ -30,22 +30,22 @@ public static class Bmi1 /// unsigned int _bextr_u32 (unsigned int a, unsigned int start, unsigned int len) /// BEXTR r32a, reg/m32, r32b /// - public static uint BitFieldExtract(uint value, uint start, uint length) { throw new PlatformNotSupportedException(); } + public static uint BitFieldExtract(uint value, byte start, byte length) { throw new PlatformNotSupportedException(); } /// /// unsigned __int64 _bextr_u64 (unsigned __int64 a, unsigned int start, unsigned int len) /// BEXTR r64a, reg/m64, r64b /// - public static ulong BitFieldExtract(ulong value, ulong start, ulong length) { throw new PlatformNotSupportedException(); } + public static ulong BitFieldExtract(ulong value, byte start, byte length) { throw new PlatformNotSupportedException(); } /// /// unsigned int _bextr2_u32 (unsigned int a, unsigned int control) /// BEXTR r32a, reg/m32, r32b /// - public static uint BitFieldExtract(uint value, uint control) { throw new PlatformNotSupportedException(); } + public static uint BitFieldExtract(uint value, ushort control) { throw new PlatformNotSupportedException(); } /// /// unsigned __int64 _bextr2_u64 (unsigned __int64 a, unsigned __int64 control) /// BEXTR r64a, reg/m64, r64b /// - public static ulong BitFieldExtract(ulong value, ulong control) { throw new PlatformNotSupportedException(); } + public static ulong BitFieldExtract(ulong value, ushort control) { throw new PlatformNotSupportedException(); } /// /// unsigned int _blsi_u32 (unsigned int a) @@ -62,12 +62,12 @@ public static class Bmi1 /// unsigned int _blsmsk_u32 (unsigned int a) /// BLSMSK reg, reg/m32 /// - public static uint GetMaskUptoLowestSetBit(uint value) { throw new PlatformNotSupportedException(); } + public static uint GetMaskUpToLowestSetBit(uint value) { throw new PlatformNotSupportedException(); } /// /// unsigned __int64 _blsmsk_u64 (unsigned __int64 a) /// BLSMSK reg, reg/m64 /// - public static ulong GetMaskUptoLowestSetBit(ulong value) { throw new PlatformNotSupportedException(); } + public static ulong GetMaskUpToLowestSetBit(ulong value) { throw new PlatformNotSupportedException(); } /// /// unsigned int _blsr_u32 (unsigned int a) diff --git a/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Bmi1.cs b/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Bmi1.cs index d8e41ea0a2c..e1652ea4f74 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Bmi1.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Bmi1.cs @@ -30,22 +30,22 @@ public static class Bmi1 /// unsigned int _bextr_u32 (unsigned int a, unsigned int start, unsigned int len) /// BEXTR r32a, reg/m32, r32b /// - public static uint BitFieldExtract(uint value, uint start, uint length) => BitFieldExtract(value, start, length); + public static uint BitFieldExtract(uint value, byte start, byte length) => BitFieldExtract(value, start, length); /// /// unsigned __int64 _bextr_u64 (unsigned __int64 a, unsigned int start, unsigned int len) /// BEXTR r64a, reg/m64, r64b /// - public static ulong BitFieldExtract(ulong value, ulong start, ulong length) => BitFieldExtract(value, start, length); + public static ulong BitFieldExtract(ulong value, byte start, byte length) => BitFieldExtract(value, start, length); /// /// unsigned int _bextr2_u32 (unsigned int a, unsigned int control) /// BEXTR r32a, reg/m32, r32b /// - public static uint BitFieldExtract(uint value, uint control) => BitFieldExtract(value, control); + public static uint BitFieldExtract(uint value, ushort control) => BitFieldExtract(value, control); /// /// unsigned __int64 _bextr2_u64 (unsigned __int64 a, unsigned __int64 control) /// BEXTR r64a, reg/m64, r64b /// - public static ulong BitFieldExtract(ulong value, ulong control) => BitFieldExtract(value, control); + public static ulong BitFieldExtract(ulong value, ushort control) => BitFieldExtract(value, control); /// /// unsigned int _blsi_u32 (unsigned int a) @@ -62,12 +62,12 @@ public static class Bmi1 /// unsigned int _blsmsk_u32 (unsigned int a) /// BLSMSK reg, reg/m32 /// - public static uint GetMaskUptoLowestSetBit(uint value) => GetMaskUptoLowestSetBit(value); + public static uint GetMaskUpToLowestSetBit(uint value) => GetMaskUpToLowestSetBit(value); /// /// unsigned __int64 _blsmsk_u64 (unsigned __int64 a) /// BLSMSK reg, reg/m64 /// - public static ulong GetMaskUptoLowestSetBit(ulong value) => GetMaskUptoLowestSetBit(value); + public static ulong GetMaskUpToLowestSetBit(ulong value) => GetMaskUpToLowestSetBit(value); /// /// unsigned int _blsr_u32 (unsigned int a) From e3364969f2418b906e0655aebb89ab2cffbce761 Mon Sep 17 00:00:00 2001 From: Jan Kotas Date: Sun, 1 Jul 2018 19:15:04 -0700 Subject: [PATCH 39/69] Update RyuJIT (#6038) --- dependencies.props | 4 +- src/JitInterface/src/CorInfoTypes.cs | 6 +- .../src/ThunkGenerator/cordebuginfo.h | 198 ++++++++++-------- src/JitInterface/src/ThunkGenerator/corinfo.h | 39 +++- src/Native/jitinterface/jitwrapper.cpp | 10 +- 5 files changed, 147 insertions(+), 110 deletions(-) diff --git a/dependencies.props b/dependencies.props index 0b8fd393236..c9bd5e51e3e 100644 --- a/dependencies.props +++ b/dependencies.props @@ -1,10 +1,10 @@ - 3.0.0-preview1-26624-03 + 3.0.0-preview1-26702-01 1.0.0-alpha-26412-0 4.6.0-preview1-26625-01 4.7.0-preview1-26625-01 - 3.0.0-preview1-26624-03 + 3.0.0-preview1-26702-01 2.1.0 1.0.1-prerelease-02104-02 diff --git a/src/JitInterface/src/CorInfoTypes.cs b/src/JitInterface/src/CorInfoTypes.cs index 6d6653b859e..6d0662be50b 100644 --- a/src/JitInterface/src/CorInfoTypes.cs +++ b/src/JitInterface/src/CorInfoTypes.cs @@ -193,6 +193,7 @@ public unsafe struct CORINFO_SIG_INFO // Constant Lookups are either: // IAT_VALUE: immediate (relocatable) values, // IAT_PVALUE: immediate values access via an indirection through an immediate (relocatable) address + // IAT_RELPVALUE: immediate values access via a relative indirection through an immediate offset // IAT_PPVALUE: immediate values access via a double indirection through an immediate (relocatable) address // // Runtime Lookups @@ -220,6 +221,7 @@ public unsafe struct CORINFO_CONST_LOOKUP // If accessType is // IAT_VALUE --> "handle" stores the real handle or "addr " stores the computed address // IAT_PVALUE --> "addr" stores a pointer to a location which will hold the real handle + // IAT_RELPVALUE --> "addr" stores a relative pointer to a location which will hold the real handle // IAT_PPVALUE --> "addr" stores a double indirection to a location which will hold the real handle public InfoAccessType accessType; @@ -301,6 +303,7 @@ public unsafe struct CORINFO_LOOKUP // Otherwise, it's a representative... If accessType is // IAT_VALUE --> "handle" stores the real handle or "addr " stores the computed address // IAT_PVALUE --> "addr" stores a pointer to a location which will hold the real handle + // IAT_RELPVALUE --> "addr" stores a relative pointer to a location which will hold the real handle // IAT_PPVALUE --> "addr" stores a double indirection to a location which will hold the real handle public ref CORINFO_CONST_LOOKUP constLookup { @@ -495,7 +498,8 @@ public enum InfoAccessType { IAT_VALUE, // The info value is directly available IAT_PVALUE, // The value needs to be accessed via an indirection - IAT_PPVALUE // The value needs to be accessed via a double indirection + IAT_PPVALUE, // The value needs to be accessed via a double indirection + IAT_RELPVALUE // The value needs to be accessed via a relative indirection } public enum CorInfoGCType diff --git a/src/JitInterface/src/ThunkGenerator/cordebuginfo.h b/src/JitInterface/src/ThunkGenerator/cordebuginfo.h index b065c5fc06b..8c076e8b68f 100644 --- a/src/JitInterface/src/ThunkGenerator/cordebuginfo.h +++ b/src/JitInterface/src/ThunkGenerator/cordebuginfo.h @@ -2,6 +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. +// +// Keep in sync with https://github.com/dotnet/corert/blob/master/src/Native/ObjWriter/cordebuginfo.h +// + /**********************************************************************************/ // DebugInfo types shared by JIT-EE interface and EE-Debugger interface @@ -191,104 +195,114 @@ class ICorDebugInfo VLT_INVALID, }; + // VLT_REG/VLT_REG_FP -- Any pointer-sized enregistered value (TYP_INT, TYP_REF, etc) + // eg. EAX + // VLT_REG_BYREF -- the specified register contains the address of the variable + // eg. [EAX] + + struct vlReg + { + RegNum vlrReg; + }; + + // VLT_STK -- Any 32 bit value which is on the stack + // eg. [ESP+0x20], or [EBP-0x28] + // VLT_STK_BYREF -- the specified stack location contains the address of the variable + // eg. mov EAX, [ESP+0x20]; [EAX] + + struct vlStk + { + RegNum vlsBaseReg; + signed vlsOffset; + }; + + // VLT_REG_REG -- TYP_LONG with both DWords enregistred + // eg. RBM_EAXEDX + + struct vlRegReg + { + RegNum vlrrReg1; + RegNum vlrrReg2; + }; + + // VLT_REG_STK -- Partly enregistered TYP_LONG + // eg { LowerDWord=EAX UpperDWord=[ESP+0x8] } + + struct vlRegStk + { + RegNum vlrsReg; + struct + { + RegNum vlrssBaseReg; + signed vlrssOffset; + } vlrsStk; + }; + + // VLT_STK_REG -- Partly enregistered TYP_LONG + // eg { LowerDWord=[ESP+0x8] UpperDWord=EAX } + + struct vlStkReg + { + struct + { + RegNum vlsrsBaseReg; + signed vlsrsOffset; + } vlsrStk; + RegNum vlsrReg; + }; + + // VLT_STK2 -- Any 64 bit value which is on the stack, + // in 2 successsive DWords. + // eg 2 DWords at [ESP+0x10] + + struct vlStk2 + { + RegNum vls2BaseReg; + signed vls2Offset; + }; + + // VLT_FPSTK -- enregisterd TYP_DOUBLE (on the FP stack) + // eg. ST(3). Actually it is ST("FPstkHeigth - vpFpStk") + + struct vlFPstk + { + unsigned vlfReg; + }; + + // VLT_FIXED_VA -- fixed argument of a varargs function. + // The argument location depends on the size of the variable + // arguments (...). Inspecting the VARARGS_HANDLE indicates the + // location of the first arg. This argument can then be accessed + // relative to the position of the first arg + + struct vlFixedVarArg + { + unsigned vlfvOffset; + }; + + // VLT_MEMORY + + struct vlMemory + { + void *rpValue; // pointer to the in-process + // location of the value. + }; + struct VarLoc { VarLocType vlType; union { - // VLT_REG/VLT_REG_FP -- Any pointer-sized enregistered value (TYP_INT, TYP_REF, etc) - // eg. EAX - // VLT_REG_BYREF -- the specified register contains the address of the variable - // eg. [EAX] - - struct - { - RegNum vlrReg; - } vlReg; - - // VLT_STK -- Any 32 bit value which is on the stack - // eg. [ESP+0x20], or [EBP-0x28] - // VLT_STK_BYREF -- the specified stack location contains the address of the variable - // eg. mov EAX, [ESP+0x20]; [EAX] - - struct - { - RegNum vlsBaseReg; - signed vlsOffset; - } vlStk; - - // VLT_REG_REG -- TYP_LONG with both DWords enregistred - // eg. RBM_EAXEDX - - struct - { - RegNum vlrrReg1; - RegNum vlrrReg2; - } vlRegReg; - - // VLT_REG_STK -- Partly enregistered TYP_LONG - // eg { LowerDWord=EAX UpperDWord=[ESP+0x8] } - - struct - { - RegNum vlrsReg; - struct - { - RegNum vlrssBaseReg; - signed vlrssOffset; - } vlrsStk; - } vlRegStk; - - // VLT_STK_REG -- Partly enregistered TYP_LONG - // eg { LowerDWord=[ESP+0x8] UpperDWord=EAX } - - struct - { - struct - { - RegNum vlsrsBaseReg; - signed vlsrsOffset; - } vlsrStk; - RegNum vlsrReg; - } vlStkReg; - - // VLT_STK2 -- Any 64 bit value which is on the stack, - // in 2 successsive DWords. - // eg 2 DWords at [ESP+0x10] - - struct - { - RegNum vls2BaseReg; - signed vls2Offset; - } vlStk2; - - // VLT_FPSTK -- enregisterd TYP_DOUBLE (on the FP stack) - // eg. ST(3). Actually it is ST("FPstkHeigth - vpFpStk") - - struct - { - unsigned vlfReg; - } vlFPstk; - - // VLT_FIXED_VA -- fixed argument of a varargs function. - // The argument location depends on the size of the variable - // arguments (...). Inspecting the VARARGS_HANDLE indicates the - // location of the first arg. This argument can then be accessed - // relative to the position of the first arg - - struct - { - unsigned vlfvOffset; - } vlFixedVarArg; - - // VLT_MEMORY - - struct - { - void *rpValue; // pointer to the in-process - // location of the value. - } vlMemory; + vlReg vlReg; + vlStk vlStk; + vlRegReg vlRegReg; + vlRegStk vlRegStk; + vlStkReg vlStkReg; + vlStk2 vlStk2; + vlFPstk vlFPstk; + vlFixedVarArg vlFixedVarArg; + vlMemory vlMemory; }; }; diff --git a/src/JitInterface/src/ThunkGenerator/corinfo.h b/src/JitInterface/src/ThunkGenerator/corinfo.h index 1e4bb961848..2270d328d78 100644 --- a/src/JitInterface/src/ThunkGenerator/corinfo.h +++ b/src/JitInterface/src/ThunkGenerator/corinfo.h @@ -213,11 +213,11 @@ TODO: Talk about initializing strutures before use #define SELECTANY extern __declspec(selectany) #endif -SELECTANY const GUID JITEEVersionIdentifier = { /* dc72a60f-22f2-49fb-809f-00077f3eb1a8 */ - 0xdc72a60f, - 0x22f2, - 0x49fb, - { 0x80, 0x9f, 0x0, 0x7, 0x7f, 0x3e, 0xb1, 0xa8} +SELECTANY const GUID JITEEVersionIdentifier = { /* 45aafd4d-1d23-4647-9ce1-cf09a2677ca0 */ + 0x45aafd4d, + 0x1d23, + 0x4647, + {0x9c, 0xe1, 0xcf, 0x09, 0xa2, 0x67, 0x7c, 0xa0} }; ////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -977,8 +977,9 @@ enum CorInfoIntrinsics enum InfoAccessType { IAT_VALUE, // The info value is directly available - IAT_PVALUE, // The value needs to be accessed via an indirection - IAT_PPVALUE // The value needs to be accessed via a double indirection + IAT_PVALUE, // The value needs to be accessed via an indirection + IAT_PPVALUE, // The value needs to be accessed via a double indirection + IAT_RELPVALUE // The value needs to be accessed via a relative indirection }; enum CorInfoGCType @@ -1243,6 +1244,7 @@ struct CORINFO_METHOD_INFO // Constant Lookups are either: // IAT_VALUE: immediate (relocatable) values, // IAT_PVALUE: immediate values access via an indirection through an immediate (relocatable) address +// IAT_RELPVALUE: immediate values access via a relative indirection through an immediate offset // IAT_PPVALUE: immediate values access via a double indirection through an immediate (relocatable) address // // Runtime Lookups @@ -1268,9 +1270,10 @@ struct CORINFO_CONST_LOOKUP // If the handle is obtained at compile-time, then this handle is the "exact" handle (class, method, or field) // Otherwise, it's a representative... // If accessType is - // IAT_VALUE --> "handle" stores the real handle or "addr " stores the computed address - // IAT_PVALUE --> "addr" stores a pointer to a location which will hold the real handle - // IAT_PPVALUE --> "addr" stores a double indirection to a location which will hold the real handle + // IAT_VALUE --> "handle" stores the real handle or "addr " stores the computed address + // IAT_PVALUE --> "addr" stores a pointer to a location which will hold the real handle + // IAT_RELPVALUE --> "addr" stores a relative pointer to a location which will hold the real handle + // IAT_PPVALUE --> "addr" stores a double indirection to a location which will hold the real handle InfoAccessType accessType; union @@ -1361,6 +1364,7 @@ struct CORINFO_LOOKUP // Otherwise, it's a representative... If accessType is // IAT_VALUE --> "handle" stores the real handle or "addr " stores the computed address // IAT_PVALUE --> "addr" stores a pointer to a location which will hold the real handle + // IAT_RELPVALUE --> "addr" stores a relative pointer to a location which will hold the real handle // IAT_PPVALUE --> "addr" stores a double indirection to a location which will hold the real handle CORINFO_CONST_LOOKUP constLookup; }; @@ -1926,6 +1930,21 @@ struct CORINFO_VarArgInfo #include +#define SIZEOF__CORINFO_Object TARGET_POINTER_SIZE /* methTable */ + +#define OFFSETOF__CORINFO_Array__length SIZEOF__CORINFO_Object +#ifdef _TARGET_64BIT_ +#define OFFSETOF__CORINFO_Array__data (OFFSETOF__CORINFO_Array__length + sizeof(unsigned __int32) /* length */ + sizeof(unsigned __int32) /* alignpad */) +#else +#define OFFSETOF__CORINFO_Array__data (OFFSETOF__CORINFO_Array__length + sizeof(unsigned __int32) /* length */) +#endif + +#define OFFSETOF__CORINFO_TypedReference__dataPtr 0 +#define OFFSETOF__CORINFO_TypedReference__type (OFFSETOF__CORINFO_TypedReference__dataPtr + TARGET_POINTER_SIZE /* dataPtr */) + +#define OFFSETOF__CORINFO_String__stringLen SIZEOF__CORINFO_Object +#define OFFSETOF__CORINFO_String__chars (OFFSETOF__CORINFO_String__stringLen + sizeof(unsigned __int32) /* stringLen */) + enum CorInfoSecurityRuntimeChecks { CORINFO_ACCESS_SECURITY_NONE = 0, diff --git a/src/Native/jitinterface/jitwrapper.cpp b/src/Native/jitinterface/jitwrapper.cpp index d42d54a8fa9..069ef07392a 100644 --- a/src/Native/jitinterface/jitwrapper.cpp +++ b/src/Native/jitinterface/jitwrapper.cpp @@ -27,11 +27,11 @@ class CORJIT_FLAGS unsigned __int64 corJitFlags; }; -static const GUID JITEEVersionIdentifier = { /* dc72a60f-22f2-49fb-809f-00077f3eb1a8 */ - 0xdc72a60f, - 0x22f2, - 0x49fb, - { 0x80, 0x9f, 0x0, 0x7, 0x7f, 0x3e, 0xb1, 0xa8 } +static const GUID JITEEVersionIdentifier = { /* 45aafd4d-1d23-4647-9ce1-cf09a2677ca0 */ + 0x45aafd4d, + 0x1d23, + 0x4647, + {0x9c, 0xe1, 0xcf, 0x09, 0xa2, 0x67, 0x7c, 0xa0} }; class Jit From 1a67946d8d1c92772ba28e1f259c99c72e10a1c1 Mon Sep 17 00:00:00 2001 From: Jan Kotas Date: Thu, 28 Jun 2018 17:32:35 -0700 Subject: [PATCH 40/69] Tabs vs. spaces --- .../shared/System/Threading/EventWaitHandle.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/System.Private.CoreLib/shared/System/Threading/EventWaitHandle.cs b/src/System.Private.CoreLib/shared/System/Threading/EventWaitHandle.cs index 2542d8199fb..4cd733b9bd5 100644 --- a/src/System.Private.CoreLib/shared/System/Threading/EventWaitHandle.cs +++ b/src/System.Private.CoreLib/shared/System/Threading/EventWaitHandle.cs @@ -10,9 +10,9 @@ namespace System.Threading public partial class EventWaitHandle : WaitHandle { public EventWaitHandle(bool initialState, EventResetMode mode) : - this(initialState, mode, null, out _) - { - } + this(initialState, mode, null, out _) + { + } public EventWaitHandle(bool initialState, EventResetMode mode, string name) : this(initialState, mode, name, out _) From 1b248ccfd706e1b6768c2a949f89cd27bb5ff6a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michal=20Strehovsk=C3=BD?= Date: Tue, 17 Apr 2018 14:11:45 -0700 Subject: [PATCH 41/69] Add StdCall intrinsic support This is a building block to be able to write a repro case for #5587 in C#. With this, it's possible to use `AddrOf` intrinsic in connection with `StdCall` to hit the unimplemented functionality with pure C#. --- src/Common/src/TypeSystem/IL/ILProvider.cs | 2 +- src/Common/src/TypeSystem/IL/Stubs/CalliIntrinsic.cs | 8 ++++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/src/Common/src/TypeSystem/IL/ILProvider.cs b/src/Common/src/TypeSystem/IL/ILProvider.cs index d12904f3836..e583890a3fc 100644 --- a/src/Common/src/TypeSystem/IL/ILProvider.cs +++ b/src/Common/src/TypeSystem/IL/ILProvider.cs @@ -246,7 +246,7 @@ private MethodIL CreateMethodIL(MethodDesc method) if (((MetadataType)method.OwningType).HasCustomAttribute("System.Runtime.InteropServices", "McgIntrinsicsAttribute")) { var name = method.Name; - if (name == "Call") + if (name == "Call" || name == "StdCall") { return CalliIntrinsic.EmitIL(method); } diff --git a/src/Common/src/TypeSystem/IL/Stubs/CalliIntrinsic.cs b/src/Common/src/TypeSystem/IL/Stubs/CalliIntrinsic.cs index 28ae8b621e9..9d509c40f0e 100644 --- a/src/Common/src/TypeSystem/IL/Stubs/CalliIntrinsic.cs +++ b/src/Common/src/TypeSystem/IL/Stubs/CalliIntrinsic.cs @@ -18,7 +18,7 @@ public static class CalliIntrinsic { public static MethodIL EmitIL(MethodDesc target) { - Debug.Assert(target.Name == "Call"); + Debug.Assert(target.Name == "Call" || target.Name == "StdCall"); Debug.Assert(target.Signature.Length > 0 && target.Signature[0] == target.Context.GetWellKnownType(WellKnownType.IntPtr)); @@ -44,7 +44,11 @@ public static MethodIL EmitIL(MethodDesc target) parameters[i - 1] = template[i]; } - var signature = new MethodSignature(template.Flags, 0, returnType, parameters); + MethodSignatureFlags flags = template.Flags; + if (target.Name == "StdCall") + flags |= MethodSignatureFlags.UnmanagedCallingConventionStdCall; + + var signature = new MethodSignature(flags, 0, returnType, parameters); codeStream.Emit(ILOpcode.calli, emitter.NewToken(signature)); codeStream.Emit(ILOpcode.ret); From ad22792139f7929070ec254e1073e346ceb510e6 Mon Sep 17 00:00:00 2001 From: Jan Kotas Date: Wed, 2 May 2018 22:06:24 -0700 Subject: [PATCH 42/69] Enable PInvoke calli stubs Fixes #5587 --- .../IL/Stubs/CalliMarshallingMethodThunk.cs | 15 +++- .../TypeSystem/IL/Stubs/PInvokeILEmitter.cs | 75 ++++++++++++++----- src/JitInterface/src/CorInfoImpl.cs | 56 ++++++++++---- tests/CoreCLR.issues.targets | 8 -- 4 files changed, 109 insertions(+), 45 deletions(-) diff --git a/src/Common/src/TypeSystem/IL/Stubs/CalliMarshallingMethodThunk.cs b/src/Common/src/TypeSystem/IL/Stubs/CalliMarshallingMethodThunk.cs index a70ceb5fed5..11489bb8314 100644 --- a/src/Common/src/TypeSystem/IL/Stubs/CalliMarshallingMethodThunk.cs +++ b/src/Common/src/TypeSystem/IL/Stubs/CalliMarshallingMethodThunk.cs @@ -62,9 +62,9 @@ public override MethodSignature Signature // Prepend fnptr argument to the signature TypeDesc[] parameterTypes = new TypeDesc[_targetSignature.Length + 1]; - parameterTypes[0] = Context.GetWellKnownType(WellKnownType.IntPtr); for (int i = 0; i < _targetSignature.Length; i++) - parameterTypes[i + 1] = _targetSignature[i]; + parameterTypes[i] = _targetSignature[i]; + parameterTypes[parameterTypes.Length - 1] = Context.GetWellKnownType(WellKnownType.IntPtr); _signature = new MethodSignature(MethodSignatureFlags.Static, 0, _targetSignature.ReturnType, parameterTypes); } @@ -80,10 +80,17 @@ public override string Name } } + public override bool IsPInvoke + { + get + { + return true; + } + } + public override MethodIL EmitIL() { - // TODO - throw null; + return PInvokeILEmitter.EmitIL(this, default(PInvokeILEmitterConfiguration), _interopStateManager); } } } diff --git a/src/Common/src/TypeSystem/IL/Stubs/PInvokeILEmitter.cs b/src/Common/src/TypeSystem/IL/Stubs/PInvokeILEmitter.cs index fa503b74278..7620bda5bc3 100644 --- a/src/Common/src/TypeSystem/IL/Stubs/PInvokeILEmitter.cs +++ b/src/Common/src/TypeSystem/IL/Stubs/PInvokeILEmitter.cs @@ -40,12 +40,10 @@ private PInvokeILEmitter(MethodDesc targetMethod, PInvokeILEmitterConfiguration // targetMethod could be either a PInvoke or a DelegateMarshallingMethodThunk // ForwardNativeFunctionWrapper method thunks are marked as PInvokes, so it is // important to check them first here so that we get the right flags. - // - DelegateMarshallingMethodThunk delegateThunk = _targetMethod as DelegateMarshallingMethodThunk; - - if (delegateThunk != null) + // + if (_targetMethod is DelegateMarshallingMethodThunk delegateMethod) { - _flags = ((EcmaType)delegateThunk.DelegateType).GetDelegatePInvokeFlags(); + _flags = ((EcmaType)delegateMethod.DelegateType).GetDelegatePInvokeFlags(); } else { @@ -57,9 +55,21 @@ private PInvokeILEmitter(MethodDesc targetMethod, PInvokeILEmitterConfiguration private static Marshaller[] InitializeMarshallers(MethodDesc targetMethod, InteropStateManager interopStateManager, PInvokeFlags flags) { - bool isDelegate = targetMethod is DelegateMarshallingMethodThunk; - MethodSignature methodSig = isDelegate ? ((DelegateMarshallingMethodThunk)targetMethod).DelegateSignature : targetMethod.Signature; - MarshalDirection direction = isDelegate ? ((DelegateMarshallingMethodThunk)targetMethod).Direction: MarshalDirection.Forward; + MarshalDirection direction = MarshalDirection.Forward; + MethodSignature methodSig; + switch (targetMethod) + { + case DelegateMarshallingMethodThunk delegateMethod: + methodSig = delegateMethod.DelegateSignature; + direction = delegateMethod.Direction; + break; + case CalliMarshallingMethodThunk calliMethod: + methodSig = calliMethod.TargetSignature; + break; + default: + methodSig = targetMethod.Signature; + break; + } int indexOffset = 0; if (!methodSig.IsStatic && direction == MarshalDirection.Forward) { @@ -282,6 +292,27 @@ private void EmitPInvokeCall(PInvokeILCodeStreams ilCodeStreams) } } + private void EmitCalli(PInvokeILCodeStreams ilCodeStreams, CalliMarshallingMethodThunk calliThunk) + { + ILEmitter emitter = ilCodeStreams.Emitter; + ILCodeStream callsiteSetupCodeStream = ilCodeStreams.CallsiteSetupCodeStream; + + TypeDesc nativeReturnType = _marshallers[0].NativeParameterType; + TypeDesc[] nativeParameterTypes = new TypeDesc[_marshallers.Length - 1]; + + for (int i = 1; i < _marshallers.Length; i++) + { + nativeParameterTypes[i - 1] = _marshallers[i].NativeParameterType; + } + + MethodSignature nativeSig = new MethodSignature( + calliThunk.TargetSignature.Flags, 0, nativeReturnType, + nativeParameterTypes); + + callsiteSetupCodeStream.EmitLdArg(calliThunk.TargetSignature.Length); + callsiteSetupCodeStream.Emit(ILOpcode.calli, emitter.NewToken(nativeSig)); + } + private MethodIL EmitIL() { PInvokeILCodeStreams pInvokeILCodeStreams = new PInvokeILCodeStreams(); @@ -295,20 +326,23 @@ private MethodIL EmitIL() } // make the call - DelegateMarshallingMethodThunk delegateMethod = _targetMethod as DelegateMarshallingMethodThunk; - if (delegateMethod != null) - { - EmitDelegateCall(delegateMethod, pInvokeILCodeStreams); - } - else + switch (_targetMethod) { - EmitPInvokeCall(pInvokeILCodeStreams); + case DelegateMarshallingMethodThunk delegateMethod: + EmitDelegateCall(delegateMethod, pInvokeILCodeStreams); + break; + case CalliMarshallingMethodThunk calliMethod: + EmitCalli(pInvokeILCodeStreams, calliMethod); + break; + default: + EmitPInvokeCall(pInvokeILCodeStreams); + break; } _marshallers[0].LoadReturnValue(unmarshallingCodestream); unmarshallingCodestream.Emit(ILOpcode.ret); - return new PInvokeILStubMethodIL((ILStubMethodIL)emitter.Link(_targetMethod), IsStubRequired()); + return new PInvokeILStubMethodIL((ILStubMethodIL)emitter.Link(_targetMethod), IsStubRequired()); } public static MethodIL EmitIL(MethodDesc method, @@ -342,11 +376,14 @@ private bool IsStubRequired() return true; } - if (MarshalHelpers.UseLazyResolution(_targetMethod, _importMetadata.Module, - _pInvokeILEmitterConfiguration)) + if (_pInvokeILEmitterConfiguration != null) { - return true; + if (MarshalHelpers.UseLazyResolution(_targetMethod, _importMetadata.Module, _pInvokeILEmitterConfiguration)) + { + return true; + } } + if (_flags.SetLastError) { return true; diff --git a/src/JitInterface/src/CorInfoImpl.cs b/src/JitInterface/src/CorInfoImpl.cs index 7d8d4944527..1a0c2bbb785 100644 --- a/src/JitInterface/src/CorInfoImpl.cs +++ b/src/JitInterface/src/CorInfoImpl.cs @@ -760,13 +760,8 @@ private uint getMethodAttribsInternal(MethodDesc method) result |= CorInfoFlag.CORINFO_FLG_SHAREDINST; if (method.IsPInvoke) - { result |= CorInfoFlag.CORINFO_FLG_PINVOKE; - // See comment in pInvokeMarshalingRequired - result |= CorInfoFlag.CORINFO_FLG_DONT_INLINE; - } - // TODO: Cache inlining hits // Check for an inlining directive. @@ -1037,23 +1032,34 @@ private CorInfoUnmanagedCallConv getUnmanagedCallConv(CORINFO_METHOD_STRUCT_* me return (CorInfoUnmanagedCallConv)unmanagedCallConv; } + private bool IsPInvokeStubRequired(MethodDesc method) + { + return ((Internal.IL.Stubs.PInvokeILStubMethodIL)_compilation.GetMethodIL(method)).IsStubRequired; + } + private bool pInvokeMarshalingRequired(CORINFO_METHOD_STRUCT_* handle, CORINFO_SIG_INFO* callSiteSig) { - // TODO: Support for PInvoke calli with marshalling. For now, assume there is no marshalling required. + // calli is covered by convertPInvokeCalliToCall if (handle == null) + { +#if DEBUG + MethodSignature methodSignature = (MethodSignature)HandleToObject((IntPtr)callSiteSig->pSig); + + MethodDesc stub = _compilation.PInvokeILProvider.GetCalliStub(methodSignature); + Debug.Assert(!IsPInvokeStubRequired(stub)); +#endif + return false; + } MethodDesc method = HandleToObject(handle); if (method.IsRawPInvoke()) return false; - // TODO: Ideally, we would just give back the PInvoke stub IL to the JIT and let it inline it, without - // checking whether it is required upfront. Unfortunatelly, RyuJIT is not able to generate PInvoke - // transitions in inlined methods today (impCheckForPInvokeCall is not called for inlinees and number of other places - // depend on it). To get a decent code with this limitation, we mirror CoreCLR behavior: Check - // whether PInvoke stub is required here, and disable inlining of PInvoke methods in getMethodAttribsInternal. - return ((Internal.IL.Stubs.PInvokeILStubMethodIL)_compilation.GetMethodIL(method)).IsStubRequired; + // We could have given back the PInvoke stub IL to the JIT and let it inline it, without + // checking whether there is any stub required. Save the JIT from doing the inlining by checking upfront. + return IsPInvokeStubRequired(method); } private bool satisfiesMethodConstraints(CORINFO_CLASS_STRUCT_* parent, CORINFO_METHOD_STRUCT_* method) @@ -3450,8 +3456,30 @@ private void MethodCompileComplete(CORINFO_METHOD_STRUCT_* methHnd) private bool convertPInvokeCalliToCall(ref CORINFO_RESOLVED_TOKEN pResolvedToken, bool mustConvert) { - Debug.Assert(!mustConvert); - return false; + var methodIL = (MethodIL)HandleToObject((IntPtr)pResolvedToken.tokenScope); + if (methodIL.OwningMethod.IsPInvoke) + { + return false; + } + + MethodSignature signature = (MethodSignature)methodIL.GetObject((int)pResolvedToken.token); + + CorInfoCallConv callConv = (CorInfoCallConv)(signature.Flags & MethodSignatureFlags.UnmanagedCallingConventionMask); + if (callConv != CorInfoCallConv.CORINFO_CALLCONV_C && + callConv != CorInfoCallConv.CORINFO_CALLCONV_STDCALL && + callConv != CorInfoCallConv.CORINFO_CALLCONV_THISCALL && + callConv != CorInfoCallConv.CORINFO_CALLCONV_FASTCALL) + { + return false; + } + + MethodDesc stub = _compilation.PInvokeILProvider.GetCalliStub(signature); + if (!mustConvert && !IsPInvokeStubRequired(stub)) + return false; + + pResolvedToken.hMethod = ObjectToHandle(stub); + pResolvedToken.hClass = ObjectToHandle(stub.OwningType); + return true; } private void* getMemoryManager() diff --git a/tests/CoreCLR.issues.targets b/tests/CoreCLR.issues.targets index a2efda51848..d5001d14549 100644 --- a/tests/CoreCLR.issues.targets +++ b/tests/CoreCLR.issues.targets @@ -2,12 +2,6 @@ xmlns="http://schemas.microsoft.com/developer/msbuild/2003" > - - - - - - @@ -266,8 +260,6 @@ - - From 766ced933310b87e21ebac18458957e54750912a Mon Sep 17 00:00:00 2001 From: Tanner Gooding Date: Sat, 30 Jun 2018 12:10:40 -0700 Subject: [PATCH 43/69] Updating the Avx.Extract/Insert methods to throw PNSE when IsSupported is false a Signed-off-by: dotnet-bot --- .../System/Runtime/Intrinsics/X86/Avx.cs | 30 +++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Avx.cs b/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Avx.cs index 63e0e29efd0..2115e9609b3 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Avx.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/Intrinsics/X86/Avx.cs @@ -241,6 +241,10 @@ public static class Avx /// public static byte Extract(Vector256 value, byte index) { + if (!IsSupported) + { + throw new PlatformNotSupportedException(); + } return Unsafe.Add(ref Unsafe.As, byte>(ref value), index & 0x1F); } @@ -251,6 +255,10 @@ public static byte Extract(Vector256 value, byte index) /// public static ushort Extract(Vector256 value, byte index) { + if (!IsSupported) + { + throw new PlatformNotSupportedException(); + } return Unsafe.Add(ref Unsafe.As, ushort>(ref value), index & 0xF); } @@ -260,6 +268,10 @@ public static ushort Extract(Vector256 value, byte index) /// public static int Extract(Vector256 value, byte index) { + if (!IsSupported) + { + throw new PlatformNotSupportedException(); + } return Unsafe.Add(ref Unsafe.As, int>(ref value), index & 0x7); } @@ -269,6 +281,10 @@ public static int Extract(Vector256 value, byte index) /// public static uint Extract(Vector256 value, byte index) { + if (!IsSupported) + { + throw new PlatformNotSupportedException(); + } return Unsafe.Add(ref Unsafe.As, uint>(ref value), index & 0x7); } @@ -278,7 +294,7 @@ public static uint Extract(Vector256 value, byte index) /// public static long Extract(Vector256 value, byte index) { - if (IntPtr.Size != 8) + if (!IsSupported || (IntPtr.Size != 8)) { throw new PlatformNotSupportedException(); } @@ -291,7 +307,7 @@ public static long Extract(Vector256 value, byte index) /// public static ulong Extract(Vector256 value, byte index) { - if (IntPtr.Size != 8) + if (!IsSupported || (IntPtr.Size != 8)) { throw new PlatformNotSupportedException(); } @@ -523,6 +539,11 @@ public static Vector256 Insert(Vector256 value, uint data, byte inde /// public static Vector256 Insert(Vector256 value, long data, byte index) { + if (IntPtr.Size != 8) + { + throw new PlatformNotSupportedException(); + } + unsafe { index &= 0x3; @@ -539,6 +560,11 @@ public static Vector256 Insert(Vector256 value, long data, byte inde /// public static Vector256 Insert(Vector256 value, ulong data, byte index) { + if (IntPtr.Size != 8) + { + throw new PlatformNotSupportedException(); + } + unsafe { index &= 0x3; From a49a6cd2e05ff208b5e2b1ce6295dab02b66bb59 Mon Sep 17 00:00:00 2001 From: Fadi Hanna Date: Mon, 2 Jul 2018 18:57:56 -0700 Subject: [PATCH 44/69] Fixing HFA issues on arm64 in the CallInterceptor infrastructure. The issue is that the FP blocks in the TransitionBlock or return block in the CallDescrData use 64 bit slots for floats and doubles, because the S and D registers on ARM64 overlap. However, the locals blocks used by the call interceptor logic do not have such overlapping, and use regular 32-bit floats in HFA structs. These changes replace the simple memcopy operations that the call interceptor was using to read/write HFA structs between locals blocks and native transition blocks with correct copy operations of individual float values, to properly form HFA structs in memory. [tfs-changeset: 1706403] --- .../Runtime/TypeLoader/CallInterceptor.cs | 246 +++++++++++++++--- 1 file changed, 210 insertions(+), 36 deletions(-) diff --git a/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallInterceptor.cs b/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallInterceptor.cs index b26dd803f5e..e7fc86fa800 100644 --- a/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallInterceptor.cs +++ b/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallInterceptor.cs @@ -95,6 +95,9 @@ public unsafe T GetVar(int index) { address = *(IntPtr*)address.ToPointer(); } +#if CCCONVERTER_TRACE + CallingConventionConverterLogger.WriteLine("READ " + (_types[index].ByRef ? "ByRef " : "") + "LocalVariableSet, _pbMemory:" + new IntPtr(_pbMemory).LowLevelToString() + "[" + index.LowLevelToString() + "]. " + _types[index].TypeInstanceFieldSize.LowLevelToString() + " bytes <- [" + address.LowLevelToString() + "]"); +#endif return Unsafe.Read((void*)address); } @@ -108,6 +111,9 @@ public unsafe void SetVar(int index, T value) { address = *(IntPtr*)address.ToPointer(); } +#if CCCONVERTER_TRACE + CallingConventionConverterLogger.WriteLine("WRITE " + (_types[index].ByRef ? "ByRef " : "") + "LocalVariableSet, _pbMemory:" + new IntPtr(_pbMemory).LowLevelToString() + "[" + index.LowLevelToString() + "]. " + _types[index].TypeInstanceFieldSize.LowLevelToString() + " bytes -> [" + address.LowLevelToString() + "]"); +#endif Unsafe.Write((void*)address, value); } @@ -259,7 +265,7 @@ public unsafe void DumpDebugInfo() /// /// Abstraction for the type information needed to be a local /// - public struct LocalVariableType + public unsafe struct LocalVariableType { public LocalVariableType(RuntimeTypeHandle typeHandle, bool pinned, bool byRef) { @@ -276,13 +282,10 @@ internal int TypeInstanceFieldSize { get { - unsafe - { - if (IsValueType) - return (int)TypeHandle.ToEETypePtr()->ValueTypeSize; - else - return IntPtr.Size; - } + if (IsValueType) + return (int)TypeHandle.ToEETypePtr()->ValueTypeSize; + else + return IntPtr.Size; } } @@ -290,10 +293,7 @@ internal int TypeInstanceFieldAlignment { get { - unsafe - { - return (int)TypeHandle.ToEETypePtr()->FieldAlignmentRequirement; - } + return (int)TypeHandle.ToEETypePtr()->FieldAlignmentRequirement; } } @@ -301,10 +301,35 @@ internal bool IsValueType { get { - unsafe - { - return TypeHandle.ToEETypePtr()->IsValueType; - } + return TypeHandle.ToEETypePtr()->IsValueType; + } + } + + internal bool IsHFA + { + get + { +#if ARM || ARM64 + return TypeHandle.ToEETypePtr()->IsHFA; +#else + return false; +#endif + } + } + + internal CorElementType HFAType + { + get + { + Debug.Assert(IsHFA); +#if ARM + return RequiresAlign8() ? CorElementType.ELEMENT_TYPE_R8 : CorElementType.ELEMENT_TYPE_R4; +#elif ARM64 + return (TypeHandle.ToEETypePtr()->FieldAlignmentRequirement == IntPtr.Size) ? CorElementType.ELEMENT_TYPE_R8 : CorElementType.ELEMENT_TYPE_R4; +#else + Debug.Assert(false /* UNREACHABLE */); + return CorElementType.ELEMENT_TYPE_END; +#endif } } } @@ -510,16 +535,38 @@ private static CallConversionOperation[] ProduceOpcodesForDynamicCall(CallingCon break; default: - callConversionOps.Add(new CallConversionOperation( - CallConversionOperation.OpCode.COPY_X_BYTES_FROM_LOCALBLOCK_Y_POINTER_Z_TO_OFFSET_W_IN_TRANSITION_BLOCK, - calleeArgs.GetArgSize(), - CallConversionInterpreter.ArgBlock, - i, - ofsCallee + { +#if ARM64 + if (ofsCallee < 0 && argTypeHandle.IsHFA() && argTypeHandle.GetHFAType() == CorElementType.ELEMENT_TYPE_R4) + { + // S and D registers overlap. The FP block of the transition block has 64-bit slots that are used for both floats and doubles. + // When dealing with float HFAs, we need to copy the 32-bit floats into the 64-bit slots to match the format of the transition block's FP block. + + callConversionOps.Add(new CallConversionOperation( + CallConversionOperation.OpCode.ARM64_COPY_X_HFA_FLOATS_FROM_LOCALBLOCK_Y_POINTER_Z_TO_OFFSET_W_IN_TRANSITION_BLOCK, + (int)argTypeHandle.GetSize() / 4, + CallConversionInterpreter.ArgBlock, + i, + ofsCallee #if CCCONVERTER_TRACE - , "Arg #" + i.LowLevelToString() + , "Arg #" + i.LowLevelToString() #endif - )); + )); + break; + } +#endif + + callConversionOps.Add(new CallConversionOperation( + CallConversionOperation.OpCode.COPY_X_BYTES_FROM_LOCALBLOCK_Y_POINTER_Z_TO_OFFSET_W_IN_TRANSITION_BLOCK, + calleeArgs.GetArgSize(), + CallConversionInterpreter.ArgBlock, + i, + ofsCallee +#if CCCONVERTER_TRACE + , "Arg #" + i.LowLevelToString() +#endif + )); + } break; } } @@ -556,8 +603,20 @@ private static CallConversionOperation[] ProduceOpcodesForDynamicCall(CallingCon } else { - // Copy from return buffer into return value local - callConversionOps.Add(new CallConversionOperation(CallConversionOperation.OpCode.COPY_X_BYTES_FROM_RETBUF_TO_LOCALBLOCK_Y_POINTER_Z, checked((int)returnType.GetSize()), CallConversionInterpreter.ArgBlock, 0)); +#if ARM64 + if (returnType.IsHFA() && returnType.GetHFAType() == CorElementType.ELEMENT_TYPE_R4) + { + // S and D registers overlap. The return buffer has 64-bit slots that are used for both floats and doubles. + // When dealing with float HFAs, we need to copy 32-bit float values from the 64-bit slots of the return buffer (A simple memcopy won't work here). + + callConversionOps.Add(new CallConversionOperation(CallConversionOperation.OpCode.ARM64_COPY_X_HFA_FLOATS_FROM_RETBUF_TO_LOCALBLOCK_Y_POINTER_Z, checked((int)returnType.GetSize() / 4), CallConversionInterpreter.ArgBlock, 0)); + } + else +#endif + { + // Copy from return buffer into return value local + callConversionOps.Add(new CallConversionOperation(CallConversionOperation.OpCode.COPY_X_BYTES_FROM_RETBUF_TO_LOCALBLOCK_Y_POINTER_Z, checked((int)returnType.GetSize()), CallConversionInterpreter.ArgBlock, 0)); + } } } @@ -640,7 +699,7 @@ public string DebugString s = "RETURN_RETBUF_FROM_OFFSET_X_IN_TRANSITION_BLOCK"; break; case OpCode.RETURN_FLOATINGPOINT_BYVALUE_FROM_LOCALBLOCK_X_POINTER_Y_OF_SIZE_Z: - s = "__RETURN_FLOATINGPOINT_BYVALUE_FROM_LOCALBLOCK_X_POINTER_Y_OF_SIZE_Z__"; + s = "RETURN_FLOATINGPOINT_BYVALUE_FROM_LOCALBLOCK_X_POINTER_Y_OF_SIZE_Z"; break; case OpCode.RETURN_INTEGER_BYVALUE_FROM_LOCALBLOCK_X_POINTER_Y_OF_SIZE_Z: s = "RETURN_INTEGER_BYVALUE_FROM_LOCALBLOCK_X_POINTER_Y_OF_SIZE_Z"; @@ -663,6 +722,20 @@ public string DebugString case OpCode.COPY_GENERIC_CONTEXT_TO_OFFSET_X_IN_TRANSITION_BLOCK: s = "COPY_GENERIC_CONTEXT_TO_OFFSET_X_IN_TRANSITION_BLOCK"; break; +#if ARM64 + case OpCode.ARM64_COMPACT_X_FLOATS_INTO_HFA_AT_OFFSET_Y_IN_TRANSITION_BLOCK: + s = "ARM64_COMPACT_X_FLOATS_INTO_HFA_AT_OFFSET_Y_IN_TRANSITION_BLOCK"; + break; + case OpCode.ARM64_EXPAND_X_FLOATS_INTO_HFA_IN_RETURN_BLOCK: + s = "ARM64_EXPAND_X_FLOATS_INTO_HFA_IN_RETURN_BLOCK"; + break; + case OpCode.ARM64_COPY_X_HFA_FLOATS_FROM_LOCALBLOCK_Y_POINTER_Z_TO_OFFSET_W_IN_TRANSITION_BLOCK: + s = "ARM64_COPY_X_HFA_FLOATS_FROM_LOCALBLOCK_Y_POINTER_Z_TO_OFFSET_W_IN_TRANSITION_BLOCK"; + break; + case OpCode.ARM64_COPY_X_HFA_FLOATS_FROM_RETBUF_TO_LOCALBLOCK_Y_POINTER_Z: + s = "ARM64_COPY_X_HFA_FLOATS_FROM_RETBUF_TO_LOCALBLOCK_Y_POINTER_Z"; + break; +#endif default: s = ""; break; @@ -690,7 +763,7 @@ public string DebugString } #else - public CallConversionOperation(OpCode op, int X, int Y, int Z, int W) + public CallConversionOperation(OpCode op, int X, int Y, int Z, int W) { this.Op = op; this.X = X; @@ -755,7 +828,13 @@ public enum OpCode CALL_DESCR_MANAGED_WITH_RETBUF_AS_LOCALBLOCK_X_POINTER_Y_STACKSLOTS_Z_FPCALLINFO_W, CALL_DESCR_NATIVE_WITH_RETBUF_AS_LOCALBLOCK_X_POINTER_Y_STACKSLOTS_Z_FPCALLINFO_W, COPY_X_BYTES_FROM_RETBUF_TO_LOCALBLOCK_Y_POINTER_Z, - COPY_GENERIC_CONTEXT_TO_OFFSET_X_IN_TRANSITION_BLOCK + COPY_GENERIC_CONTEXT_TO_OFFSET_X_IN_TRANSITION_BLOCK, +#if ARM64 + ARM64_COMPACT_X_FLOATS_INTO_HFA_AT_OFFSET_Y_IN_TRANSITION_BLOCK, + ARM64_EXPAND_X_FLOATS_INTO_HFA_IN_RETURN_BLOCK, + ARM64_COPY_X_HFA_FLOATS_FROM_LOCALBLOCK_Y_POINTER_Z_TO_OFFSET_W_IN_TRANSITION_BLOCK, + ARM64_COPY_X_HFA_FLOATS_FROM_RETBUF_TO_LOCALBLOCK_Y_POINTER_Z +#endif } public OpCode Op; @@ -875,6 +954,73 @@ public static unsafe void Interpret(ref CallConversionInterpreterLocals locals) } break; +#if ARM64 + case CallConversionOperation.OpCode.ARM64_COMPACT_X_FLOATS_INTO_HFA_AT_OFFSET_Y_IN_TRANSITION_BLOCK: + { + Debug.Assert(op.X > 0 && op.X <= 4); + + float* pFPRegs = (float*)(locals.TransitionBlockPtr + op.Y); + for (int i = 1; i < op.X; i++) + pFPRegs[i] = pFPRegs[i * 2]; + +#if CCCONVERTER_TRACE + CallingConventionConverterLogger.WriteLine(" -> Compact " + op.X.LowLevelToString() + " ARM64 HFA floats at [" + new IntPtr(pFPRegs).LowLevelToString() + "]"); +#endif + } + break; + + case CallConversionOperation.OpCode.ARM64_EXPAND_X_FLOATS_INTO_HFA_IN_RETURN_BLOCK: + { + Debug.Assert(op.X > 0 && op.X <= 4); + + byte* pReturnBlock = locals.TransitionBlockPtr + TransitionBlock.GetOffsetOfFloatArgumentRegisters(); + for (int i = op.X - 1; i >= 0; i--) + { + float value = ((float*)pReturnBlock)[i]; + *((IntPtr*)pReturnBlock + i) = IntPtr.Zero; // Clear destination slot to zeros before copying the float value + *((float*)((IntPtr*)pReturnBlock + i)) = value; + } + +#if CCCONVERTER_TRACE + CallingConventionConverterLogger.WriteLine(" -> Expand " + op.X.LowLevelToString() + " ARM64 HFA floats at [" + new IntPtr(pReturnBlock).LowLevelToString() + "]"); +#endif + } + break; + + case CallConversionOperation.OpCode.ARM64_COPY_X_HFA_FLOATS_FROM_LOCALBLOCK_Y_POINTER_Z_TO_OFFSET_W_IN_TRANSITION_BLOCK: + { + Debug.Assert(op.X > 0 && op.X <= 4); + + float* pSrc = (float*)(locals.GetLocalBlock(op.Y).GetRawMemoryPointer()[op.Z]); + float* pDst = (float*)(locals.TransitionBlockPtr + op.W); + for (int i = 0; i < op.X; i++) + { + ((IntPtr*)pDst)[i] = IntPtr.Zero; // Clear destination slot to zeros before copying the float value + pDst[i * 2] = pSrc[i]; + } + +#if CCCONVERTER_TRACE + CallingConventionConverterLogger.WriteLine(" -> Copy " + op.X.LowLevelToString() + " ARM64 HFA floats from [" + new IntPtr(pSrc).LowLevelToString() + "] to [" + new IntPtr(pDst).LowLevelToString() + "]"); +#endif + } + break; + + case CallConversionOperation.OpCode.ARM64_COPY_X_HFA_FLOATS_FROM_RETBUF_TO_LOCALBLOCK_Y_POINTER_Z: + { + Debug.Assert(op.X > 0 && op.X <= 4); + + float* pSrc = (float*)locals.IntPtrReturnVal.ToPointer(); + float* pDst = (float*)(locals.GetLocalBlock(op.Y).GetRawMemoryPointer()[op.Z].ToPointer()); + for (int i = 0; i < op.X; i++) + pDst[i] = pSrc[i * 2]; + +#if CCCONVERTER_TRACE + CallingConventionConverterLogger.WriteLine(" -> Copy " + op.X.LowLevelToString() + " ARM64 HFA floats from [" + new IntPtr(pSrc).LowLevelToString() + "] to [" + new IntPtr(pDst).LowLevelToString() + "]"); +#endif + } + break; +#endif + case CallConversionOperation.OpCode.COPY_X_BYTES_FROM_LOCALBLOCK_Y_OFFSET_Z_IN_LOCALBLOCK_TO_OFFSET_W_IN_TRANSITION_BLOCK: { void* pSrc = ((byte*)locals.GetLocalBlock(op.Y).GetRawMemoryPointer()) + op.Z; @@ -1064,15 +1210,15 @@ public static unsafe void Interpret(ref CallConversionInterpreterLocals locals) case CallConversionOperation.OpCode.RETURN_FLOATINGPOINT_BYVALUE_FROM_LOCALBLOCK_X_POINTER_Y_OF_SIZE_Z: { #if CALLDESCR_FPARGREGSARERETURNREGS - byte* returnBlock = locals.TransitionBlockPtr + TransitionBlock.GetOffsetOfFloatArgumentRegisters(); - MemoryHelpers.Memset((IntPtr)returnBlock, IntPtr.Size, 0); - Buffer.MemoryCopy(locals.GetLocalBlock(op.X).GetRawMemoryPointer()[op.Y].ToPointer(), returnBlock, op.Z, op.Z); + byte* pReturnBlock = locals.TransitionBlockPtr + TransitionBlock.GetOffsetOfFloatArgumentRegisters(); + MemoryHelpers.Memset((IntPtr)pReturnBlock, IntPtr.Size, 0); + Buffer.MemoryCopy(locals.GetLocalBlock(op.X).GetRawMemoryPointer()[op.Y].ToPointer(), pReturnBlock, op.Z, op.Z); locals.IntPtrReturnVal = CallConverterThunk.ReturnVoidReturnThunk; #elif X86 CallConverterThunk.SetupCallerActualReturnData(locals.TransitionBlockPtr); - fixed (ReturnBlock* retBlk = &CallConverterThunk.t_NonArgRegisterReturnSpace) + fixed (ReturnBlock* pReturnBlock = &CallConverterThunk.t_NonArgRegisterReturnSpace) { - Buffer.MemoryCopy(locals.GetLocalBlock(op.X).GetRawMemoryPointer()[op.Y].ToPointer(), retBlk, op.Z, op.Z); + Buffer.MemoryCopy(locals.GetLocalBlock(op.X).GetRawMemoryPointer()[op.Y].ToPointer(), pReturnBlock, op.Z, op.Z); } if (op.Z == 4) { @@ -1446,8 +1592,10 @@ private CallConversionOperation[] BuildOpsListForThunk(CallingConvention calling { int ofsCaller = callerArgs.GetNextOffset(); - TypeHandle dummyTypeHandle; - if (callerArgs.IsArgPassedByRef() && callerArgs.GetArgType(out dummyTypeHandle) != CorElementType.ELEMENT_TYPE_BYREF) + TypeHandle argTypeHandle; + CorElementType argType = callerArgs.GetArgType(out argTypeHandle); + + if (callerArgs.IsArgPassedByRef() && argType != CorElementType.ELEMENT_TYPE_BYREF) { callConversionOps.Add(new CallConversionOperation( CallConversionOperation.OpCode.COPY_X_BYTES_TO_LOCALBLOCK_Y_OFFSET_Z_IN_LOCALBLOCK_FROM_OFFSET_W_IN_TRANSITION_BLOCK, @@ -1462,6 +1610,24 @@ private CallConversionOperation[] BuildOpsListForThunk(CallingConvention calling } else { +#if ARM64 + if (ofsCaller < 0 && argTypeHandle.IsHFA() && argTypeHandle.GetHFAType() == CorElementType.ELEMENT_TYPE_R4) + { + // S and D registers overlap. The FP block of the transition block will have the float values of the HFA struct stored in 64-bit slots. We cannot directly + // memcopy or point at these values without first re-writing them as consecutive 32-bit float values + + callConversionOps.Add(new CallConversionOperation( + CallConversionOperation.OpCode.ARM64_COMPACT_X_FLOATS_INTO_HFA_AT_OFFSET_Y_IN_TRANSITION_BLOCK, + (int)argTypeHandle.GetSize() / 4, + ofsCaller, + 0 +#if CCCONVERTER_TRACE + , "Arg #" + i.LowLevelToString() +#endif + )); + } +#endif + callConversionOps.Add(new CallConversionOperation( CallConversionOperation.OpCode.SET_LOCALBLOCK_X_POINTER_Y_TO_OFFSET_Z_IN_TRANSITION_BLOCK, CallConversionInterpreter.ArgBlock, @@ -1492,6 +1658,14 @@ private CallConversionOperation[] BuildOpsListForThunk(CallingConvention calling else if (callerArgs.GetFPReturnSize() > 0) { callConversionOps.Add(new CallConversionOperation(CallConversionOperation.OpCode.RETURN_FLOATINGPOINT_BYVALUE_FROM_LOCALBLOCK_X_POINTER_Y_OF_SIZE_Z, CallConversionInterpreter.ArgBlock, 0, checked((int)callerArgs.GetFPReturnSize()))); + +#if ARM64 + if (returnType.IsHFA() && returnType.GetHFAType() == CorElementType.ELEMENT_TYPE_R4) + { + // S and D registers overlap, so we need to re-write the float values into 64-bit slots to match the format of the UniversalTransitionBlock's FP return block + callConversionOps.Add(new CallConversionOperation(CallConversionOperation.OpCode.ARM64_EXPAND_X_FLOATS_INTO_HFA_IN_RETURN_BLOCK, (int)returnType.GetSize() / 4, 0, 0)); + } +#endif } else { From 2152ccc2c599768663281aa67cb2155f1610f248 Mon Sep 17 00:00:00 2001 From: Brian Robbins Date: Mon, 2 Jul 2018 15:08:32 -0700 Subject: [PATCH 45/69] Dispatch Runtime Events to EventListener (dotnet/coreclr#18649) Signed-off-by: dotnet-bot --- .../System/Diagnostics/Tracing/EventSource.cs | 21 ++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventSource.cs b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventSource.cs index e76653215e6..162026754e4 100644 --- a/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventSource.cs +++ b/src/System.Private.CoreLib/shared/System/Diagnostics/Tracing/EventSource.cs @@ -2025,7 +2025,7 @@ private unsafe void WriteToAllListeners(int eventId, Guid* activityID, Guid* chi } // helper for writing to all EventListeners attached the current eventSource. - private unsafe void WriteToAllListeners(int eventId, Guid* activityID, Guid* childActivityID, params object[] args) + internal unsafe void WriteToAllListeners(int eventId, Guid* activityID, Guid* childActivityID, params object[] args) { EventWrittenEventArgs eventCallbackArgs = new EventWrittenEventArgs(this); eventCallbackArgs.EventId = eventId; @@ -3948,6 +3948,13 @@ public void EnableEvents(EventSource eventSource, EventLevel level, EventKeyword } eventSource.SendCommand(this, EventProviderType.None, 0, 0, EventCommand.Update, true, level, matchAnyKeyword, arguments); + +#if FEATURE_PERFTRACING + if (eventSource.GetType() == typeof(RuntimeEventSource)) + { + EventPipeEventDispatcher.Instance.SendCommand(this, EventCommand.Update, true, level, matchAnyKeyword); + } +#endif // FEATURE_PERFTRACING } /// /// Disables all events coming from eventSource identified by 'eventSource'. @@ -3962,6 +3969,13 @@ public void DisableEvents(EventSource eventSource) } eventSource.SendCommand(this, EventProviderType.None, 0, 0, EventCommand.Update, false, EventLevel.LogAlways, EventKeywords.None, null); + +#if FEATURE_PERFTRACING + if (eventSource.GetType() == typeof(RuntimeEventSource)) + { + EventPipeEventDispatcher.Instance.SendCommand(this, EventCommand.Update, false, EventLevel.LogAlways, EventKeywords.None); + } +#endif // FEATURE_PERFTRACING } /// @@ -4133,6 +4147,11 @@ private static void RemoveReferencesToListenerInEventSources(EventListener liste } } } + +#if FEATURE_PERFTRACING + // Remove the listener from the EventPipe dispatcher. + EventPipeEventDispatcher.Instance.RemoveEventListener(listenerToRemove); +#endif // FEATURE_PERFTRACING } /// From d511215822ff90298d1e1b7b9cd58c0197d54fbe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michal=20Strehovsk=C3=BD?= Date: Tue, 3 Jul 2018 05:17:24 +0200 Subject: [PATCH 46/69] Fix stack slot kind for ByReference.get_Value in CppCodegen (#6034) * Fix stack slot kind for ByReference.get_Value in CppCodegen This should be tracked as a ByRef. This was the reason why the compiler was considering `MemoryMarshal.GetNonNullPinnableReference` invalid IL and we were generating a throwing body for it. * Include cast --- src/ILCompiler.CppCodeGen/src/CppCodeGen/ILToCppImporter.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/ILCompiler.CppCodeGen/src/CppCodeGen/ILToCppImporter.cs b/src/ILCompiler.CppCodeGen/src/CppCodeGen/ILToCppImporter.cs index 92ac9790200..33ab17d76f4 100644 --- a/src/ILCompiler.CppCodeGen/src/CppCodeGen/ILToCppImporter.cs +++ b/src/ILCompiler.CppCodeGen/src/CppCodeGen/ILToCppImporter.cs @@ -1003,8 +1003,9 @@ private bool ImportIntrinsicCall(MethodDesc method) if (IsTypeName(method, "System", "ByReference`1")) { var thisRef = _stack.Pop(); - - PushExpression(StackValueKind.ValueType, ((ExpressionEntry)thisRef).Name + "->_value", method.Signature.ReturnType); + PushExpression(StackValueKind.ByRef, + String.Concat("(", GetSignatureTypeNameAndAddReference(method.Signature.ReturnType), ")", ((ExpressionEntry)thisRef).Name, "->_value"), + method.Signature.ReturnType); return true; } break; From 64b344ca9f05792c9addd291faa69f669424e115 Mon Sep 17 00:00:00 2001 From: Marco Rossignoli Date: Tue, 3 Jul 2018 06:38:33 +0200 Subject: [PATCH 47/69] Add back most CreateInstance APIs to AppDomain and Activator (#18751) * add ObjectHandle.cs * add signature placeholder * move CreateInstance from netfx * move CreateInstanceFrom from netfx * nit: visibility, text formatting Signed-off-by: dotnet-bot --- .../System.Private.CoreLib.Shared.projitems | 1 + .../System/Runtime/Remoting/ObjectHandle.cs | 25 +++++++++++++++++++ 2 files changed, 26 insertions(+) create mode 100644 src/System.Private.CoreLib/shared/System/Runtime/Remoting/ObjectHandle.cs diff --git a/src/System.Private.CoreLib/shared/System.Private.CoreLib.Shared.projitems b/src/System.Private.CoreLib/shared/System.Private.CoreLib.Shared.projitems index 59a3074ab8b..19c48e87df5 100644 --- a/src/System.Private.CoreLib/shared/System.Private.CoreLib.Shared.projitems +++ b/src/System.Private.CoreLib/shared/System.Private.CoreLib.Shared.projitems @@ -496,6 +496,7 @@ + diff --git a/src/System.Private.CoreLib/shared/System/Runtime/Remoting/ObjectHandle.cs b/src/System.Private.CoreLib/shared/System/Runtime/Remoting/ObjectHandle.cs new file mode 100644 index 00000000000..a47aaf9ca19 --- /dev/null +++ b/src/System.Private.CoreLib/shared/System/Runtime/Remoting/ObjectHandle.cs @@ -0,0 +1,25 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +namespace System.Runtime.Remoting +{ + public class ObjectHandle : MarshalByRefObject + { + private object _wrappedObject; + + private ObjectHandle() + { + } + + public ObjectHandle(object o) + { + _wrappedObject = o; + } + + public object Unwrap() + { + return _wrappedObject; + } + } +} From 2886796636ab629b970c0c474b4c494a36b54cc8 Mon Sep 17 00:00:00 2001 From: Anton Lapounov Date: Tue, 3 Jul 2018 17:15:48 -0700 Subject: [PATCH 48/69] Fix dumping cache topology and running debug x86 code on ARM64. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CR: SergeyK • Disable for ARM CPUs the assertion checking that two methods of calculating the CPU cache size produce the same results. • Replace "%zx" with "%Ix" in printf format strings. PalRedhawkMinWin.cpp is a part of mrt100.dll, which is built against the system CRT. The system CRT does not recognize the "z" size prefix added in https://github.com/dotnet/corert/commit/ef7be14256aed0bfeecda13f7687347d4d8ddbe9. [tfs-changeset: 1706474] --- .../Runtime/windows/PalRedhawkMinWin.cpp | 28 +++++++++++-------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/src/Native/Runtime/windows/PalRedhawkMinWin.cpp b/src/Native/Runtime/windows/PalRedhawkMinWin.cpp index b480acb4a6b..16ec4d6fe80 100644 --- a/src/Native/Runtime/windows/PalRedhawkMinWin.cpp +++ b/src/Native/Runtime/windows/PalRedhawkMinWin.cpp @@ -1072,7 +1072,7 @@ void DumpCacheTopology(_In_reads_(cRecords) SYSTEM_LOGICAL_PROCESSOR_INFORMATION switch (pProcInfos[i].Relationship) { case RelationProcessorCore: - printf(" [%2d] Core: %d threads 0x%04zx mask, flags = %d\n", + printf(" [%2d] Core: %d threads 0x%04Ix mask, flags = %d\n", i, CountBits(pProcInfos[i].ProcessorMask), pProcInfos[i].ProcessorMask, pProcInfos[i].ProcessorCore.Flags); break; @@ -1086,16 +1086,16 @@ void DumpCacheTopology(_In_reads_(cRecords) SYSTEM_LOGICAL_PROCESSOR_INFORMATION case CacheTrace: pszCacheType = "[Trace ]"; break; default: pszCacheType = "[Unk ]"; break; } - printf(" [%2d] Cache: %s 0x%08x bytes 0x%04zx mask\n", i, pszCacheType, + printf(" [%2d] Cache: %s 0x%08x bytes 0x%04Ix mask\n", i, pszCacheType, pProcInfos[i].Cache.Size, pProcInfos[i].ProcessorMask); break; case RelationNumaNode: - printf(" [%2d] NumaNode: #%02d 0x%04zx mask\n", + printf(" [%2d] NumaNode: #%02d 0x%04Ix mask\n", i, pProcInfos[i].NumaNode.NodeNumber, pProcInfos[i].ProcessorMask); break; case RelationProcessorPackage: - printf(" [%2d] Package: 0x%04zx mask\n", + printf(" [%2d] Package: 0x%04Ix mask\n", i, pProcInfos[i].ProcessorMask); break; case RelationAll: @@ -1113,8 +1113,8 @@ void DumpCacheTopologyResults(UInt32 maxCpuId, CpuVendor cpuVendor, _In_reads_(c DumpCacheTopology(pProcInfos, cRecords); printf("maxCpuId: %d, %s\n", maxCpuId, (cpuVendor == CpuIntel) ? "CpuIntel" : ((cpuVendor == CpuAMD) ? "CpuAMD" : "CpuUnknown")); printf(" g_cLogicalCpus: %d %d :CLR_GetLogicalCpuCount\n", g_cLogicalCpus, CLR_GetLogicalCpuCount(pProcInfos, cRecords)); - printf(" g_cbLargestOnDieCache: 0x%08zx 0x%08zx :CLR_LargestOnDieCache(TRUE)\n", g_cbLargestOnDieCache, CLR_GetLargestOnDieCacheSize(TRUE, pProcInfos, cRecords)); - printf("g_cbLargestOnDieCacheAdjusted: 0x%08zx 0x%08zx :CLR_LargestOnDieCache(FALSE)\n", g_cbLargestOnDieCacheAdjusted, CLR_GetLargestOnDieCacheSize(FALSE, pProcInfos, cRecords)); + printf(" g_cbLargestOnDieCache: 0x%08Ix 0x%08Ix :CLR_LargestOnDieCache(TRUE)\n", g_cbLargestOnDieCache, CLR_GetLargestOnDieCacheSize(TRUE, pProcInfos, cRecords)); + printf("g_cbLargestOnDieCacheAdjusted: 0x%08Ix 0x%08Ix :CLR_LargestOnDieCache(FALSE)\n", g_cbLargestOnDieCacheAdjusted, CLR_GetLargestOnDieCacheSize(FALSE, pProcInfos, cRecords)); } #endif // _DEBUG @@ -1293,12 +1293,18 @@ bool PalQueryProcessorTopology() #ifdef TRACE_CACHE_TOPOLOGY DumpCacheTopologyResults(maxCpuId, cpuVendor, pProcInfos, cRecords); #endif - if ((CLR_GetLargestOnDieCacheSize(TRUE, pProcInfos, cRecords) != g_cbLargestOnDieCache) || - (CLR_GetLargestOnDieCacheSize(FALSE, pProcInfos, cRecords) != g_cbLargestOnDieCacheAdjusted) || - (CLR_GetLogicalCpuCount(pProcInfos, cRecords) != g_cLogicalCpus)) + // CLR_GetLargestOnDieCacheSize is implemented for Intel and AMD processors only + if ((cpuVendor == CpuIntel) || (cpuVendor == CpuAMD)) { - DumpCacheTopologyResults(maxCpuId, cpuVendor, pProcInfos, cRecords); - assert(!"QueryProcessorTopology doesn't match CLR's results. See stdout for more info."); + if ((CLR_GetLargestOnDieCacheSize(TRUE, pProcInfos, cRecords) != g_cbLargestOnDieCache) || + (CLR_GetLargestOnDieCacheSize(FALSE, pProcInfos, cRecords) != g_cbLargestOnDieCacheAdjusted) || + (CLR_GetLogicalCpuCount(pProcInfos, cRecords) != g_cLogicalCpus)) + { +#ifndef TRACE_CACHE_TOPOLOGY + DumpCacheTopologyResults(maxCpuId, cpuVendor, pProcInfos, cRecords); +#endif + assert(!"QueryProcessorTopology doesn't match CLR's results. See stdout for more info."); + } } #endif // _DEBUG } From 2b657a50d4468339ea91e655cdf322dd6a51f2ae Mon Sep 17 00:00:00 2001 From: Morgan Brown Date: Tue, 3 Jul 2018 18:44:23 -0700 Subject: [PATCH 49/69] Roll back build break [tfs-changeset: 1706486] --- .../Runtime/TypeLoader/CallInterceptor.cs | 246 +++--------------- 1 file changed, 36 insertions(+), 210 deletions(-) diff --git a/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallInterceptor.cs b/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallInterceptor.cs index e7fc86fa800..b26dd803f5e 100644 --- a/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallInterceptor.cs +++ b/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallInterceptor.cs @@ -95,9 +95,6 @@ public unsafe T GetVar(int index) { address = *(IntPtr*)address.ToPointer(); } -#if CCCONVERTER_TRACE - CallingConventionConverterLogger.WriteLine("READ " + (_types[index].ByRef ? "ByRef " : "") + "LocalVariableSet, _pbMemory:" + new IntPtr(_pbMemory).LowLevelToString() + "[" + index.LowLevelToString() + "]. " + _types[index].TypeInstanceFieldSize.LowLevelToString() + " bytes <- [" + address.LowLevelToString() + "]"); -#endif return Unsafe.Read((void*)address); } @@ -111,9 +108,6 @@ public unsafe void SetVar(int index, T value) { address = *(IntPtr*)address.ToPointer(); } -#if CCCONVERTER_TRACE - CallingConventionConverterLogger.WriteLine("WRITE " + (_types[index].ByRef ? "ByRef " : "") + "LocalVariableSet, _pbMemory:" + new IntPtr(_pbMemory).LowLevelToString() + "[" + index.LowLevelToString() + "]. " + _types[index].TypeInstanceFieldSize.LowLevelToString() + " bytes -> [" + address.LowLevelToString() + "]"); -#endif Unsafe.Write((void*)address, value); } @@ -265,7 +259,7 @@ public unsafe void DumpDebugInfo() /// /// Abstraction for the type information needed to be a local /// - public unsafe struct LocalVariableType + public struct LocalVariableType { public LocalVariableType(RuntimeTypeHandle typeHandle, bool pinned, bool byRef) { @@ -282,10 +276,13 @@ internal int TypeInstanceFieldSize { get { - if (IsValueType) - return (int)TypeHandle.ToEETypePtr()->ValueTypeSize; - else - return IntPtr.Size; + unsafe + { + if (IsValueType) + return (int)TypeHandle.ToEETypePtr()->ValueTypeSize; + else + return IntPtr.Size; + } } } @@ -293,7 +290,10 @@ internal int TypeInstanceFieldAlignment { get { - return (int)TypeHandle.ToEETypePtr()->FieldAlignmentRequirement; + unsafe + { + return (int)TypeHandle.ToEETypePtr()->FieldAlignmentRequirement; + } } } @@ -301,35 +301,10 @@ internal bool IsValueType { get { - return TypeHandle.ToEETypePtr()->IsValueType; - } - } - - internal bool IsHFA - { - get - { -#if ARM || ARM64 - return TypeHandle.ToEETypePtr()->IsHFA; -#else - return false; -#endif - } - } - - internal CorElementType HFAType - { - get - { - Debug.Assert(IsHFA); -#if ARM - return RequiresAlign8() ? CorElementType.ELEMENT_TYPE_R8 : CorElementType.ELEMENT_TYPE_R4; -#elif ARM64 - return (TypeHandle.ToEETypePtr()->FieldAlignmentRequirement == IntPtr.Size) ? CorElementType.ELEMENT_TYPE_R8 : CorElementType.ELEMENT_TYPE_R4; -#else - Debug.Assert(false /* UNREACHABLE */); - return CorElementType.ELEMENT_TYPE_END; -#endif + unsafe + { + return TypeHandle.ToEETypePtr()->IsValueType; + } } } } @@ -535,38 +510,16 @@ private static CallConversionOperation[] ProduceOpcodesForDynamicCall(CallingCon break; default: - { -#if ARM64 - if (ofsCallee < 0 && argTypeHandle.IsHFA() && argTypeHandle.GetHFAType() == CorElementType.ELEMENT_TYPE_R4) - { - // S and D registers overlap. The FP block of the transition block has 64-bit slots that are used for both floats and doubles. - // When dealing with float HFAs, we need to copy the 32-bit floats into the 64-bit slots to match the format of the transition block's FP block. - - callConversionOps.Add(new CallConversionOperation( - CallConversionOperation.OpCode.ARM64_COPY_X_HFA_FLOATS_FROM_LOCALBLOCK_Y_POINTER_Z_TO_OFFSET_W_IN_TRANSITION_BLOCK, - (int)argTypeHandle.GetSize() / 4, - CallConversionInterpreter.ArgBlock, - i, - ofsCallee -#if CCCONVERTER_TRACE - , "Arg #" + i.LowLevelToString() -#endif - )); - break; - } -#endif - - callConversionOps.Add(new CallConversionOperation( - CallConversionOperation.OpCode.COPY_X_BYTES_FROM_LOCALBLOCK_Y_POINTER_Z_TO_OFFSET_W_IN_TRANSITION_BLOCK, - calleeArgs.GetArgSize(), - CallConversionInterpreter.ArgBlock, - i, - ofsCallee + callConversionOps.Add(new CallConversionOperation( + CallConversionOperation.OpCode.COPY_X_BYTES_FROM_LOCALBLOCK_Y_POINTER_Z_TO_OFFSET_W_IN_TRANSITION_BLOCK, + calleeArgs.GetArgSize(), + CallConversionInterpreter.ArgBlock, + i, + ofsCallee #if CCCONVERTER_TRACE - , "Arg #" + i.LowLevelToString() + , "Arg #" + i.LowLevelToString() #endif - )); - } + )); break; } } @@ -603,20 +556,8 @@ private static CallConversionOperation[] ProduceOpcodesForDynamicCall(CallingCon } else { -#if ARM64 - if (returnType.IsHFA() && returnType.GetHFAType() == CorElementType.ELEMENT_TYPE_R4) - { - // S and D registers overlap. The return buffer has 64-bit slots that are used for both floats and doubles. - // When dealing with float HFAs, we need to copy 32-bit float values from the 64-bit slots of the return buffer (A simple memcopy won't work here). - - callConversionOps.Add(new CallConversionOperation(CallConversionOperation.OpCode.ARM64_COPY_X_HFA_FLOATS_FROM_RETBUF_TO_LOCALBLOCK_Y_POINTER_Z, checked((int)returnType.GetSize() / 4), CallConversionInterpreter.ArgBlock, 0)); - } - else -#endif - { - // Copy from return buffer into return value local - callConversionOps.Add(new CallConversionOperation(CallConversionOperation.OpCode.COPY_X_BYTES_FROM_RETBUF_TO_LOCALBLOCK_Y_POINTER_Z, checked((int)returnType.GetSize()), CallConversionInterpreter.ArgBlock, 0)); - } + // Copy from return buffer into return value local + callConversionOps.Add(new CallConversionOperation(CallConversionOperation.OpCode.COPY_X_BYTES_FROM_RETBUF_TO_LOCALBLOCK_Y_POINTER_Z, checked((int)returnType.GetSize()), CallConversionInterpreter.ArgBlock, 0)); } } @@ -699,7 +640,7 @@ public string DebugString s = "RETURN_RETBUF_FROM_OFFSET_X_IN_TRANSITION_BLOCK"; break; case OpCode.RETURN_FLOATINGPOINT_BYVALUE_FROM_LOCALBLOCK_X_POINTER_Y_OF_SIZE_Z: - s = "RETURN_FLOATINGPOINT_BYVALUE_FROM_LOCALBLOCK_X_POINTER_Y_OF_SIZE_Z"; + s = "__RETURN_FLOATINGPOINT_BYVALUE_FROM_LOCALBLOCK_X_POINTER_Y_OF_SIZE_Z__"; break; case OpCode.RETURN_INTEGER_BYVALUE_FROM_LOCALBLOCK_X_POINTER_Y_OF_SIZE_Z: s = "RETURN_INTEGER_BYVALUE_FROM_LOCALBLOCK_X_POINTER_Y_OF_SIZE_Z"; @@ -722,20 +663,6 @@ public string DebugString case OpCode.COPY_GENERIC_CONTEXT_TO_OFFSET_X_IN_TRANSITION_BLOCK: s = "COPY_GENERIC_CONTEXT_TO_OFFSET_X_IN_TRANSITION_BLOCK"; break; -#if ARM64 - case OpCode.ARM64_COMPACT_X_FLOATS_INTO_HFA_AT_OFFSET_Y_IN_TRANSITION_BLOCK: - s = "ARM64_COMPACT_X_FLOATS_INTO_HFA_AT_OFFSET_Y_IN_TRANSITION_BLOCK"; - break; - case OpCode.ARM64_EXPAND_X_FLOATS_INTO_HFA_IN_RETURN_BLOCK: - s = "ARM64_EXPAND_X_FLOATS_INTO_HFA_IN_RETURN_BLOCK"; - break; - case OpCode.ARM64_COPY_X_HFA_FLOATS_FROM_LOCALBLOCK_Y_POINTER_Z_TO_OFFSET_W_IN_TRANSITION_BLOCK: - s = "ARM64_COPY_X_HFA_FLOATS_FROM_LOCALBLOCK_Y_POINTER_Z_TO_OFFSET_W_IN_TRANSITION_BLOCK"; - break; - case OpCode.ARM64_COPY_X_HFA_FLOATS_FROM_RETBUF_TO_LOCALBLOCK_Y_POINTER_Z: - s = "ARM64_COPY_X_HFA_FLOATS_FROM_RETBUF_TO_LOCALBLOCK_Y_POINTER_Z"; - break; -#endif default: s = ""; break; @@ -763,7 +690,7 @@ public string DebugString } #else - public CallConversionOperation(OpCode op, int X, int Y, int Z, int W) + public CallConversionOperation(OpCode op, int X, int Y, int Z, int W) { this.Op = op; this.X = X; @@ -828,13 +755,7 @@ public enum OpCode CALL_DESCR_MANAGED_WITH_RETBUF_AS_LOCALBLOCK_X_POINTER_Y_STACKSLOTS_Z_FPCALLINFO_W, CALL_DESCR_NATIVE_WITH_RETBUF_AS_LOCALBLOCK_X_POINTER_Y_STACKSLOTS_Z_FPCALLINFO_W, COPY_X_BYTES_FROM_RETBUF_TO_LOCALBLOCK_Y_POINTER_Z, - COPY_GENERIC_CONTEXT_TO_OFFSET_X_IN_TRANSITION_BLOCK, -#if ARM64 - ARM64_COMPACT_X_FLOATS_INTO_HFA_AT_OFFSET_Y_IN_TRANSITION_BLOCK, - ARM64_EXPAND_X_FLOATS_INTO_HFA_IN_RETURN_BLOCK, - ARM64_COPY_X_HFA_FLOATS_FROM_LOCALBLOCK_Y_POINTER_Z_TO_OFFSET_W_IN_TRANSITION_BLOCK, - ARM64_COPY_X_HFA_FLOATS_FROM_RETBUF_TO_LOCALBLOCK_Y_POINTER_Z -#endif + COPY_GENERIC_CONTEXT_TO_OFFSET_X_IN_TRANSITION_BLOCK } public OpCode Op; @@ -954,73 +875,6 @@ public static unsafe void Interpret(ref CallConversionInterpreterLocals locals) } break; -#if ARM64 - case CallConversionOperation.OpCode.ARM64_COMPACT_X_FLOATS_INTO_HFA_AT_OFFSET_Y_IN_TRANSITION_BLOCK: - { - Debug.Assert(op.X > 0 && op.X <= 4); - - float* pFPRegs = (float*)(locals.TransitionBlockPtr + op.Y); - for (int i = 1; i < op.X; i++) - pFPRegs[i] = pFPRegs[i * 2]; - -#if CCCONVERTER_TRACE - CallingConventionConverterLogger.WriteLine(" -> Compact " + op.X.LowLevelToString() + " ARM64 HFA floats at [" + new IntPtr(pFPRegs).LowLevelToString() + "]"); -#endif - } - break; - - case CallConversionOperation.OpCode.ARM64_EXPAND_X_FLOATS_INTO_HFA_IN_RETURN_BLOCK: - { - Debug.Assert(op.X > 0 && op.X <= 4); - - byte* pReturnBlock = locals.TransitionBlockPtr + TransitionBlock.GetOffsetOfFloatArgumentRegisters(); - for (int i = op.X - 1; i >= 0; i--) - { - float value = ((float*)pReturnBlock)[i]; - *((IntPtr*)pReturnBlock + i) = IntPtr.Zero; // Clear destination slot to zeros before copying the float value - *((float*)((IntPtr*)pReturnBlock + i)) = value; - } - -#if CCCONVERTER_TRACE - CallingConventionConverterLogger.WriteLine(" -> Expand " + op.X.LowLevelToString() + " ARM64 HFA floats at [" + new IntPtr(pReturnBlock).LowLevelToString() + "]"); -#endif - } - break; - - case CallConversionOperation.OpCode.ARM64_COPY_X_HFA_FLOATS_FROM_LOCALBLOCK_Y_POINTER_Z_TO_OFFSET_W_IN_TRANSITION_BLOCK: - { - Debug.Assert(op.X > 0 && op.X <= 4); - - float* pSrc = (float*)(locals.GetLocalBlock(op.Y).GetRawMemoryPointer()[op.Z]); - float* pDst = (float*)(locals.TransitionBlockPtr + op.W); - for (int i = 0; i < op.X; i++) - { - ((IntPtr*)pDst)[i] = IntPtr.Zero; // Clear destination slot to zeros before copying the float value - pDst[i * 2] = pSrc[i]; - } - -#if CCCONVERTER_TRACE - CallingConventionConverterLogger.WriteLine(" -> Copy " + op.X.LowLevelToString() + " ARM64 HFA floats from [" + new IntPtr(pSrc).LowLevelToString() + "] to [" + new IntPtr(pDst).LowLevelToString() + "]"); -#endif - } - break; - - case CallConversionOperation.OpCode.ARM64_COPY_X_HFA_FLOATS_FROM_RETBUF_TO_LOCALBLOCK_Y_POINTER_Z: - { - Debug.Assert(op.X > 0 && op.X <= 4); - - float* pSrc = (float*)locals.IntPtrReturnVal.ToPointer(); - float* pDst = (float*)(locals.GetLocalBlock(op.Y).GetRawMemoryPointer()[op.Z].ToPointer()); - for (int i = 0; i < op.X; i++) - pDst[i] = pSrc[i * 2]; - -#if CCCONVERTER_TRACE - CallingConventionConverterLogger.WriteLine(" -> Copy " + op.X.LowLevelToString() + " ARM64 HFA floats from [" + new IntPtr(pSrc).LowLevelToString() + "] to [" + new IntPtr(pDst).LowLevelToString() + "]"); -#endif - } - break; -#endif - case CallConversionOperation.OpCode.COPY_X_BYTES_FROM_LOCALBLOCK_Y_OFFSET_Z_IN_LOCALBLOCK_TO_OFFSET_W_IN_TRANSITION_BLOCK: { void* pSrc = ((byte*)locals.GetLocalBlock(op.Y).GetRawMemoryPointer()) + op.Z; @@ -1210,15 +1064,15 @@ public static unsafe void Interpret(ref CallConversionInterpreterLocals locals) case CallConversionOperation.OpCode.RETURN_FLOATINGPOINT_BYVALUE_FROM_LOCALBLOCK_X_POINTER_Y_OF_SIZE_Z: { #if CALLDESCR_FPARGREGSARERETURNREGS - byte* pReturnBlock = locals.TransitionBlockPtr + TransitionBlock.GetOffsetOfFloatArgumentRegisters(); - MemoryHelpers.Memset((IntPtr)pReturnBlock, IntPtr.Size, 0); - Buffer.MemoryCopy(locals.GetLocalBlock(op.X).GetRawMemoryPointer()[op.Y].ToPointer(), pReturnBlock, op.Z, op.Z); + byte* returnBlock = locals.TransitionBlockPtr + TransitionBlock.GetOffsetOfFloatArgumentRegisters(); + MemoryHelpers.Memset((IntPtr)returnBlock, IntPtr.Size, 0); + Buffer.MemoryCopy(locals.GetLocalBlock(op.X).GetRawMemoryPointer()[op.Y].ToPointer(), returnBlock, op.Z, op.Z); locals.IntPtrReturnVal = CallConverterThunk.ReturnVoidReturnThunk; #elif X86 CallConverterThunk.SetupCallerActualReturnData(locals.TransitionBlockPtr); - fixed (ReturnBlock* pReturnBlock = &CallConverterThunk.t_NonArgRegisterReturnSpace) + fixed (ReturnBlock* retBlk = &CallConverterThunk.t_NonArgRegisterReturnSpace) { - Buffer.MemoryCopy(locals.GetLocalBlock(op.X).GetRawMemoryPointer()[op.Y].ToPointer(), pReturnBlock, op.Z, op.Z); + Buffer.MemoryCopy(locals.GetLocalBlock(op.X).GetRawMemoryPointer()[op.Y].ToPointer(), retBlk, op.Z, op.Z); } if (op.Z == 4) { @@ -1592,10 +1446,8 @@ private CallConversionOperation[] BuildOpsListForThunk(CallingConvention calling { int ofsCaller = callerArgs.GetNextOffset(); - TypeHandle argTypeHandle; - CorElementType argType = callerArgs.GetArgType(out argTypeHandle); - - if (callerArgs.IsArgPassedByRef() && argType != CorElementType.ELEMENT_TYPE_BYREF) + TypeHandle dummyTypeHandle; + if (callerArgs.IsArgPassedByRef() && callerArgs.GetArgType(out dummyTypeHandle) != CorElementType.ELEMENT_TYPE_BYREF) { callConversionOps.Add(new CallConversionOperation( CallConversionOperation.OpCode.COPY_X_BYTES_TO_LOCALBLOCK_Y_OFFSET_Z_IN_LOCALBLOCK_FROM_OFFSET_W_IN_TRANSITION_BLOCK, @@ -1610,24 +1462,6 @@ private CallConversionOperation[] BuildOpsListForThunk(CallingConvention calling } else { -#if ARM64 - if (ofsCaller < 0 && argTypeHandle.IsHFA() && argTypeHandle.GetHFAType() == CorElementType.ELEMENT_TYPE_R4) - { - // S and D registers overlap. The FP block of the transition block will have the float values of the HFA struct stored in 64-bit slots. We cannot directly - // memcopy or point at these values without first re-writing them as consecutive 32-bit float values - - callConversionOps.Add(new CallConversionOperation( - CallConversionOperation.OpCode.ARM64_COMPACT_X_FLOATS_INTO_HFA_AT_OFFSET_Y_IN_TRANSITION_BLOCK, - (int)argTypeHandle.GetSize() / 4, - ofsCaller, - 0 -#if CCCONVERTER_TRACE - , "Arg #" + i.LowLevelToString() -#endif - )); - } -#endif - callConversionOps.Add(new CallConversionOperation( CallConversionOperation.OpCode.SET_LOCALBLOCK_X_POINTER_Y_TO_OFFSET_Z_IN_TRANSITION_BLOCK, CallConversionInterpreter.ArgBlock, @@ -1658,14 +1492,6 @@ private CallConversionOperation[] BuildOpsListForThunk(CallingConvention calling else if (callerArgs.GetFPReturnSize() > 0) { callConversionOps.Add(new CallConversionOperation(CallConversionOperation.OpCode.RETURN_FLOATINGPOINT_BYVALUE_FROM_LOCALBLOCK_X_POINTER_Y_OF_SIZE_Z, CallConversionInterpreter.ArgBlock, 0, checked((int)callerArgs.GetFPReturnSize()))); - -#if ARM64 - if (returnType.IsHFA() && returnType.GetHFAType() == CorElementType.ELEMENT_TYPE_R4) - { - // S and D registers overlap, so we need to re-write the float values into 64-bit slots to match the format of the UniversalTransitionBlock's FP return block - callConversionOps.Add(new CallConversionOperation(CallConversionOperation.OpCode.ARM64_EXPAND_X_FLOATS_INTO_HFA_IN_RETURN_BLOCK, (int)returnType.GetSize() / 4, 0, 0)); - } -#endif } else { From 303df5960283a70111bd5e09fcd5e1792a502a36 Mon Sep 17 00:00:00 2001 From: Michal Strehovsky Date: Wed, 4 Jul 2018 02:13:44 -0700 Subject: [PATCH 50/69] Fix MightHaveInterfaceDispatchMap to work with optimized CoreRT builds This applies the same pattern that was added in CS 1706049. Without this, the code was trying to access virtual slot information for things like IFoo, which kind of works in Debug builds, but fails when scanner is used (optimized builds or --scan passed at the command line). [tfs-changeset: 1706526] --- .../InterfaceDispatchMapNode.cs | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/InterfaceDispatchMapNode.cs b/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/InterfaceDispatchMapNode.cs index fb72c8a7cdc..bab5d54e9a7 100644 --- a/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/InterfaceDispatchMapNode.cs +++ b/src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/InterfaceDispatchMapNode.cs @@ -76,10 +76,15 @@ public static bool MightHaveInterfaceDispatchMap(TypeDesc type, NodeFactory fact if (!type.IsArray && !type.IsDefType) return false; - TypeDesc declType = type.GetClosestDefType().GetTypeDefinition(); + TypeDesc declType = type.GetClosestDefType(); - foreach (DefType interfaceType in declType.RuntimeInterfaces) + for (int interfaceIndex = 0; interfaceIndex < declType.RuntimeInterfaces.Length; interfaceIndex++) { + DefType interfaceType = declType.RuntimeInterfaces[interfaceIndex]; + InstantiatedType interfaceOnDefinitionType = interfaceType.IsTypeDefinition ? + null : + (InstantiatedType)declType.GetTypeDefinition().RuntimeInterfaces[interfaceIndex]; + IEnumerable slots; // If the vtable has fixed slots, we can query it directly. @@ -91,12 +96,16 @@ public static bool MightHaveInterfaceDispatchMap(TypeDesc type, NodeFactory fact else slots = interfaceType.GetAllMethods(); - foreach (MethodDesc declMethod in slots) + foreach (MethodDesc slotMethod in slots) { + MethodDesc declMethod = slotMethod; + if (interfaceOnDefinitionType != null) + declMethod = factory.TypeSystemContext.GetMethodForInstantiatedType(declMethod.GetTypicalMethodDefinition(), interfaceOnDefinitionType); + if (declMethod.Signature.IsStatic) continue; - var implMethod = declType.ResolveInterfaceMethodToVirtualMethodOnType(declMethod); + var implMethod = declType.GetTypeDefinition().ResolveInterfaceMethodToVirtualMethodOnType(declMethod); if (implMethod != null) return true; } From 51e9932784b8894413e3a49efeadf42377d10ab2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michal=20Strehovsk=C3=BD?= Date: Wed, 4 Jul 2018 19:40:40 +0200 Subject: [PATCH 51/69] Fix handling of StdCall intrinsic (#6051) The Project N compiler only needs the prefix to match, so matching the behavior here. dotnet/csharplang#1685 can't come soon enough. --- src/Common/src/TypeSystem/IL/ILProvider.cs | 2 +- src/Common/src/TypeSystem/IL/Stubs/CalliIntrinsic.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Common/src/TypeSystem/IL/ILProvider.cs b/src/Common/src/TypeSystem/IL/ILProvider.cs index e583890a3fc..8ea30ad898c 100644 --- a/src/Common/src/TypeSystem/IL/ILProvider.cs +++ b/src/Common/src/TypeSystem/IL/ILProvider.cs @@ -246,7 +246,7 @@ private MethodIL CreateMethodIL(MethodDesc method) if (((MetadataType)method.OwningType).HasCustomAttribute("System.Runtime.InteropServices", "McgIntrinsicsAttribute")) { var name = method.Name; - if (name == "Call" || name == "StdCall") + if (name == "Call" || name.StartsWith("StdCall")) { return CalliIntrinsic.EmitIL(method); } diff --git a/src/Common/src/TypeSystem/IL/Stubs/CalliIntrinsic.cs b/src/Common/src/TypeSystem/IL/Stubs/CalliIntrinsic.cs index 9d509c40f0e..2a39b777952 100644 --- a/src/Common/src/TypeSystem/IL/Stubs/CalliIntrinsic.cs +++ b/src/Common/src/TypeSystem/IL/Stubs/CalliIntrinsic.cs @@ -18,7 +18,7 @@ public static class CalliIntrinsic { public static MethodIL EmitIL(MethodDesc target) { - Debug.Assert(target.Name == "Call" || target.Name == "StdCall"); + Debug.Assert(target.Name == "Call" || target.Name.StartsWith("StdCall")); Debug.Assert(target.Signature.Length > 0 && target.Signature[0] == target.Context.GetWellKnownType(WellKnownType.IntPtr)); From 59c778d6b83e3159db5184dda18e813e85d4cc77 Mon Sep 17 00:00:00 2001 From: Petr Bred Date: Wed, 4 Jul 2018 21:09:02 +0300 Subject: [PATCH 52/69] [Linux] Fix build for new clang versions (#6047) Signed-off-by: Petr Bred --- src/Native/CMakeLists.txt | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/Native/CMakeLists.txt b/src/Native/CMakeLists.txt index 475bf711317..1a3622a0de4 100644 --- a/src/Native/CMakeLists.txt +++ b/src/Native/CMakeLists.txt @@ -95,6 +95,9 @@ if (CLR_CMAKE_PLATFORM_UNIX) add_compile_options(-Wno-null-arithmetic) add_compile_options(-Wno-null-conversion) + # Since 6 version, clang generates pragma-pack warnings, so disable it because we use pshpack[1..8].h/poppack.h + add_compile_options(-Wno-pragmas) + if(CLR_CMAKE_PLATFORM_ARCH_AMD64 OR CLR_CMAKE_PLATFORM_ARCH_I386) # Allow 16 byte compare-exchange add_compile_options(-mcx16) From 583d9e1f8bc8ca7820401dac3f30c87a3326a187 Mon Sep 17 00:00:00 2001 From: Viktor Hofer Date: Wed, 4 Jul 2018 20:56:25 +0200 Subject: [PATCH 53/69] Add LastIndexOf compareoptions overload (dotnet/coreclr#18652) * Add LastIndexOf compareoptions overload Signed-off-by: dotnet-bot --- .../Interop.Collation.cs | 4 +- .../Globalization/CompareInfo.Invariant.cs | 14 +- .../System/Globalization/CompareInfo.Unix.cs | 132 +++++++++++++----- .../Globalization/CompareInfo.Windows.cs | 11 +- .../System/Globalization/CompareInfo.cs | 20 ++- .../shared/System/MemoryExtensions.Fast.cs | 46 +++++- 6 files changed, 169 insertions(+), 58 deletions(-) diff --git a/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Collation.cs b/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Collation.cs index 9942882f1a1..aeeb60ff775 100644 --- a/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Collation.cs +++ b/src/System.Private.CoreLib/shared/Interop/Unix/System.Globalization.Native/Interop.Collation.cs @@ -20,13 +20,11 @@ internal static partial class Globalization [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_CompareString")] internal static extern unsafe int CompareString(SafeSortHandle sortHandle, char* lpStr1, int cwStr1Len, char* lpStr2, int cwStr2Len, CompareOptions options); - [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_IndexOf")] - internal static extern unsafe int IndexOf(SafeSortHandle sortHandle, string target, int cwTargetLength, char* pSource, int cwSourceLength, CompareOptions options, int* matchLengthPtr); [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_IndexOf")] internal static extern unsafe int IndexOf(SafeSortHandle sortHandle, char* target, int cwTargetLength, char* pSource, int cwSourceLength, CompareOptions options, int* matchLengthPtr); [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_LastIndexOf")] - internal static extern unsafe int LastIndexOf(SafeSortHandle sortHandle, string target, int cwTargetLength, char* pSource, int cwSourceLength, CompareOptions options); + internal static extern unsafe int LastIndexOf(SafeSortHandle sortHandle, char* target, int cwTargetLength, char* pSource, int cwSourceLength, CompareOptions options); [DllImport(Libraries.GlobalizationNative, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_IndexOfOrdinalIgnoreCase")] internal static extern unsafe int IndexOfOrdinalIgnoreCase(string target, int cwTargetLength, char* pSource, int cwSourceLength, bool findLast); diff --git a/src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.Invariant.cs b/src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.Invariant.cs index 29e4f53212f..16201b8d1fa 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.Invariant.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.Invariant.cs @@ -18,7 +18,7 @@ internal static unsafe int InvariantIndexOf(string source, string value, int sta fixed (char* pSource = source) fixed (char* pValue = value) { char* pSrc = &pSource[startIndex]; - int index = InvariantFindString(pSrc, count, pValue, value.Length, ignoreCase, start : true); + int index = InvariantFindString(pSrc, count, pValue, value.Length, ignoreCase, fromBeginning : true); if (index >= 0) { return index + startIndex; @@ -27,7 +27,7 @@ internal static unsafe int InvariantIndexOf(string source, string value, int sta } } - internal static unsafe int InvariantIndexOf(ReadOnlySpan source, ReadOnlySpan value, bool ignoreCase) + internal static unsafe int InvariantIndexOf(ReadOnlySpan source, ReadOnlySpan value, bool ignoreCase, bool fromBeginning = true) { Debug.Assert(source.Length != 0); Debug.Assert(value.Length != 0); @@ -35,7 +35,7 @@ internal static unsafe int InvariantIndexOf(ReadOnlySpan source, ReadOnlyS fixed (char* pSource = &MemoryMarshal.GetReference(source)) fixed (char* pValue = &MemoryMarshal.GetReference(value)) { - return InvariantFindString(pSource, source.Length, pValue, value.Length, ignoreCase, start: true); + return InvariantFindString(pSource, source.Length, pValue, value.Length, ignoreCase, fromBeginning); } } @@ -48,7 +48,7 @@ internal static unsafe int InvariantLastIndexOf(string source, string value, int fixed (char* pSource = source) fixed (char* pValue = value) { char* pSrc = &pSource[startIndex - count + 1]; - int index = InvariantFindString(pSrc, count, pValue, value.Length, ignoreCase, start : false); + int index = InvariantFindString(pSrc, count, pValue, value.Length, ignoreCase, fromBeginning : false); if (index >= 0) { return index + startIndex - count + 1; @@ -57,7 +57,7 @@ internal static unsafe int InvariantLastIndexOf(string source, string value, int } } - private static unsafe int InvariantFindString(char* source, int sourceCount, char* value, int valueCount, bool ignoreCase, bool start) + private static unsafe int InvariantFindString(char* source, int sourceCount, char* value, int valueCount, bool ignoreCase, bool fromBeginning) { int ctrSource = 0; // index value into source int ctrValue = 0; // index value into value @@ -72,7 +72,7 @@ private static unsafe int InvariantFindString(char* source, int sourceCount, cha if (valueCount == 0) { - return start ? 0 : sourceCount - 1; + return fromBeginning ? 0 : sourceCount - 1; } if (sourceCount < valueCount) @@ -80,7 +80,7 @@ private static unsafe int InvariantFindString(char* source, int sourceCount, cha return -1; } - if (start) + if (fromBeginning) { lastSourceStart = sourceCount - valueCount; if (ignoreCase) diff --git a/src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.Unix.cs b/src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.Unix.cs index 90e9eba0bbe..f5175400996 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.Unix.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.Unix.cs @@ -88,7 +88,7 @@ internal static unsafe int IndexOfOrdinalCore(string source, string value, int s return -1; } - internal static unsafe int IndexOfOrdinalCore(ReadOnlySpan source, ReadOnlySpan value, bool ignoreCase) + internal static unsafe int IndexOfOrdinalCore(ReadOnlySpan source, ReadOnlySpan value, bool ignoreCase, bool fromBeginning) { Debug.Assert(!GlobalizationMode.Invariant); @@ -105,13 +105,29 @@ internal static unsafe int IndexOfOrdinalCore(ReadOnlySpan source, ReadOnl fixed (char* pSource = &MemoryMarshal.GetReference(source)) fixed (char* pValue = &MemoryMarshal.GetReference(value)) { - int index = Interop.Globalization.IndexOfOrdinalIgnoreCase(pValue, value.Length, pSource, source.Length, findLast: false); - return index; + return Interop.Globalization.IndexOfOrdinalIgnoreCase(pValue, value.Length, pSource, source.Length, findLast: !fromBeginning); } } - int endIndex = source.Length - value.Length; - for (int i = 0; i <= endIndex; i++) + int startIndex, endIndex, jump; + if (fromBeginning) + { + // Left to right, from zero to last possible index in the source string. + // Incrementing by one after each iteration. Stop condition is last possible index plus 1. + startIndex = 0; + endIndex = source.Length - value.Length + 1; + jump = 1; + } + else + { + // Right to left, from first possible index in the source string to zero. + // Decrementing by one after each iteration. Stop condition is last possible index minus 1. + startIndex = source.Length - value.Length; + endIndex = -1; + jump = -1; + } + + for (int i = startIndex; i != endIndex; i += jump) { int valueIndex, sourceIndex; @@ -259,15 +275,16 @@ internal unsafe int IndexOfCore(string source, string target, int startIndex, in #endif fixed (char* pSource = source) + fixed (char* pTarget = target) { - index = Interop.Globalization.IndexOf(_sortHandle, target, target.Length, pSource + startIndex, count, options, matchLengthPtr); + index = Interop.Globalization.IndexOf(_sortHandle, pTarget, target.Length, pSource + startIndex, count, options, matchLengthPtr); return index != -1 ? index + startIndex : -1; } } // For now, this method is only called from Span APIs with either options == CompareOptions.None or CompareOptions.IgnoreCase - internal unsafe int IndexOfCore(ReadOnlySpan source, ReadOnlySpan target, CompareOptions options, int* matchLengthPtr) + internal unsafe int IndexOfCore(ReadOnlySpan source, ReadOnlySpan target, CompareOptions options, int* matchLengthPtr, bool fromBeginning) { Debug.Assert(!_invariantMode); Debug.Assert(source.Length != 0); @@ -276,25 +293,29 @@ internal unsafe int IndexOfCore(ReadOnlySpan source, ReadOnlySpan ta if (_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options)) { if ((options & CompareOptions.IgnoreCase) == CompareOptions.IgnoreCase) - { - return IndexOfOrdinalIgnoreCaseHelper(source, target, options, matchLengthPtr); - } + return IndexOfOrdinalIgnoreCaseHelper(source, target, options, matchLengthPtr, fromBeginning); else - { - return IndexOfOrdinalHelper(source, target, options, matchLengthPtr); - } + return IndexOfOrdinalHelper(source, target, options, matchLengthPtr, fromBeginning); } else { fixed (char* pSource = &MemoryMarshal.GetReference(source)) fixed (char* pTarget = &MemoryMarshal.GetReference(target)) { - return Interop.Globalization.IndexOf(_sortHandle, pTarget, target.Length, pSource, source.Length, options, matchLengthPtr); + if (fromBeginning) + return Interop.Globalization.IndexOf(_sortHandle, pTarget, target.Length, pSource, source.Length, options, matchLengthPtr); + else + return Interop.Globalization.LastIndexOf(_sortHandle, pTarget, target.Length, pSource, source.Length, options); } } } - private unsafe int IndexOfOrdinalIgnoreCaseHelper(ReadOnlySpan source, ReadOnlySpan target, CompareOptions options, int* matchLengthPtr) + /// + /// Duplicate of IndexOfOrdinalHelper that also handles ignore case. Can't converge both methods + /// as the JIT wouldn't be able to optimize the ignoreCase path away. + /// + /// + private unsafe int IndexOfOrdinalIgnoreCaseHelper(ReadOnlySpan source, ReadOnlySpan target, CompareOptions options, int* matchLengthPtr, bool fromBeginning) { Debug.Assert(!_invariantMode); @@ -307,9 +328,8 @@ private unsafe int IndexOfOrdinalIgnoreCaseHelper(ReadOnlySpan source, Rea { char* a = ap; char* b = bp; - int endIndex = source.Length - target.Length; - if (endIndex < 0) + if (target.Length > source.Length) goto InteropCall; for (int j = 0; j < target.Length; j++) @@ -319,20 +339,36 @@ private unsafe int IndexOfOrdinalIgnoreCaseHelper(ReadOnlySpan source, Rea goto InteropCall; } - int i = 0; - for (; i <= endIndex; i++) + int startIndex, endIndex, jump; + if (fromBeginning) + { + // Left to right, from zero to last possible index in the source string. + // Incrementing by one after each iteration. Stop condition is last possible index plus 1. + startIndex = 0; + endIndex = source.Length - target.Length + 1; + jump = 1; + } + else + { + // Right to left, from first possible index in the source string to zero. + // Decrementing by one after each iteration. Stop condition is last possible index minus 1. + startIndex = source.Length - target.Length; + endIndex = -1; + jump = -1; + } + + for (int i = startIndex; i != endIndex; i += jump) { int targetIndex = 0; int sourceIndex = i; - for (; targetIndex < target.Length; targetIndex++) + for (; targetIndex < target.Length; targetIndex++, sourceIndex++) { char valueChar = *(a + sourceIndex); char targetChar = *(b + targetIndex); if (valueChar == targetChar && valueChar < 0x80 && !s_highCharTable[valueChar]) { - sourceIndex++; continue; } @@ -346,7 +382,6 @@ private unsafe int IndexOfOrdinalIgnoreCaseHelper(ReadOnlySpan source, Rea goto InteropCall; else if (valueChar != targetChar) break; - sourceIndex++; } if (targetIndex == target.Length) @@ -356,14 +391,17 @@ private unsafe int IndexOfOrdinalIgnoreCaseHelper(ReadOnlySpan source, Rea return i; } } - if (i > endIndex) - return -1; - InteropCall: - return Interop.Globalization.IndexOf(_sortHandle, b, target.Length, a, source.Length, options, matchLengthPtr); + + return -1; + InteropCall: + if (fromBeginning) + return Interop.Globalization.IndexOf(_sortHandle, b, target.Length, a, source.Length, options, matchLengthPtr); + else + return Interop.Globalization.LastIndexOf(_sortHandle, b, target.Length, a, source.Length, options); } } - private unsafe int IndexOfOrdinalHelper(ReadOnlySpan source, ReadOnlySpan target, CompareOptions options, int* matchLengthPtr) + private unsafe int IndexOfOrdinalHelper(ReadOnlySpan source, ReadOnlySpan target, CompareOptions options, int* matchLengthPtr, bool fromBeginning) { Debug.Assert(!_invariantMode); @@ -376,9 +414,8 @@ private unsafe int IndexOfOrdinalHelper(ReadOnlySpan source, ReadOnlySpan< { char* a = ap; char* b = bp; - int endIndex = source.Length - target.Length; - if (endIndex < 0) + if (target.Length > source.Length) goto InteropCall; for (int j = 0; j < target.Length; j++) @@ -388,21 +425,38 @@ private unsafe int IndexOfOrdinalHelper(ReadOnlySpan source, ReadOnlySpan< goto InteropCall; } - int i = 0; - for (; i <= endIndex; i++) + int startIndex, endIndex, jump; + if (fromBeginning) + { + // Left to right, from zero to last possible index in the source string. + // Incrementing by one after each iteration. Stop condition is last possible index plus 1. + startIndex = 0; + endIndex = source.Length - target.Length + 1; + jump = 1; + } + else + { + // Right to left, from first possible index in the source string to zero. + // Decrementing by one after each iteration. Stop condition is last possible index minus 1. + startIndex = source.Length - target.Length; + endIndex = -1; + jump = -1; + } + + for (int i = startIndex; i != endIndex; i += jump) { int targetIndex = 0; int sourceIndex = i; - for (; targetIndex < target.Length; targetIndex++) + for (; targetIndex < target.Length; targetIndex++, sourceIndex++) { char valueChar = *(a + sourceIndex); char targetChar = *(b + targetIndex); + if (valueChar >= 0x80 || s_highCharTable[valueChar]) goto InteropCall; else if (valueChar != targetChar) break; - sourceIndex++; } if (targetIndex == target.Length) @@ -412,10 +466,13 @@ private unsafe int IndexOfOrdinalHelper(ReadOnlySpan source, ReadOnlySpan< return i; } } - if (i > endIndex) - return -1; + + return -1; InteropCall: - return Interop.Globalization.IndexOf(_sortHandle, b, target.Length, a, source.Length, options, matchLengthPtr); + if (fromBeginning) + return Interop.Globalization.IndexOf(_sortHandle, b, target.Length, a, source.Length, options, matchLengthPtr); + else + return Interop.Globalization.LastIndexOf(_sortHandle, b, target.Length, a, source.Length, options); } } @@ -449,8 +506,9 @@ private unsafe int LastIndexOfCore(string source, string target, int startIndex, int leftStartIndex = (startIndex - count + 1); fixed (char* pSource = source) + fixed (char* pTarget = target) { - int lastIndex = Interop.Globalization.LastIndexOf(_sortHandle, target, target.Length, pSource + (startIndex - count + 1), count, options); + int lastIndex = Interop.Globalization.LastIndexOf(_sortHandle, pTarget, target.Length, pSource + (startIndex - count + 1), count, options); return lastIndex != -1 ? lastIndex + leftStartIndex : -1; } diff --git a/src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.Windows.cs b/src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.Windows.cs index 2a14e26c510..d1b12c664fb 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.Windows.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.Windows.cs @@ -91,14 +91,15 @@ internal static int IndexOfOrdinalCore(string source, string value, int startInd return FindStringOrdinal(FIND_FROMSTART, source, startIndex, count, value, value.Length, ignoreCase); } - internal static int IndexOfOrdinalCore(ReadOnlySpan source, ReadOnlySpan value, bool ignoreCase) + internal static int IndexOfOrdinalCore(ReadOnlySpan source, ReadOnlySpan value, bool ignoreCase, bool fromBeginning) { Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(source.Length != 0); Debug.Assert(value.Length != 0); - return FindStringOrdinal(FIND_FROMSTART, source, value, ignoreCase); + uint positionFlag = fromBeginning ? (uint)FIND_FROMSTART : FIND_FROMEND; + return FindStringOrdinal(positionFlag, source, value, ignoreCase); } internal static int LastIndexOfOrdinalCore(string source, string value, int startIndex, int count, bool ignoreCase) @@ -359,7 +360,7 @@ internal unsafe int IndexOfCore(string source, string target, int startIndex, in return -1; } - internal unsafe int IndexOfCore(ReadOnlySpan source, ReadOnlySpan target, CompareOptions options, int* matchLengthPtr) + internal unsafe int IndexOfCore(ReadOnlySpan source, ReadOnlySpan target, CompareOptions options, int* matchLengthPtr, bool fromBeginning) { Debug.Assert(!_invariantMode); @@ -367,8 +368,8 @@ internal unsafe int IndexOfCore(ReadOnlySpan source, ReadOnlySpan ta Debug.Assert(target.Length != 0); Debug.Assert((options == CompareOptions.None || options == CompareOptions.IgnoreCase)); - int retValue = FindString(FIND_FROMSTART | (uint)GetNativeCompareFlags(options), source, target, matchLengthPtr); - return retValue; + uint positionFlag = fromBeginning ? (uint)FIND_FROMSTART : FIND_FROMEND; + return FindString(positionFlag | (uint)GetNativeCompareFlags(options), source, target, matchLengthPtr); } private unsafe int LastIndexOfCore(string source, string target, int startIndex, int count, CompareOptions options) diff --git a/src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.cs b/src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.cs index 74924ee4767..92742c7b9fc 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/CompareInfo.cs @@ -939,7 +939,15 @@ internal int IndexOfOrdinal(ReadOnlySpan source, ReadOnlySpan value, Debug.Assert(!_invariantMode); Debug.Assert(!source.IsEmpty); Debug.Assert(!value.IsEmpty); - return IndexOfOrdinalCore(source, value, ignoreCase); + return IndexOfOrdinalCore(source, value, ignoreCase, fromBeginning: true); + } + + internal int LastIndexOfOrdinal(ReadOnlySpan source, ReadOnlySpan value, bool ignoreCase) + { + Debug.Assert(!_invariantMode); + Debug.Assert(!source.IsEmpty); + Debug.Assert(!value.IsEmpty); + return IndexOfOrdinalCore(source, value, ignoreCase, fromBeginning: false); } internal unsafe int IndexOf(ReadOnlySpan source, ReadOnlySpan value, CompareOptions options) @@ -947,7 +955,15 @@ internal unsafe int IndexOf(ReadOnlySpan source, ReadOnlySpan value, Debug.Assert(!_invariantMode); Debug.Assert(!source.IsEmpty); Debug.Assert(!value.IsEmpty); - return IndexOfCore(source, value, options, null); + return IndexOfCore(source, value, options, null, fromBeginning: true); + } + + internal unsafe int LastIndexOf(ReadOnlySpan source, ReadOnlySpan value, CompareOptions options) + { + Debug.Assert(!_invariantMode); + Debug.Assert(!source.IsEmpty); + Debug.Assert(!value.IsEmpty); + return IndexOfCore(source, value, options, null, fromBeginning: false); } // The following IndexOf overload is mainly used by String.Replace. This overload assumes the parameters are already validated diff --git a/src/System.Private.CoreLib/shared/System/MemoryExtensions.Fast.cs b/src/System.Private.CoreLib/shared/System/MemoryExtensions.Fast.cs index f957e6db7dc..a53ed19bd67 100644 --- a/src/System.Private.CoreLib/shared/System/MemoryExtensions.Fast.cs +++ b/src/System.Private.CoreLib/shared/System/MemoryExtensions.Fast.cs @@ -170,13 +170,51 @@ public static int IndexOf(this ReadOnlySpan span, ReadOnlySpan value case StringComparison.InvariantCultureIgnoreCase: return CompareInfo.Invariant.IndexOf(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType)); - case StringComparison.Ordinal: - case StringComparison.OrdinalIgnoreCase: + default: + Debug.Assert(comparisonType == StringComparison.Ordinal || comparisonType == StringComparison.OrdinalIgnoreCase); return CompareInfo.Invariant.IndexOfOrdinal(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType) != CompareOptions.None); } + } - Debug.Fail("StringComparison outside range"); - return -1; + /// + /// Reports the zero-based index of the last occurrence of the specified in the current . + /// The source span. + /// The value to seek within the source span. + /// One of the enumeration values that determines how the and are compared. + /// + public static int LastIndexOf(this ReadOnlySpan span, ReadOnlySpan value, StringComparison comparisonType) + { + string.CheckStringComparison(comparisonType); + + if (value.Length == 0) + { + return 0; + } + + if (span.Length == 0) + { + return -1; + } + + if (GlobalizationMode.Invariant) + { + return CompareInfo.InvariantIndexOf(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType) != CompareOptions.None, fromBeginning: false); + } + + switch (comparisonType) + { + case StringComparison.CurrentCulture: + case StringComparison.CurrentCultureIgnoreCase: + return CultureInfo.CurrentCulture.CompareInfo.LastIndexOf(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType)); + + case StringComparison.InvariantCulture: + case StringComparison.InvariantCultureIgnoreCase: + return CompareInfo.Invariant.LastIndexOf(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType)); + + default: + Debug.Assert(comparisonType == StringComparison.Ordinal || comparisonType == StringComparison.OrdinalIgnoreCase); + return CompareInfo.Invariant.LastIndexOfOrdinal(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType) != CompareOptions.None); + } } /// From 4a25e1aea1e8b845d50b2d9da90df850132e093c Mon Sep 17 00:00:00 2001 From: Stephen Toub Date: Wed, 4 Jul 2018 21:38:05 -0400 Subject: [PATCH 54/69] Improve DateTime{Offset}.ParseExact{Multiple} performance for RFC1123 ("r") (#18771) * Improve DateTime{Offset}.ParseExact{Multiple} performance for RFC1123 ("r") Significantly improves the performance by porting and adapting the Utf8Parser code from corefx. This optimizes for the (default) case of a DateTimeStyles.None; specifying any other style falls back to the normal parsing support, as that requires handling things such as arbitrary whitespace anywhere in the string. * Address PR feedback Signed-off-by: dotnet-bot --- .../System/Globalization/DateTimeParse.cs | 234 +++++++++++++++++- 1 file changed, 222 insertions(+), 12 deletions(-) diff --git a/src/System.Private.CoreLib/shared/System/Globalization/DateTimeParse.cs b/src/System.Private.CoreLib/shared/System/Globalization/DateTimeParse.cs index 682b9e32b41..d9c76646984 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/DateTimeParse.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/DateTimeParse.cs @@ -3789,13 +3789,7 @@ private static string ExpandPredefinedFormat(ReadOnlySpan format, ref Date break; case 'r': case 'R': // RFC 1123 Standard. (in Universal time) - parseInfo.calendar = GregorianCalendar.GetDefaultInstance(); - dtfi = DateTimeFormatInfo.InvariantInfo; - - if ((result.flags & ParseFlags.CaptureOffset) != 0) - { - result.flags |= ParseFlags.Rfc1123Pattern; - } + ConfigureFormatR(ref dtfi, ref parseInfo, ref result); break; case 's': // Sortable format (in local time) dtfi = DateTimeFormatInfo.InvariantInfo; @@ -3829,10 +3823,16 @@ private static string ExpandPredefinedFormat(ReadOnlySpan format, ref Date return (DateTimeFormat.GetRealFormat(format, dtfi)); } - - - - + private static void ConfigureFormatR(ref DateTimeFormatInfo dtfi, ref ParsingInfo parseInfo, ref DateTimeResult result) + { + parseInfo.calendar = GregorianCalendar.GetDefaultInstance(); + dtfi = DateTimeFormatInfo.InvariantInfo; + if ((result.flags & ParseFlags.CaptureOffset) != 0) + { + result.flags |= ParseFlags.Rfc1123Pattern; + } + } + // Given a specified format character, parse and update the parsing result. // private static bool ParseByFormat( @@ -4443,12 +4443,27 @@ internal static bool TryParseQuoteString(ReadOnlySpan format, int pos, Str if (formatParam.Length == 1) { - if (((result.flags & ParseFlags.CaptureOffset) != 0) && formatParam[0] == 'U') + char formatParamChar = formatParam[0]; + + // Fast-paths for common and important formats/configurations. + if (styles == DateTimeStyles.None) + { + switch (formatParamChar) + { + case 'R': + case 'r': + ConfigureFormatR(ref dtfi, ref parseInfo, ref result); + return ParseFormatR(s, ref parseInfo, ref result); + } + } + + if (((result.flags & ParseFlags.CaptureOffset) != 0) && formatParamChar == 'U') { // The 'U' format is not allowed for DateTimeOffset result.SetBadFormatSpecifierFailure(formatParam); return false; } + formatParam = ExpandPredefinedFormat(formatParam, ref dtfi, ref parseInfo, ref result); } @@ -4621,6 +4636,201 @@ internal static bool TryParseQuoteString(ReadOnlySpan format, int pos, Str return true; } + private static bool ParseFormatR(ReadOnlySpan source, ref ParsingInfo parseInfo, ref DateTimeResult result) + { + // Example: + // Tue, 03 Jan 2017 08:08:05 GMT + + // The format is exactly 29 characters. + if ((uint)source.Length != 29) + { + result.SetBadDateTimeFailure(); + return false; + } + + // Parse the three-letter day of week. Any casing is valid. + DayOfWeek dayOfWeek; + { + uint dow0 = source[0], dow1 = source[1], dow2 = source[2], comma = source[3]; + + if ((dow0 | dow1 | dow2 | comma) > 0x7F) + { + result.SetBadDateTimeFailure(); + return false; + } + + uint dowString = (dow0 << 24) | (dow1 << 16) | (dow2 << 8) | comma | 0x20202000; + switch (dowString) + { + case 0x73756E2c /* 'sun,' */: dayOfWeek = DayOfWeek.Sunday; break; + case 0x6d6f6e2c /* 'mon,' */: dayOfWeek = DayOfWeek.Monday; break; + case 0x7475652c /* 'tue,' */: dayOfWeek = DayOfWeek.Tuesday; break; + case 0x7765642c /* 'wed,' */: dayOfWeek = DayOfWeek.Wednesday; break; + case 0x7468752c /* 'thu,' */: dayOfWeek = DayOfWeek.Thursday; break; + case 0x6672692c /* 'fri,' */: dayOfWeek = DayOfWeek.Friday; break; + case 0x7361742c /* 'sat,' */: dayOfWeek = DayOfWeek.Saturday; break; + default: + result.SetBadDateTimeFailure(); + return false; + } + } + + if (source[4] != ' ') + { + result.SetBadDateTimeFailure(); + return false; + } + + // Parse the two digit day. + int day; + { + uint digit1 = (uint)(source[5] - '0'), digit2 = (uint)(source[6] - '0'); + + if (digit1 > 9 || digit2 > 9) + { + result.SetBadDateTimeFailure(); + return false; + } + + day = (int)(digit1*10 + digit2); + } + + if (source[7] != ' ') + { + result.SetBadDateTimeFailure(); + return false; + } + + // Parse the three letter month (followed by a space). Any casing is valid. + int month; + { + uint m0 = source[8], m1 = source[9], m2 = source[10], space = source[11]; + + if ((m0 | m1 | m2 | space) > 0x7F) + { + result.SetBadDateTimeFailure(); + return false; + } + + switch ((m0 << 24) | (m1 << 16) | (m2 << 8) | space | 0x20202000) + { + case 0x6a616e20 /* 'jan ' */ : month = 1; break; + case 0x66656220 /* 'feb ' */ : month = 2; break; + case 0x6d617220 /* 'mar ' */ : month = 3; break; + case 0x61707220 /* 'apr ' */ : month = 4; break; + case 0x6d617920 /* 'may ' */ : month = 5; break; + case 0x6a756e20 /* 'jun ' */ : month = 6; break; + case 0x6a756c20 /* 'jul ' */ : month = 7; break; + case 0x61756720 /* 'aug ' */ : month = 8; break; + case 0x73657020 /* 'sep ' */ : month = 9; break; + case 0x6f637420 /* 'oct ' */ : month = 10; break; + case 0x6e6f7620 /* 'nov ' */ : month = 11; break; + case 0x64656320 /* 'dec ' */ : month = 12; break; + default: + result.SetBadDateTimeFailure(); + return false; + } + } + + // Parse the four-digit year. + int year; + { + uint y1 = (uint)(source[12] - '0'), y2 = (uint)(source[13] - '0'), y3 = (uint)(source[14] - '0'), y4 = (uint)(source[15] - '0'); + + if (y1 > 9 || y2 > 9 || y3 > 9 || y4 > 9) + { + result.SetBadDateTimeFailure(); + return false; + } + + year = (int)(y1*1000 + y2*100 + y3*10 + y4); + } + + if (source[16] != ' ') + { + result.SetBadDateTimeFailure(); + return false; + } + + // Parse the two digit hour. + int hour; + { + uint h1 = (uint)(source[17] - '0'), h2 = (uint)(source[18] - '0'); + + if (h1 > 9 || h2 > 9) + { + result.SetBadDateTimeFailure(); + return false; + } + + hour = (int)(h1*10 + h2); + } + + if (source[19] != ':') + { + result.SetBadDateTimeFailure(); + return false; + } + + // Parse the two-digit minute. + int minute; + { + uint m1 = (uint)(source[20] - '0'); + uint m2 = (uint)(source[21] - '0'); + + if (m1 > 9 || m2 > 9) + { + result.SetBadDateTimeFailure(); + return false; + } + + minute = (int)(m1*10 + m2); + } + + if (source[22] != ':') + { + result.SetBadDateTimeFailure(); + return false; + } + + // Parse the two-digit second. + int second; + { + uint s1 = (uint)(source[23] - '0'), s2 = (uint)(source[24] - '0'); + + if (s1 > 9 || s2 > 9) + { + result.SetBadDateTimeFailure(); + return false; + } + + second = (int)(s1*10 + s2); + } + + // Parse " GMT". It must be upper case. + if (source[25] != ' ' || source[26] != 'G' || source[27] != 'M' || source[28] != 'T') + { + result.SetBadDateTimeFailure(); + return false; + } + + // Validate that the parsed date is valid according to the calendar. + if (!parseInfo.calendar.TryToDateTime(year, month, day, hour, minute, second, 0, 0, out result.parsedDate)) + { + result.SetFailure(ParseFailureKind.FormatBadDateTimeCalendar, nameof(SR.Format_BadDateTimeCalendar)); + return false; + } + + // And validate that the parsed day of week matches what the calendar said it should be. + if (dayOfWeek != result.parsedDate.DayOfWeek) + { + result.SetFailure(ParseFailureKind.FormatWithOriginalDateTime, nameof(SR.Format_BadDayOfWeek)); + return false; + } + + return true; + } + private static Exception GetDateTimeParseException(ref DateTimeResult result) { switch (result.failure) From 5c54131e87a5a9b52b16697b3459f2249d32146e Mon Sep 17 00:00:00 2001 From: Fadi Hanna Date: Thu, 5 Jul 2018 09:23:52 -0700 Subject: [PATCH 55/69] Fixing a perf issue discovered in the arm64 assembly stubs: using the BR instruction for tail calls, instead of the RET instruction. These changes should improve the overall performance on ARM64. An example of measured perf gains: 362% improvement for interface calls on cached cells. Here's the test output for 100000000 iterations: BEFORE the changes: ======================= "LowLevelPerf.exe" -name INTERFACE_INTERFACE_METHOD -iters 100000000 INTERFACE_INTERFACE_METHOD Dynamic Timer = 425064.815690 Iters/Sec Seconds = 235.258239 Seconds Process Cycles = 565810805623.000000 Cycles Process Cycles/Iter = 5658.108056 Cycles/Iters AFTER the changes: ======================= "LowLevelPerf.exe" -name INTERFACE_INTERFACE_METHOD -iters 100000000 INTERFACE_INTERFACE_METHOD Dynamic Timer = 1531103.010283 Iters/Sec Seconds = 65.312392 Seconds Process Cycles = 156754061586.000000 Cycles Process Cycles/Iter = 1567.540616 Cycles/Iters [tfs-changeset: 1706580] --- .../Runtime/arm64/CallingConventionConverterHelpers.asm | 2 +- src/Native/Runtime/arm64/ExceptionHandling.asm | 2 +- src/Native/Runtime/arm64/GcProbe.asm | 6 +++--- src/Native/Runtime/arm64/InteropThunksHelpers.asm | 2 +- src/Native/Runtime/arm64/MiscStubs.asm | 2 +- src/Native/Runtime/arm64/StubDispatch.asm | 8 ++++---- src/Native/Runtime/arm64/ThunkPoolThunks.asm | 2 +- src/Native/Runtime/arm64/UniversalTransition.asm | 2 +- 8 files changed, 13 insertions(+), 13 deletions(-) diff --git a/src/Native/Runtime/arm64/CallingConventionConverterHelpers.asm b/src/Native/Runtime/arm64/CallingConventionConverterHelpers.asm index 2d43d5bba42..f60e115780b 100644 --- a/src/Native/Runtime/arm64/CallingConventionConverterHelpers.asm +++ b/src/Native/Runtime/arm64/CallingConventionConverterHelpers.asm @@ -46,7 +46,7 @@ POINTER_SIZE equ 0x08 ldr xip0, [xip0, #POINTER_SIZE] ; get pointer to CallingConventionConverter_CommonCallingStub_PointerData into xip0 ldr x12, [xip0, #POINTER_SIZE] ; get address of UniversalTransitionThunk (which we'll tailcall to later) ldr xip0, [xip0] ; get address of ManagedCallConverterThunk (target for universal thunk to call) - ret x12 + br x12 LEAF_END __jmpstub__CallingConventionConverter_CommonCallingStub ;; diff --git a/src/Native/Runtime/arm64/ExceptionHandling.asm b/src/Native/Runtime/arm64/ExceptionHandling.asm index c71194da9e1..35843afee21 100644 --- a/src/Native/Runtime/arm64/ExceptionHandling.asm +++ b/src/Native/Runtime/arm64/ExceptionHandling.asm @@ -489,7 +489,7 @@ DonePopping NoAbort ;; reset SP and jump to continuation address mov sp, x2 - ret x0 + br x0 NESTED_END RhpCallCatchFunclet diff --git a/src/Native/Runtime/arm64/GcProbe.asm b/src/Native/Runtime/arm64/GcProbe.asm index caa400ce474..73d674a5cb3 100644 --- a/src/Native/Runtime/arm64/GcProbe.asm +++ b/src/Native/Runtime/arm64/GcProbe.asm @@ -566,7 +566,7 @@ EXTRA_SAVE_SIZE equ (32*16) EPILOG_RESTORE_REG_PAIR x27, x28, #0x60 EPILOG_NOP ldr x9, [sp, #0x78] EPILOG_RESTORE_REG_PAIR fp, lr, #(SIZEOF__PAL_LIMITED_CONTEXT + 0x20)! - EPILOG_NOP ret x9 + EPILOG_NOP br x9 NESTED_END RhpHijackForGcStressLeaf @@ -675,7 +675,7 @@ EXTRA_SAVE_SIZE equ (32*16) ldr x2, [sp, #PROBE_FRAME_SIZE] FREE_PROBE_FRAME 0x10, {true} ; This restores exception object back into x0 EPILOG_NOP mov x1, x0 ; Move the Exception object back into x1 where the catch handler expects it - EPILOG_NOP ret x2 + EPILOG_NOP br x2 MEND ;; @@ -847,7 +847,7 @@ DoneWaitingForGc EPILOG_NOP ldr x1, [sp, #8] ; hijack target address EPILOG_STACK_FREE 0x10 - EPILOG_NOP ret x1 ; jump to the hijack target + EPILOG_NOP br x1 ; jump to the hijack target Abort FREE_LOOP_HIJACK_FRAME diff --git a/src/Native/Runtime/arm64/InteropThunksHelpers.asm b/src/Native/Runtime/arm64/InteropThunksHelpers.asm index 88bb7da5d56..cc8489ef13e 100644 --- a/src/Native/Runtime/arm64/InteropThunksHelpers.asm +++ b/src/Native/Runtime/arm64/InteropThunksHelpers.asm @@ -58,7 +58,7 @@ __SECTIONREL_ThunkParamSlot ;; Now load the target address and jump to it. ldr xip0, [xip0, #POINTER_SIZE] - ret xip0 + br xip0 LEAF_END RhCommonStub diff --git a/src/Native/Runtime/arm64/MiscStubs.asm b/src/Native/Runtime/arm64/MiscStubs.asm index ba18a93c202..99c05e4a372 100644 --- a/src/Native/Runtime/arm64/MiscStubs.asm +++ b/src/Native/Runtime/arm64/MiscStubs.asm @@ -96,7 +96,7 @@ RhpCheckCctor__SlowPath EPILOG_RESTORE_REG_PAIR fp, lr, #0x20! ;; tail-call the class lib cctor check function. This function is required to return its first ;; argument, so that x0 can be preserved. - EPILOG_NOP ret x12 + EPILOG_NOP br x12 NESTED_END RhpCheckCctor__SlowPath2 diff --git a/src/Native/Runtime/arm64/StubDispatch.asm b/src/Native/Runtime/arm64/StubDispatch.asm index 82a4f861e3c..8f3b7488c1e 100644 --- a/src/Native/Runtime/arm64/StubDispatch.asm +++ b/src/Native/Runtime/arm64/StubDispatch.asm @@ -55,7 +55,7 @@ SECTIONREL_t_TLS_DispatchCell cmp x10, x11 bne %ft0 ;; Jump to label '0' ldr x9, [x9, #(OFFSETOF__InterfaceDispatchCache__m_rgEntries + ($entry * 16) + 8)] - ret x9 + br x9 0 ;; Label '0' MEND @@ -70,7 +70,7 @@ SECTIONREL_t_TLS_DispatchCell ;; Now load the target address and jump to it. ldr x9, [xip0, #8] - ret x9 + br x9 LEAF_END RhpCastableObjectDispatch_CommonStub LEAF_ENTRY RhpTailCallTLSDispatchCell @@ -79,7 +79,7 @@ SECTIONREL_t_TLS_DispatchCell ;; Tail call to the target of the dispatch cell, preserving the cell address in xip1 ldr x9, [xip1] - ret x9 + br x9 LEAF_END RhpTailCallTLSDispatchCell LEAF_ENTRY RhpCastableObjectDispatchHelper_TailCalled @@ -168,7 +168,7 @@ CurrentEntry SETA CurrentEntry + 1 ;; Load the target address of the vtable into x12 ldr x12, [x12] - ret x12 + br x12 LEAF_END RhpVTableOffsetDispatch ;; diff --git a/src/Native/Runtime/arm64/ThunkPoolThunks.asm b/src/Native/Runtime/arm64/ThunkPoolThunks.asm index ddd2636dbcd..6d9a02ff601 100644 --- a/src/Native/Runtime/arm64/ThunkPoolThunks.asm +++ b/src/Native/Runtime/arm64/ThunkPoolThunks.asm @@ -42,7 +42,7 @@ RO$name % 8 ;; fix offset to point to last QWROD in page : xip1 <- [xip0 + PAGE_SIZE - POINTER_SIZE] ;; tailcall to the location pointed at by the last qword in the data page ldr xip1, [xip0, #(PAGE_SIZE - POINTER_SIZE - ($groupIndex * THUNK_DATASIZE * 10 + THUNK_DATASIZE * $index))] - ret xip1 + br xip1 brk 0xf000 ;; Stubs need to be 16-byte aligned (see comment above). Filling padding with a ;; deterministic brk instruction, instead of having it just filled with zeros. diff --git a/src/Native/Runtime/arm64/UniversalTransition.asm b/src/Native/Runtime/arm64/UniversalTransition.asm index fe476374054..dc699ebed4b 100644 --- a/src/Native/Runtime/arm64/UniversalTransition.asm +++ b/src/Native/Runtime/arm64/UniversalTransition.asm @@ -147,7 +147,7 @@ EPILOG_RESTORE_REG_PAIR fp, lr, #STACK_SIZE! ;; Tailcall to the target address. - EPILOG_NOP ret x12 + EPILOG_NOP br x12 NESTED_END Rhp$FunctionName From 0d3dca445f77882ec499c59a8135df9ee512f142 Mon Sep 17 00:00:00 2001 From: Fadi Hanna Date: Thu, 5 Jul 2018 10:07:58 -0700 Subject: [PATCH 56/69] Fixing HFA issues on arm64 in the CallInterceptor infrastructure. The issue is that the FP blocks in the TransitionBlock or return block in the CallDescrData use 64 bit slots for floats and doubles, because the S and D registers on ARM64 overlap. However, the locals blocks used by the call interceptor logic do not have such overlapping, and use regular 32-bit floats in HFA structs. These changes replace the simple memcopy operations that the call interceptor was using to read/write HFA structs between locals blocks and native transition blocks with correct copy operations of individual float values, to properly form HFA structs in memory. [tfs-changeset: 1706584] --- .../Runtime/TypeLoader/CallInterceptor.cs | 195 ++++++++++++++++-- 1 file changed, 175 insertions(+), 20 deletions(-) diff --git a/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallInterceptor.cs b/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallInterceptor.cs index b26dd803f5e..039dab7bf86 100644 --- a/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallInterceptor.cs +++ b/src/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallInterceptor.cs @@ -95,6 +95,9 @@ public unsafe T GetVar(int index) { address = *(IntPtr*)address.ToPointer(); } +#if CCCONVERTER_TRACE + CallingConventionConverterLogger.WriteLine("READ " + (_types[index].ByRef ? "ByRef " : "") + "LocalVariableSet, _pbMemory:" + new IntPtr(_pbMemory).LowLevelToString() + "[" + index.LowLevelToString() + "]. " + _types[index].TypeInstanceFieldSize.LowLevelToString() + " bytes <- [" + address.LowLevelToString() + "]"); +#endif return Unsafe.Read((void*)address); } @@ -108,6 +111,9 @@ public unsafe void SetVar(int index, T value) { address = *(IntPtr*)address.ToPointer(); } +#if CCCONVERTER_TRACE + CallingConventionConverterLogger.WriteLine("WRITE " + (_types[index].ByRef ? "ByRef " : "") + "LocalVariableSet, _pbMemory:" + new IntPtr(_pbMemory).LowLevelToString() + "[" + index.LowLevelToString() + "]. " + _types[index].TypeInstanceFieldSize.LowLevelToString() + " bytes -> [" + address.LowLevelToString() + "]"); +#endif Unsafe.Write((void*)address, value); } @@ -510,16 +516,38 @@ private static CallConversionOperation[] ProduceOpcodesForDynamicCall(CallingCon break; default: - callConversionOps.Add(new CallConversionOperation( - CallConversionOperation.OpCode.COPY_X_BYTES_FROM_LOCALBLOCK_Y_POINTER_Z_TO_OFFSET_W_IN_TRANSITION_BLOCK, - calleeArgs.GetArgSize(), - CallConversionInterpreter.ArgBlock, - i, - ofsCallee + { +#if ARM64 + if (ofsCallee < 0 && argTypeHandle.IsHFA() && argTypeHandle.GetHFAType() == CorElementType.ELEMENT_TYPE_R4) + { + // S and D registers overlap. The FP block of the transition block has 64-bit slots that are used for both floats and doubles. + // When dealing with float HFAs, we need to copy the 32-bit floats into the 64-bit slots to match the format of the transition block's FP block. + + callConversionOps.Add(new CallConversionOperation( + CallConversionOperation.OpCode.ARM64_COPY_X_HFA_FLOATS_FROM_LOCALBLOCK_Y_POINTER_Z_TO_OFFSET_W_IN_TRANSITION_BLOCK, + (int)argTypeHandle.GetSize() / 4, + CallConversionInterpreter.ArgBlock, + i, + ofsCallee #if CCCONVERTER_TRACE - , "Arg #" + i.LowLevelToString() + , "Arg #" + i.LowLevelToString() #endif - )); + )); + break; + } +#endif + + callConversionOps.Add(new CallConversionOperation( + CallConversionOperation.OpCode.COPY_X_BYTES_FROM_LOCALBLOCK_Y_POINTER_Z_TO_OFFSET_W_IN_TRANSITION_BLOCK, + calleeArgs.GetArgSize(), + CallConversionInterpreter.ArgBlock, + i, + ofsCallee +#if CCCONVERTER_TRACE + , "Arg #" + i.LowLevelToString() +#endif + )); + } break; } } @@ -556,8 +584,20 @@ private static CallConversionOperation[] ProduceOpcodesForDynamicCall(CallingCon } else { - // Copy from return buffer into return value local - callConversionOps.Add(new CallConversionOperation(CallConversionOperation.OpCode.COPY_X_BYTES_FROM_RETBUF_TO_LOCALBLOCK_Y_POINTER_Z, checked((int)returnType.GetSize()), CallConversionInterpreter.ArgBlock, 0)); +#if ARM64 + if (returnType.IsHFA() && returnType.GetHFAType() == CorElementType.ELEMENT_TYPE_R4) + { + // S and D registers overlap. The return buffer has 64-bit slots that are used for both floats and doubles. + // When dealing with float HFAs, we need to copy 32-bit float values from the 64-bit slots of the return buffer (A simple memcopy won't work here). + + callConversionOps.Add(new CallConversionOperation(CallConversionOperation.OpCode.ARM64_COPY_X_HFA_FLOATS_FROM_RETBUF_TO_LOCALBLOCK_Y_POINTER_Z, checked((int)returnType.GetSize() / 4), CallConversionInterpreter.ArgBlock, 0)); + } + else +#endif + { + // Copy from return buffer into return value local + callConversionOps.Add(new CallConversionOperation(CallConversionOperation.OpCode.COPY_X_BYTES_FROM_RETBUF_TO_LOCALBLOCK_Y_POINTER_Z, checked((int)returnType.GetSize()), CallConversionInterpreter.ArgBlock, 0)); + } } } @@ -640,7 +680,7 @@ public string DebugString s = "RETURN_RETBUF_FROM_OFFSET_X_IN_TRANSITION_BLOCK"; break; case OpCode.RETURN_FLOATINGPOINT_BYVALUE_FROM_LOCALBLOCK_X_POINTER_Y_OF_SIZE_Z: - s = "__RETURN_FLOATINGPOINT_BYVALUE_FROM_LOCALBLOCK_X_POINTER_Y_OF_SIZE_Z__"; + s = "RETURN_FLOATINGPOINT_BYVALUE_FROM_LOCALBLOCK_X_POINTER_Y_OF_SIZE_Z"; break; case OpCode.RETURN_INTEGER_BYVALUE_FROM_LOCALBLOCK_X_POINTER_Y_OF_SIZE_Z: s = "RETURN_INTEGER_BYVALUE_FROM_LOCALBLOCK_X_POINTER_Y_OF_SIZE_Z"; @@ -663,6 +703,20 @@ public string DebugString case OpCode.COPY_GENERIC_CONTEXT_TO_OFFSET_X_IN_TRANSITION_BLOCK: s = "COPY_GENERIC_CONTEXT_TO_OFFSET_X_IN_TRANSITION_BLOCK"; break; +#if ARM64 + case OpCode.ARM64_COMPACT_X_FLOATS_INTO_HFA_AT_OFFSET_Y_IN_TRANSITION_BLOCK: + s = "ARM64_COMPACT_X_FLOATS_INTO_HFA_AT_OFFSET_Y_IN_TRANSITION_BLOCK"; + break; + case OpCode.ARM64_EXPAND_X_FLOATS_INTO_HFA_IN_RETURN_BLOCK: + s = "ARM64_EXPAND_X_FLOATS_INTO_HFA_IN_RETURN_BLOCK"; + break; + case OpCode.ARM64_COPY_X_HFA_FLOATS_FROM_LOCALBLOCK_Y_POINTER_Z_TO_OFFSET_W_IN_TRANSITION_BLOCK: + s = "ARM64_COPY_X_HFA_FLOATS_FROM_LOCALBLOCK_Y_POINTER_Z_TO_OFFSET_W_IN_TRANSITION_BLOCK"; + break; + case OpCode.ARM64_COPY_X_HFA_FLOATS_FROM_RETBUF_TO_LOCALBLOCK_Y_POINTER_Z: + s = "ARM64_COPY_X_HFA_FLOATS_FROM_RETBUF_TO_LOCALBLOCK_Y_POINTER_Z"; + break; +#endif default: s = ""; break; @@ -690,7 +744,7 @@ public string DebugString } #else - public CallConversionOperation(OpCode op, int X, int Y, int Z, int W) + public CallConversionOperation(OpCode op, int X, int Y, int Z, int W) { this.Op = op; this.X = X; @@ -755,7 +809,13 @@ public enum OpCode CALL_DESCR_MANAGED_WITH_RETBUF_AS_LOCALBLOCK_X_POINTER_Y_STACKSLOTS_Z_FPCALLINFO_W, CALL_DESCR_NATIVE_WITH_RETBUF_AS_LOCALBLOCK_X_POINTER_Y_STACKSLOTS_Z_FPCALLINFO_W, COPY_X_BYTES_FROM_RETBUF_TO_LOCALBLOCK_Y_POINTER_Z, - COPY_GENERIC_CONTEXT_TO_OFFSET_X_IN_TRANSITION_BLOCK + COPY_GENERIC_CONTEXT_TO_OFFSET_X_IN_TRANSITION_BLOCK, +#if ARM64 + ARM64_COMPACT_X_FLOATS_INTO_HFA_AT_OFFSET_Y_IN_TRANSITION_BLOCK, + ARM64_EXPAND_X_FLOATS_INTO_HFA_IN_RETURN_BLOCK, + ARM64_COPY_X_HFA_FLOATS_FROM_LOCALBLOCK_Y_POINTER_Z_TO_OFFSET_W_IN_TRANSITION_BLOCK, + ARM64_COPY_X_HFA_FLOATS_FROM_RETBUF_TO_LOCALBLOCK_Y_POINTER_Z +#endif } public OpCode Op; @@ -875,6 +935,73 @@ public static unsafe void Interpret(ref CallConversionInterpreterLocals locals) } break; +#if ARM64 + case CallConversionOperation.OpCode.ARM64_COMPACT_X_FLOATS_INTO_HFA_AT_OFFSET_Y_IN_TRANSITION_BLOCK: + { + Debug.Assert(op.X > 0 && op.X <= 4); + + float* pFPRegs = (float*)(locals.TransitionBlockPtr + op.Y); + for (int i = 1; i < op.X; i++) + pFPRegs[i] = pFPRegs[i * 2]; + +#if CCCONVERTER_TRACE + CallingConventionConverterLogger.WriteLine(" -> Compact " + op.X.LowLevelToString() + " ARM64 HFA floats at [" + new IntPtr(pFPRegs).LowLevelToString() + "]"); +#endif + } + break; + + case CallConversionOperation.OpCode.ARM64_EXPAND_X_FLOATS_INTO_HFA_IN_RETURN_BLOCK: + { + Debug.Assert(op.X > 0 && op.X <= 4); + + byte* pReturnBlock = locals.TransitionBlockPtr + TransitionBlock.GetOffsetOfFloatArgumentRegisters(); + for (int i = op.X - 1; i >= 0; i--) + { + float value = ((float*)pReturnBlock)[i]; + *((IntPtr*)pReturnBlock + i) = IntPtr.Zero; // Clear destination slot to zeros before copying the float value + *((float*)((IntPtr*)pReturnBlock + i)) = value; + } + +#if CCCONVERTER_TRACE + CallingConventionConverterLogger.WriteLine(" -> Expand " + op.X.LowLevelToString() + " ARM64 HFA floats at [" + new IntPtr(pReturnBlock).LowLevelToString() + "]"); +#endif + } + break; + + case CallConversionOperation.OpCode.ARM64_COPY_X_HFA_FLOATS_FROM_LOCALBLOCK_Y_POINTER_Z_TO_OFFSET_W_IN_TRANSITION_BLOCK: + { + Debug.Assert(op.X > 0 && op.X <= 4); + + float* pSrc = (float*)(locals.GetLocalBlock(op.Y).GetRawMemoryPointer()[op.Z]); + float* pDst = (float*)(locals.TransitionBlockPtr + op.W); + for (int i = 0; i < op.X; i++) + { + ((IntPtr*)pDst)[i] = IntPtr.Zero; // Clear destination slot to zeros before copying the float value + pDst[i * 2] = pSrc[i]; + } + +#if CCCONVERTER_TRACE + CallingConventionConverterLogger.WriteLine(" -> Copy " + op.X.LowLevelToString() + " ARM64 HFA floats from [" + new IntPtr(pSrc).LowLevelToString() + "] to [" + new IntPtr(pDst).LowLevelToString() + "]"); +#endif + } + break; + + case CallConversionOperation.OpCode.ARM64_COPY_X_HFA_FLOATS_FROM_RETBUF_TO_LOCALBLOCK_Y_POINTER_Z: + { + Debug.Assert(op.X > 0 && op.X <= 4); + + float* pSrc = (float*)locals.IntPtrReturnVal.ToPointer(); + float* pDst = (float*)(locals.GetLocalBlock(op.Y).GetRawMemoryPointer()[op.Z].ToPointer()); + for (int i = 0; i < op.X; i++) + pDst[i] = pSrc[i * 2]; + +#if CCCONVERTER_TRACE + CallingConventionConverterLogger.WriteLine(" -> Copy " + op.X.LowLevelToString() + " ARM64 HFA floats from [" + new IntPtr(pSrc).LowLevelToString() + "] to [" + new IntPtr(pDst).LowLevelToString() + "]"); +#endif + } + break; +#endif + case CallConversionOperation.OpCode.COPY_X_BYTES_FROM_LOCALBLOCK_Y_OFFSET_Z_IN_LOCALBLOCK_TO_OFFSET_W_IN_TRANSITION_BLOCK: { void* pSrc = ((byte*)locals.GetLocalBlock(op.Y).GetRawMemoryPointer()) + op.Z; @@ -1064,15 +1191,15 @@ public static unsafe void Interpret(ref CallConversionInterpreterLocals locals) case CallConversionOperation.OpCode.RETURN_FLOATINGPOINT_BYVALUE_FROM_LOCALBLOCK_X_POINTER_Y_OF_SIZE_Z: { #if CALLDESCR_FPARGREGSARERETURNREGS - byte* returnBlock = locals.TransitionBlockPtr + TransitionBlock.GetOffsetOfFloatArgumentRegisters(); - MemoryHelpers.Memset((IntPtr)returnBlock, IntPtr.Size, 0); - Buffer.MemoryCopy(locals.GetLocalBlock(op.X).GetRawMemoryPointer()[op.Y].ToPointer(), returnBlock, op.Z, op.Z); + byte* pReturnBlock = locals.TransitionBlockPtr + TransitionBlock.GetOffsetOfFloatArgumentRegisters(); + MemoryHelpers.Memset((IntPtr)pReturnBlock, IntPtr.Size, 0); + Buffer.MemoryCopy(locals.GetLocalBlock(op.X).GetRawMemoryPointer()[op.Y].ToPointer(), pReturnBlock, op.Z, op.Z); locals.IntPtrReturnVal = CallConverterThunk.ReturnVoidReturnThunk; #elif X86 CallConverterThunk.SetupCallerActualReturnData(locals.TransitionBlockPtr); - fixed (ReturnBlock* retBlk = &CallConverterThunk.t_NonArgRegisterReturnSpace) + fixed (ReturnBlock* pReturnBlock = &CallConverterThunk.t_NonArgRegisterReturnSpace) { - Buffer.MemoryCopy(locals.GetLocalBlock(op.X).GetRawMemoryPointer()[op.Y].ToPointer(), retBlk, op.Z, op.Z); + Buffer.MemoryCopy(locals.GetLocalBlock(op.X).GetRawMemoryPointer()[op.Y].ToPointer(), pReturnBlock, op.Z, op.Z); } if (op.Z == 4) { @@ -1446,8 +1573,10 @@ private CallConversionOperation[] BuildOpsListForThunk(CallingConvention calling { int ofsCaller = callerArgs.GetNextOffset(); - TypeHandle dummyTypeHandle; - if (callerArgs.IsArgPassedByRef() && callerArgs.GetArgType(out dummyTypeHandle) != CorElementType.ELEMENT_TYPE_BYREF) + TypeHandle argTypeHandle; + CorElementType argType = callerArgs.GetArgType(out argTypeHandle); + + if (callerArgs.IsArgPassedByRef() && argType != CorElementType.ELEMENT_TYPE_BYREF) { callConversionOps.Add(new CallConversionOperation( CallConversionOperation.OpCode.COPY_X_BYTES_TO_LOCALBLOCK_Y_OFFSET_Z_IN_LOCALBLOCK_FROM_OFFSET_W_IN_TRANSITION_BLOCK, @@ -1462,6 +1591,24 @@ private CallConversionOperation[] BuildOpsListForThunk(CallingConvention calling } else { +#if ARM64 + if (ofsCaller < 0 && argTypeHandle.IsHFA() && argTypeHandle.GetHFAType() == CorElementType.ELEMENT_TYPE_R4) + { + // S and D registers overlap. The FP block of the transition block will have the float values of the HFA struct stored in 64-bit slots. We cannot directly + // memcopy or point at these values without first re-writing them as consecutive 32-bit float values + + callConversionOps.Add(new CallConversionOperation( + CallConversionOperation.OpCode.ARM64_COMPACT_X_FLOATS_INTO_HFA_AT_OFFSET_Y_IN_TRANSITION_BLOCK, + (int)argTypeHandle.GetSize() / 4, + ofsCaller, + 0 +#if CCCONVERTER_TRACE + , "Arg #" + i.LowLevelToString() +#endif + )); + } +#endif + callConversionOps.Add(new CallConversionOperation( CallConversionOperation.OpCode.SET_LOCALBLOCK_X_POINTER_Y_TO_OFFSET_Z_IN_TRANSITION_BLOCK, CallConversionInterpreter.ArgBlock, @@ -1492,6 +1639,14 @@ private CallConversionOperation[] BuildOpsListForThunk(CallingConvention calling else if (callerArgs.GetFPReturnSize() > 0) { callConversionOps.Add(new CallConversionOperation(CallConversionOperation.OpCode.RETURN_FLOATINGPOINT_BYVALUE_FROM_LOCALBLOCK_X_POINTER_Y_OF_SIZE_Z, CallConversionInterpreter.ArgBlock, 0, checked((int)callerArgs.GetFPReturnSize()))); + +#if ARM64 + if (returnType.IsHFA() && returnType.GetHFAType() == CorElementType.ELEMENT_TYPE_R4) + { + // S and D registers overlap, so we need to re-write the float values into 64-bit slots to match the format of the UniversalTransitionBlock's FP return block + callConversionOps.Add(new CallConversionOperation(CallConversionOperation.OpCode.ARM64_EXPAND_X_FLOATS_INTO_HFA_IN_RETURN_BLOCK, (int)returnType.GetSize() / 4, 0, 0)); + } +#endif } else { From a442332458fd7d255af4f26d83e95919ff22d8a4 Mon Sep 17 00:00:00 2001 From: Stephen Toub Date: Fri, 6 Jul 2018 12:12:54 -0400 Subject: [PATCH 57/69] Improve DateTime{Offset}.ParseExact performance for "O"/"o" roundtrip format (#18800) Ports the code used by Utf8Parser, modified to support things Utf8Parser doesn't but DateTime{Offset{.ParseExact do, such as single-digit offset hours. Signed-off-by: dotnet-bot --- .../System/Globalization/DateTimeParse.cs | 242 +++++++++++++++++- 1 file changed, 229 insertions(+), 13 deletions(-) diff --git a/src/System.Private.CoreLib/shared/System/Globalization/DateTimeParse.cs b/src/System.Private.CoreLib/shared/System/Globalization/DateTimeParse.cs index d9c76646984..b9da9007898 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/DateTimeParse.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/DateTimeParse.cs @@ -2719,7 +2719,7 @@ internal static bool TryParse(ReadOnlySpan s, DateTimeFormatInfo dtfi, Dat result.parsedDate = time; - if (!DetermineTimeZoneAdjustments(ref str, ref result, styles, bTimeOnly)) + if (!DetermineTimeZoneAdjustments(ref result, styles, bTimeOnly)) { TPTraceExit("0120 (DetermineTimeZoneAdjustments)", dps); return false; @@ -2730,13 +2730,13 @@ internal static bool TryParse(ReadOnlySpan s, DateTimeFormatInfo dtfi, Dat // Handles time zone adjustments and sets DateTimeKind values as required by the styles - private static bool DetermineTimeZoneAdjustments(ref __DTString str, ref DateTimeResult result, DateTimeStyles styles, bool bTimeOnly) + private static bool DetermineTimeZoneAdjustments(ref DateTimeResult result, DateTimeStyles styles, bool 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 str, ref result, styles); + return DateTimeOffsetTimeZonePostProcessing(ref result, styles); } else { @@ -2808,7 +2808,7 @@ private static bool DetermineTimeZoneAdjustments(ref __DTString str, ref DateTim } // Apply validation and adjustments specific to DateTimeOffset - private static bool DateTimeOffsetTimeZonePostProcessing(ref __DTString str, ref DateTimeResult result, DateTimeStyles styles) + private static bool 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. @@ -3061,7 +3061,7 @@ private static bool ParseISO8601(ref DateTimeRawInfo raw, ref __DTString str, Da time = time.AddTicks((long)Math.Round(partSecond * Calendar.TicksPerSecond)); result.parsedDate = time; - if (!DetermineTimeZoneAdjustments(ref str, ref result, styles, false)) + if (!DetermineTimeZoneAdjustments(ref result, styles, false)) { return false; } @@ -3782,19 +3782,15 @@ private static string ExpandPredefinedFormat(ReadOnlySpan format, ref Date // switch (format[0]) { + case 's': // Sortable format (in local time) case 'o': case 'O': // Round Trip Format - parseInfo.calendar = GregorianCalendar.GetDefaultInstance(); - dtfi = DateTimeFormatInfo.InvariantInfo; + ConfigureFormatOS(ref dtfi, ref parseInfo); break; case 'r': case 'R': // RFC 1123 Standard. (in Universal time) ConfigureFormatR(ref dtfi, ref parseInfo, ref result); break; - case 's': // Sortable format (in local time) - dtfi = DateTimeFormatInfo.InvariantInfo; - parseInfo.calendar = GregorianCalendar.GetDefaultInstance(); - break; case 'u': // Universal time format in sortable format. parseInfo.calendar = GregorianCalendar.GetDefaultInstance(); dtfi = DateTimeFormatInfo.InvariantInfo; @@ -3832,7 +3828,13 @@ private static void ConfigureFormatR(ref DateTimeFormatInfo dtfi, ref ParsingInf result.flags |= ParseFlags.Rfc1123Pattern; } } - + + private static void ConfigureFormatOS(ref DateTimeFormatInfo dtfi, ref ParsingInfo parseInfo) + { + parseInfo.calendar = GregorianCalendar.GetDefaultInstance(); + dtfi = DateTimeFormatInfo.InvariantInfo; + } + // Given a specified format character, parse and update the parsing result. // private static bool ParseByFormat( @@ -4454,6 +4456,11 @@ internal static bool TryParseQuoteString(ReadOnlySpan format, int pos, Str case 'r': ConfigureFormatR(ref dtfi, ref parseInfo, ref result); return ParseFormatR(s, ref parseInfo, ref result); + + case 'O': + case 'o': + ConfigureFormatOS(ref dtfi, ref parseInfo); + return ParseFormatO(s, ref parseInfo, ref result); } } @@ -4629,7 +4636,7 @@ internal static bool TryParseQuoteString(ReadOnlySpan format, int pos, Str } - if (!DetermineTimeZoneAdjustments(ref str, ref result, styles, bTimeOnly)) + if (!DetermineTimeZoneAdjustments(ref result, styles, bTimeOnly)) { return false; } @@ -4831,6 +4838,215 @@ private static bool ParseFormatR(ReadOnlySpan source, ref ParsingInfo pars return true; } + private static bool ParseFormatO(ReadOnlySpan source, ref ParsingInfo parseInfo, ref DateTimeResult result) + { + // Examples: + // 2017-06-12T05:30:45.7680000 (interpreted as local time wrt to current time zone) + // 2017-06-12T05:30:45.7680000Z (Z is short for "+00:00" but also distinguishes DateTimeKind.Utc from DateTimeKind.Local) + // 2017-06-12T05:30:45.7680000-7:00 (special-case of one-digit offset hour) + // 2017-06-12T05:30:45.7680000-07:00 + + if ((uint)source.Length < 27 || + source[4] != '-' || + source[7] != '-' || + source[10] != 'T' || + source[13] != ':' || + source[16] != ':' || + source[19] != '.') + { + result.SetBadDateTimeFailure(); + return false; + } + + int year; + { + uint y1 = (uint)(source[0] - '0'), y2 = (uint)(source[1] - '0'), y3 = (uint)(source[2] - '0'), y4 = (uint)(source[3] - '0'); + + if (y1 > 9 || y2 > 9 || y3 > 9 || y4 > 9) + { + result.SetBadDateTimeFailure(); + return false; + } + + year = (int)(y1*1000 + y2*100 + y3*10 + y4); + } + + int month; + { + uint m1 = (uint)(source[5] - '0'), m2 = (uint)(source[6] - '0'); + + if (m1 > 9 || m2 > 9) + { + result.SetBadDateTimeFailure(); + return false; + } + + month = (int)(m1*10 + m2); + } + + int day; + { + uint d1 = (uint)(source[8] - '0'), d2 = (uint)(source[9] - '0'); + + if (d1 > 9 || d2 > 9) + { + result.SetBadDateTimeFailure(); + return false; + } + + day = (int)(d1*10 + d2); + } + + int hour; + { + uint h1 = (uint)(source[11] - '0'), h2 = (uint)(source[12] - '0'); + + if (h1 > 9 || h2 > 9) + { + result.SetBadDateTimeFailure(); + return false; + } + + hour = (int)(h1*10 + h2); + } + + int minute; + { + uint m1 = (uint)(source[14] - '0'), m2 = (uint)(source[15] - '0'); + + if (m1 > 9 || m2 > 9) + { + result.SetBadDateTimeFailure(); + return false; + } + + minute = (int)(m1*10 + m2); + } + + int second; + { + uint s1 = (uint)(source[17] - '0'), s2 = (uint)(source[18] - '0'); + + if (s1 > 9 || s2 > 9) + { + result.SetBadDateTimeFailure(); + return false; + } + + second = (int)(s1*10 + s2); + } + + double fraction; + { + uint f1 = (uint)(source[20] - '0'); + uint f2 = (uint)(source[21] - '0'); + uint f3 = (uint)(source[22] - '0'); + uint f4 = (uint)(source[23] - '0'); + uint f5 = (uint)(source[24] - '0'); + uint f6 = (uint)(source[25] - '0'); + uint f7 = (uint)(source[26] - '0'); + + if (f1 > 9 || f2 > 9 || f3 > 9 || f4 > 9 || f5 > 9 || f6 > 9 || f7 > 9) + { + result.SetBadDateTimeFailure(); + return false; + } + + fraction = (f1*1000000 + f2*100000 + f3*10000 + f4*1000 + f5*100 + f6*10 + f7) / 10000000.0; + } + + if (!DateTime.TryCreate(year, month, day, hour, minute, second, 0, out DateTime dateTime)) + { + result.SetBadDateTimeFailure(); + return false; + } + result.parsedDate = dateTime.AddTicks((long)Math.Round(fraction * Calendar.TicksPerSecond)); + + if ((uint)source.Length > 27) + { + char offsetChar = source[27]; + switch (offsetChar) + { + case 'Z': + if (source.Length != 28) + { + result.SetBadDateTimeFailure(); + return false; + } + result.flags |= ParseFlags.TimeZoneUsed | ParseFlags.TimeZoneUtc; + break; + + case '+': + case '-': + int offsetHours, colonIndex; + + if ((uint)source.Length == 33) + { + uint oh1 = (uint)(source[28] - '0'), oh2 = (uint)(source[29] - '0'); + + if (oh1 > 9 || oh2 > 9) + { + result.SetBadDateTimeFailure(); + return false; + } + + offsetHours = (int)(oh1 * 10 + oh2); + colonIndex = 30; + } + else if ((uint)source.Length == 32) // special-case allowed for compat: only one offset hour digit + { + offsetHours = source[28] - '0'; + + if ((uint)offsetHours > 9) + { + result.SetBadDateTimeFailure(); + return false; + } + + colonIndex = 29; + } + else + { + result.SetBadDateTimeFailure(); + return false; + } + + if (source[colonIndex] != ':') + { + result.SetBadDateTimeFailure(); + return false; + } + + int offsetMinutes; + { + uint om1 = (uint)(source[colonIndex + 1] - '0'), om2 = (uint)(source[colonIndex + 2] - '0'); + + if (om1 > 9 || om2 > 9) + { + result.SetBadDateTimeFailure(); + return false; + } + + offsetMinutes = (int)(om1*10 + om2); + } + + result.flags |= ParseFlags.TimeZoneUsed; + result.timeZoneOffset = new TimeSpan(offsetHours, offsetMinutes, 0); + if (offsetChar == '-') + { + result.timeZoneOffset = result.timeZoneOffset.Negate(); + } + break; + + default: + result.SetBadDateTimeFailure(); + return false; + } + } + + return DetermineTimeZoneAdjustments(ref result, DateTimeStyles.None, bTimeOnly: false); + } + private static Exception GetDateTimeParseException(ref DateTimeResult result) { switch (result.failure) From f11556c5de040d3aa2c96a9d1ecbae6efe8feeba Mon Sep 17 00:00:00 2001 From: Viktor Hofer Date: Sun, 8 Jul 2018 15:41:26 +0200 Subject: [PATCH 58/69] Fix Span LastIndexOf empty value handling Signed-off-by: dotnet-bot --- .../shared/System/MemoryExtensions.Fast.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/System.Private.CoreLib/shared/System/MemoryExtensions.Fast.cs b/src/System.Private.CoreLib/shared/System/MemoryExtensions.Fast.cs index a53ed19bd67..58d0b5c10fb 100644 --- a/src/System.Private.CoreLib/shared/System/MemoryExtensions.Fast.cs +++ b/src/System.Private.CoreLib/shared/System/MemoryExtensions.Fast.cs @@ -188,7 +188,7 @@ public static int LastIndexOf(this ReadOnlySpan span, ReadOnlySpan v if (value.Length == 0) { - return 0; + return span.Length - 1; } if (span.Length == 0) From 19125deeeca35d2a1a37a50a5ddc2f83778c94df Mon Sep 17 00:00:00 2001 From: Viktor Hofer Date: Sun, 8 Jul 2018 19:41:40 +0200 Subject: [PATCH 59/69] LastIndexOf corner case fix when span is empty (dotnet/coreclr#18826) Signed-off-by: dotnet-bot --- .../shared/System/MemoryExtensions.Fast.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/System.Private.CoreLib/shared/System/MemoryExtensions.Fast.cs b/src/System.Private.CoreLib/shared/System/MemoryExtensions.Fast.cs index 58d0b5c10fb..4e84223b204 100644 --- a/src/System.Private.CoreLib/shared/System/MemoryExtensions.Fast.cs +++ b/src/System.Private.CoreLib/shared/System/MemoryExtensions.Fast.cs @@ -188,7 +188,7 @@ public static int LastIndexOf(this ReadOnlySpan span, ReadOnlySpan v if (value.Length == 0) { - return span.Length - 1; + return span.Length > 0 ? span.Length - 1 : 0; } if (span.Length == 0) From 482e922f14b265de2ecb4744848b09eb02d8f4eb Mon Sep 17 00:00:00 2001 From: Michal Strehovsky Date: Mon, 9 Jul 2018 07:11:45 -0700 Subject: [PATCH 60/69] Delete orphaned resource strings in S.P.Threading and S.P.Reflection [tfs-changeset: 1706795] --- .../src/Resources/Strings.resx | 18 ------- .../src/Resources/Strings.resx | 24 ---------- .../src/Resources/Strings.resx | 47 +------------------ 3 files changed, 1 insertion(+), 88 deletions(-) diff --git a/src/System.Private.Reflection.Core/src/Resources/Strings.resx b/src/System.Private.Reflection.Core/src/Resources/Strings.resx index 4d761569991..6488cc43469 100644 --- a/src/System.Private.Reflection.Core/src/Resources/Strings.resx +++ b/src/System.Private.Reflection.Core/src/Resources/Strings.resx @@ -150,9 +150,6 @@ The type '{0}' cannot be found in assembly '{1}'. - - An invalid escape sequence was found inside a type name. - Cannot load assembly '{0}'. No metadata found for this assembly. @@ -228,9 +225,6 @@ Property set method not found. - - Type instance is not IReflectable. - Array may not be empty. @@ -246,12 +240,6 @@ There is no metadata token available for the given member. - - Module version IDs (MVIDs) cannot be retrieved on this platform. - - - Could not resolve assembly '{0}'. - Field not found. @@ -286,18 +274,12 @@ Named parameter array cannot be bigger than argument array. - - Must specify property Set or Get or method call for a COM Object. - Cannot specify both Get and Set on a property. Cannot specify Set on a property and Invoke on a method. - - Only one of the following binding flags can be set: BindingFlags.SetProperty, BindingFlags.PutDispProperty, BindingFlags.PutRefDispProperty. - Named parameter value must not be null. diff --git a/src/System.Private.Reflection.Execution/src/Resources/Strings.resx b/src/System.Private.Reflection.Execution/src/Resources/Strings.resx index f03a830ef23..0a8ef5f1ba9 100644 --- a/src/System.Private.Reflection.Execution/src/Resources/Strings.resx +++ b/src/System.Private.Reflection.Execution/src/Resources/Strings.resx @@ -141,30 +141,9 @@ Nullable object must have a value. - - Late-bound invocation is not supported for compiler-intrinsic methods. - - - Methods using the vararg calling convention are not supported on this platform. - - - Passing or returning pointers through Invoke is not supported on this platform. - Non-static field requires a target. - - Prerelease Restriction: The following type member cannot be referenced from inside a Linq Expression:\n\n - - - \n\nThe following may be used as a workaround:\n\n - - - 1. Make the member public or mark the member with the System.Reflection.Metadata.Controls.ReflectionInfo attribute specifying the argument ReflectionInfoOption.Include\n - - - 2. Enable Reflection for its declaring type with the System.Reflection.Consumption.EnableDynamicProgramming attribute.\n\n\n - Constructor on type '{0}' not found. @@ -192,9 +171,6 @@ '{0}', on '{1}' violates the constraint of type '{2}'. - - Obtaining a MethodInfo of a reflection-constructed delegate to a virtual method is not supported on this platform. - At least one object must implement IComparable. diff --git a/src/System.Private.Threading/src/Resources/Strings.resx b/src/System.Private.Threading/src/Resources/Strings.resx index f160191c09d..ff802f945c0 100644 --- a/src/System.Private.Threading/src/Resources/Strings.resx +++ b/src/System.Private.Threading/src/Resources/Strings.resx @@ -117,52 +117,7 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - The event is already signaled and cannot be incremented. - - - The increment operation would cause the CurrentCount to overflow. - - - Invalid attempt made to decrement the event's count below zero. - - - The operation was canceled. - - - The barrier has been disposed. - - - The barrier has no registered participants. - - - The specified timeout must represent a value between -1 and Int32.MaxValue, inclusive. - - - The participantCount argument is greater than the number of participants that haven't yet arrived at the barrier in this phase. - - - The participantCount argument must be less than or equal the number of participants. - - - The participantCount argument must be a positive value. - - - This method may not be called from within the postPhaseAction. - - - The participantCount argument must be a positive value. - - - The number of threads using the barrier exceeded the total number of registered participants. - The postPhaseAction failed with an exception. - - The participantCount argument must be non-negative and less than or equal to 32767. - - - Adding participantCount participants would result in the number of participants exceeding the maximum number allowed. - - \ No newline at end of file + From 898dc439c0ac8851085d4eb5648450b6d5cf6c8a Mon Sep 17 00:00:00 2001 From: Jan Kotas Date: Mon, 9 Jul 2018 12:30:34 -0700 Subject: [PATCH 61/69] Disable PInvoke inlining (#6064) PInvoke inlining makes us drop delegate required marshaling data. Proper fix is tracked by https://github.com/dotnet/corert/issues/6063. Fixes #6060 --- src/JitInterface/src/CorInfoImpl.cs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/JitInterface/src/CorInfoImpl.cs b/src/JitInterface/src/CorInfoImpl.cs index 1a0c2bbb785..13d2ccac485 100644 --- a/src/JitInterface/src/CorInfoImpl.cs +++ b/src/JitInterface/src/CorInfoImpl.cs @@ -760,8 +760,14 @@ private uint getMethodAttribsInternal(MethodDesc method) result |= CorInfoFlag.CORINFO_FLG_SHAREDINST; if (method.IsPInvoke) + { result |= CorInfoFlag.CORINFO_FLG_PINVOKE; + // TODO: Enable PInvoke inlining + // https://github.com/dotnet/corert/issues/6063 + result |= CorInfoFlag.CORINFO_FLG_DONT_INLINE; + } + // TODO: Cache inlining hits // Check for an inlining directive. From c4314f34df3f3169976d89d599d928aac71a8904 Mon Sep 17 00:00:00 2001 From: Anirudh Agnihotry Date: Mon, 9 Jul 2018 02:21:55 -0700 Subject: [PATCH 62/69] Moved ManualResetEventSlim to shared (dotnet/coreclr#18799) * Moved ManualResetEventSlim to shared * covert System.int to System.Int32 Signed-off-by: dotnet-bot --- .../System.Private.CoreLib.Shared.projitems | 1 + .../System/Threading/ManualResetEventSlim.cs | 759 ++++++++++++++++++ .../shared/System/Threading/SpinWait.cs | 2 +- 3 files changed, 761 insertions(+), 1 deletion(-) create mode 100644 src/System.Private.CoreLib/shared/System/Threading/ManualResetEventSlim.cs diff --git a/src/System.Private.CoreLib/shared/System.Private.CoreLib.Shared.projitems b/src/System.Private.CoreLib/shared/System.Private.CoreLib.Shared.projitems index 19c48e87df5..8b66d375999 100644 --- a/src/System.Private.CoreLib/shared/System.Private.CoreLib.Shared.projitems +++ b/src/System.Private.CoreLib/shared/System.Private.CoreLib.Shared.projitems @@ -591,6 +591,7 @@ + diff --git a/src/System.Private.CoreLib/shared/System/Threading/ManualResetEventSlim.cs b/src/System.Private.CoreLib/shared/System/Threading/ManualResetEventSlim.cs new file mode 100644 index 00000000000..fa42a81933e --- /dev/null +++ b/src/System.Private.CoreLib/shared/System/Threading/ManualResetEventSlim.cs @@ -0,0 +1,759 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Diagnostics; + +namespace System.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 + // a brief amount of spinning that should, on the average, make using the slim event + // cheaper than using Win32 events directly. This can be reset manually, much like + // a Win32 manual-reset would be. + // + // Notes: + // We lazily allocate the Win32 event internally. Therefore, the caller should + // always call Dispose to clean it up, just in case. This API is a no-op of the + // event wasn't allocated, but if it was, ensures that the event goes away + // eagerly, instead of waiting for finalization. + + /// + /// Provides a slimmed down version of . + /// + /// + /// All public and protected members of are thread-safe and may be used + /// concurrently from multiple threads, with the exception of Dispose, which + /// must only be used when all other operations on the have + /// completed, and Reset, which should only be used when no other threads are + /// accessing the event. + /// + [DebuggerDisplay("Set = {IsSet}")] + public class ManualResetEventSlim : IDisposable + { + // These are the default spin counts we use on single-proc and MP machines. + private const int DEFAULT_SPIN_SP = 1; + + private volatile object m_lock; + // A lock used for waiting and pulsing. Lazily initialized via EnsureLockObjectCreated() + + private volatile ManualResetEvent m_eventObj; // A true Win32 event used for waiting. + + // -- State -- // + //For a packed word a uint would seem better, but Interlocked.* doesn't support them as uint isn't CLS-compliant. + private volatile int m_combinedState; //ie a uint. Used for the state items listed below. + + //1-bit for signalled state + private const int SignalledState_BitMask = unchecked((int)0x80000000);//1000 0000 0000 0000 0000 0000 0000 0000 + private const int SignalledState_ShiftCount = 31; + + //1-bit for disposed state + private const int Dispose_BitMask = unchecked((int)0x40000000);//0100 0000 0000 0000 0000 0000 0000 0000 + + //11-bits for m_spinCount + private const int SpinCountState_BitMask = unchecked((int)0x3FF80000); //0011 1111 1111 1000 0000 0000 0000 0000 + private const int SpinCountState_ShiftCount = 19; + private const int SpinCountState_MaxValue = (1 << 11) - 1; //2047 + + //19-bits for m_waiters. This allows support of 512K threads waiting which should be ample + private const int NumWaitersState_BitMask = unchecked((int)0x0007FFFF); // 0000 0000 0000 0111 1111 1111 1111 1111 + private const int NumWaitersState_ShiftCount = 0; + private const int NumWaitersState_MaxValue = (1 << 19) - 1; //512K-1 + // ----------- // + +#if DEBUG + private static int s_nextId; // The next id that will be given out. + private int m_id = Interlocked.Increment(ref s_nextId); // A unique id for debugging purposes only. + private long m_lastSetTime; + private long m_lastResetTime; +#endif + + /// + /// Gets the underlying object for this . + /// + /// The underlying event object fore this . + /// + /// Accessing this property forces initialization of an underlying event object if one hasn't + /// already been created. To simply wait on this , + /// the public Wait methods should be preferred. + /// + public WaitHandle WaitHandle + { + get + { + ThrowIfDisposed(); + if (m_eventObj == null) + { + // Lazily initialize the event object if needed. + LazyInitializeEvent(); + } + + return m_eventObj; + } + } + + /// + /// Gets whether the event is set. + /// + /// true if the event has is set; otherwise, false. + public bool IsSet + { + get + { + return 0 != ExtractStatePortion(m_combinedState, SignalledState_BitMask); + } + + private set + { + UpdateStateAtomically(((value) ? 1 : 0) << SignalledState_ShiftCount, SignalledState_BitMask); + } + } + + /// + /// Gets the number of spin waits that will be occur before falling back to a true wait. + /// + public int SpinCount + { + get + { + return ExtractStatePortionAndShiftRight(m_combinedState, SpinCountState_BitMask, SpinCountState_ShiftCount); + } + + private set + { + Debug.Assert(value >= 0, "SpinCount is a restricted-width integer. The value supplied is outside the legal range."); + Debug.Assert(value <= SpinCountState_MaxValue, "SpinCount is a restricted-width integer. The value supplied is outside the legal range."); + // Don't worry about thread safety because it's set one time from the constructor + m_combinedState = (m_combinedState & ~SpinCountState_BitMask) | (value << SpinCountState_ShiftCount); + } + } + + /// + /// How many threads are waiting. + /// + private int Waiters + { + get + { + return ExtractStatePortionAndShiftRight(m_combinedState, NumWaitersState_BitMask, NumWaitersState_ShiftCount); + } + + set + { + //setting to <0 would indicate an internal flaw, hence Assert is appropriate. + Debug.Assert(value >= 0, "NumWaiters should never be less than zero. This indicates an internal error."); + + // it is possible for the max number of waiters to be exceeded via user-code, hence we use a real exception here. + if (value >= NumWaitersState_MaxValue) + throw new InvalidOperationException(string.Format(SR.ManualResetEventSlim_ctor_TooManyWaiters, NumWaitersState_MaxValue)); + + UpdateStateAtomically(value << NumWaitersState_ShiftCount, NumWaitersState_BitMask); + } + } + + //----------------------------------------------------------------------------------- + // Constructs a new event, optionally specifying the initial state and spin count. + // The defaults are that the event is unsignaled and some reasonable default spin. + // + + /// + /// Initializes a new instance of the + /// class with an initial state of nonsignaled. + /// + public ManualResetEventSlim() + : this(false) + { + } + + /// + /// Initializes a new instance of the + /// class with a boolean value indicating whether to set the initial state to signaled. + /// + /// true to set the initial state signaled; false to set the initial state + /// to nonsignaled. + public ManualResetEventSlim(bool initialState) + { + // Specify the defualt spin count, and use default spin if we're + // on a multi-processor machine. Otherwise, we won't. + Initialize(initialState, SpinWait.SpinCountforSpinBeforeWait); + } + + /// + /// Initializes a new instance of the + /// class with a Boolean value indicating whether to set the initial state to signaled and a specified + /// spin count. + /// + /// true to set the initial state to signaled; false to set the initial state + /// to nonsignaled. + /// The number of spin waits that will occur before falling back to a true + /// wait. + /// is less than + /// 0 or greater than the maximum allowed value. + public ManualResetEventSlim(bool initialState, int spinCount) + { + if (spinCount < 0) + { + throw new ArgumentOutOfRangeException(nameof(spinCount)); + } + + if (spinCount > SpinCountState_MaxValue) + { + throw new ArgumentOutOfRangeException( + nameof(spinCount), + string.Format(SR.ManualResetEventSlim_ctor_SpinCountOutOfRange, SpinCountState_MaxValue)); + } + + // We will suppress default spin because the user specified a count. + Initialize(initialState, spinCount); + } + + /// + /// Initializes the internal state of the event. + /// + /// Whether the event is set initially or not. + /// The spin count that decides when the event will block. + private void Initialize(bool initialState, int spinCount) + { + 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; + } + + /// + /// Helper to ensure the lock object is created before first use. + /// + private void EnsureLockObjectCreated() + { + if (m_lock != null) + return; + + object newObj = new object(); + Interlocked.CompareExchange(ref m_lock, newObj, null); // failure is benign. Someone else set the value. + } + + /// + /// This method lazily initializes the event object. It uses CAS to guarantee that + /// many threads racing to call this at once don't result in more than one event + /// being stored and used. The event will be signaled or unsignaled depending on + /// the state of the thin-event itself, with synchronization taken into account. + /// + /// True if a new event was created and stored, false otherwise. + private bool LazyInitializeEvent() + { + bool preInitializeIsSet = IsSet; + ManualResetEvent newEventObj = new ManualResetEvent(preInitializeIsSet); + + // We have to CAS this in case we are racing with another thread. We must + // guarantee only one event is actually stored in this field. + if (Interlocked.CompareExchange(ref m_eventObj, newEventObj, null) != null) + { + // Someone else set the value due to a race condition. Destroy the garbage event. + newEventObj.Dispose(); + + return false; + } + 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 + // the CAS above (in addition to m_state being volatile) prevents this read + // from moving earlier and being collapsed with our original one. + bool currentIsSet = IsSet; + if (currentIsSet != preInitializeIsSet) + { + Debug.Assert(currentIsSet, + "The only safe concurrent transition is from unset->set: detected set->unset."); + + // We saw it as unsignaled, but it has since become set. + lock (newEventObj) + { + // If our event hasn't already been disposed of, we must set it. + if (m_eventObj == newEventObj) + { + newEventObj.Set(); + } + } + } + + return true; + } + } + + /// + /// Sets the state of the event to signaled, which allows one or more threads waiting on the event to + /// proceed. + /// + public void Set() + { + Set(false); + } + + /// + /// Private helper to actually perform the Set. + /// + /// Indicates whether we are calling Set() during cancellation. + /// The object has been canceled. + private void Set(bool duringCancellation) + { + // We need to ensure that IsSet=true does not get reordered past the read of m_eventObj + // This would be a legal movement according to the .NET memory model. + // The code is safe as IsSet involves an Interlocked.CompareExchange which provides a full memory barrier. + IsSet = true; + + // If there are waiting threads, we need to pulse them. + if (Waiters > 0) + { + Debug.Assert(m_lock != null); //if waiters>0, then m_lock has already been created. + lock (m_lock) + { + Monitor.PulseAll(m_lock); + } + } + + ManualResetEvent eventObj = m_eventObj; + + //Design-decision: do not set the event if we are in cancellation -> better to deadlock than to wake up waiters incorrectly + //It would be preferable to wake up the event and have it throw OCE. This requires MRE to implement cancellation logic + + if (eventObj != null && !duringCancellation) + { + // We must surround this call to Set in a lock. The reason is fairly subtle. + // Sometimes a thread will issue a Wait and wake up after we have set m_state, + // but before we have gotten around to setting m_eventObj (just below). That's + // because Wait first checks m_state and will only access the event if absolutely + // necessary. However, the coding pattern { event.Wait(); event.Dispose() } is + // quite common, and we must support it. If the waiter woke up and disposed of + // the event object before the setter has finished, however, we would try to set a + // now-disposed Win32 event. Crash! To deal with this race condition, we use a lock to + // protect access to the event object when setting and disposing of it. We also + // double-check that the event has not become null in the meantime when in the lock. + + lock (eventObj) + { + if (m_eventObj != null) + { + // If somebody is waiting, we must set the event. + m_eventObj.Set(); + } + } + } + +#if DEBUG + m_lastSetTime = DateTime.UtcNow.Ticks; +#endif + } + + /// + /// Sets the state of the event to nonsignaled, which causes threads to block. + /// + /// + /// Unlike most of the members of , is not + /// thread-safe and may not be used concurrently with other members of this instance. + /// + public void Reset() + { + ThrowIfDisposed(); + // If there's an event, reset it. + if (m_eventObj != null) + { + m_eventObj.Reset(); + } + + // There is a race condition here. If another thread Sets the event, we will get into a state + // where m_state will be unsignaled, yet the Win32 event object will have been signaled. + // This could cause waiting threads to wake up even though the event is in an + // unsignaled state. This is fine -- those that are calling Reset concurrently are + // responsible for doing "the right thing" -- e.g. rechecking the condition and + // resetting the event manually. + + // And finally set our state back to unsignaled. + IsSet = false; + +#if DEBUG + m_lastResetTime = DateTime.UtcNow.Ticks; +#endif + } + + /// + /// Blocks the current thread until the current is set. + /// + /// + /// The maximum number of waiters has been exceeded. + /// + /// + /// The caller of this method blocks indefinitely until the current instance is set. The caller will + /// return immediately if the event is currently in a set state. + /// + public void Wait() + { + Wait(Timeout.Infinite, new CancellationToken()); + } + + /// + /// Blocks the current thread until the current receives a signal, + /// while observing a . + /// + /// The to + /// observe. + /// + /// The maximum number of waiters has been exceeded. + /// + /// was + /// canceled. + /// + /// The caller of this method blocks indefinitely until the current instance is set. The caller will + /// return immediately if the event is currently in a set state. + /// + public void Wait(CancellationToken cancellationToken) + { + Wait(Timeout.Infinite, cancellationToken); + } + + /// + /// Blocks the current thread until the current is set, using a + /// to measure the time interval. + /// + /// A that represents the number of milliseconds + /// to wait, or a that represents -1 milliseconds to wait indefinitely. + /// + /// true if the was set; otherwise, + /// false. + /// is a negative + /// number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater + /// than . + /// + /// The maximum number of waiters has been exceeded. + /// + public bool Wait(TimeSpan timeout) + { + long totalMilliseconds = (long)timeout.TotalMilliseconds; + if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue) + { + throw new ArgumentOutOfRangeException(nameof(timeout)); + } + + return Wait((int)totalMilliseconds, new CancellationToken()); + } + + /// + /// Blocks the current thread until the current is set, using a + /// to measure the time interval, while observing a . + /// + /// A that represents the number of milliseconds + /// to wait, or a that represents -1 milliseconds to wait indefinitely. + /// + /// The to + /// observe. + /// true if the was set; otherwise, + /// false. + /// is a negative + /// number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater + /// than . + /// was canceled. + /// + /// The maximum number of waiters has been exceeded. + /// + public bool Wait(TimeSpan timeout, CancellationToken cancellationToken) + { + long totalMilliseconds = (long)timeout.TotalMilliseconds; + if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue) + { + throw new ArgumentOutOfRangeException(nameof(timeout)); + } + + return Wait((int)totalMilliseconds, cancellationToken); + } + + /// + /// Blocks the current thread until the current is set, using a + /// 32-bit signed integer to measure the time interval. + /// + /// The number of milliseconds to wait, or (-1) to wait indefinitely. + /// true if the was set; otherwise, + /// false. + /// is a + /// negative number other than -1, which represents an infinite time-out. + /// + /// The maximum number of waiters has been exceeded. + /// + public bool Wait(int millisecondsTimeout) + { + return Wait(millisecondsTimeout, new CancellationToken()); + } + + /// + /// Blocks the current thread until the current is set, using a + /// 32-bit signed integer to measure the time interval, while observing a . + /// + /// The number of milliseconds to wait, or (-1) to wait indefinitely. + /// The to + /// observe. + /// true if the was set; otherwise, + /// false. + /// is a + /// negative number other than -1, which represents an infinite time-out. + /// + /// The maximum number of waiters has been exceeded. + /// + /// was canceled. + public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken) + { + ThrowIfDisposed(); + cancellationToken.ThrowIfCancellationRequested(); // an early convenience check + + if (millisecondsTimeout < -1) + { + throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout)); + } + + if (!IsSet) + { + if (millisecondsTimeout == 0) + { + // For 0-timeouts, we just return immediately. + return false; + } + + + // We spin briefly before falling back to allocating and/or waiting on a true event. + uint startTime = 0; + bool bNeedTimeoutAdjustment = false; + int realMillisecondsTimeout = millisecondsTimeout; //this will be adjusted if necessary. + + if (millisecondsTimeout != Timeout.Infinite) + { + // We will account for time spent spinning, so that we can decrement it from our + // timeout. In most cases the time spent in this section will be negligible. But + // we can't discount the possibility of our thread being switched out for a lengthy + // period of time. The timeout adjustments only take effect when and if we actually + // decide to block in the kernel below. + + startTime = TimeoutHelper.GetTime(); + bNeedTimeoutAdjustment = true; + } + + // Spin + int spinCount = SpinCount; + var spinner = new SpinWait(); + while (spinner.Count < spinCount) + { + spinner.SpinOnce(SpinWait.Sleep1ThresholdForSpinBeforeWait); + + if (IsSet) + { + return true; + } + + if (spinner.Count >= 100 && spinner.Count % 10 == 0) // check the cancellation token if the user passed a very large spin count + cancellationToken.ThrowIfCancellationRequested(); + } + + // Now enter the lock and wait. + EnsureLockObjectCreated(); + + // We must register and unregister the token outside of the lock, to avoid deadlocks. + using (cancellationToken.InternalRegisterWithoutEC(s_cancellationTokenCallback, this)) + { + lock (m_lock) + { + // Loop to cope with spurious wakeups from other waits being canceled + while (!IsSet) + { + // If our token was canceled, we must throw and exit. + cancellationToken.ThrowIfCancellationRequested(); + + //update timeout (delays in wait commencement are due to spinning and/or spurious wakeups from other waits being canceled) + if (bNeedTimeoutAdjustment) + { + realMillisecondsTimeout = TimeoutHelper.UpdateTimeOut(startTime, millisecondsTimeout); + if (realMillisecondsTimeout <= 0) + return false; + } + + // There is a race condition that Set will fail to see that there are waiters as Set does not take the lock, + // so after updating waiters, we must check IsSet again. + // Also, we must ensure there cannot be any reordering of the assignment to Waiters and the + // read from IsSet. This is guaranteed as Waiters{set;} involves an Interlocked.CompareExchange + // operation which provides a full memory barrier. + // If we see IsSet=false, then we are guaranteed that Set() will see that we are + // waiting and will pulse the monitor correctly. + + Waiters = Waiters + 1; + + if (IsSet) //This check must occur after updating Waiters. + { + Waiters--; //revert the increment. + return true; + } + + // Now finally perform the wait. + try + { + // ** the actual wait ** + if (!Monitor.Wait(m_lock, realMillisecondsTimeout)) + return false; //return immediately if the timeout has expired. + } + finally + { + // Clean up: we're done waiting. + Waiters = Waiters - 1; + } + // 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) + } + } + } + } // automatically disposes (and unregisters) the callback + + return true; //done. The wait was satisfied. + } + + /// + /// Releases all resources used by the current instance of . + /// + /// + /// Unlike most of the members of , is not + /// thread-safe and may not be used concurrently with other members of this instance. + /// + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + /// + /// When overridden in a derived class, releases the unmanaged resources used by the + /// , and optionally releases the managed resources. + /// + /// true to release both managed and unmanaged resources; + /// false to release only unmanaged resources. + /// + /// Unlike most of the members of , is not + /// thread-safe and may not be used concurrently with other members of this instance. + /// + protected virtual void Dispose(bool disposing) + { + if ((m_combinedState & Dispose_BitMask) != 0) + return; // already disposed + + m_combinedState |= Dispose_BitMask; //set the dispose bit + if (disposing) + { + // We will dispose of the event object. We do this under a lock to protect + // against the race condition outlined in the Set method above. + ManualResetEvent eventObj = m_eventObj; + if (eventObj != null) + { + lock (eventObj) + { + eventObj.Dispose(); + m_eventObj = null; + } + } + } + } + + /// + /// Throw ObjectDisposedException if the MRES is disposed + /// + private void ThrowIfDisposed() + { + if ((m_combinedState & Dispose_BitMask) != 0) + throw new ObjectDisposedException(SR.ManualResetEventSlim_Disposed); + } + + /// + /// Private helper method to wake up waiters when a cancellationToken gets canceled. + /// + private static Action s_cancellationTokenCallback = new Action(CancellationTokenCallback); + private static void CancellationTokenCallback(object obj) + { + ManualResetEventSlim mre = obj as ManualResetEventSlim; + Debug.Assert(mre != null, "Expected a ManualResetEventSlim"); + Debug.Assert(mre.m_lock != null); //the lock should have been created before this callback is registered for use. + lock (mre.m_lock) + { + Monitor.PulseAll(mre.m_lock); // awaken all waiters + } + } + + /// + /// Private helper method for updating parts of a bit-string state value. + /// Mainly called from the IsSet and Waiters properties setters + /// + /// + /// Note: the parameter types must be int as CompareExchange cannot take a Uint + /// + /// The new value + /// The mask used to set the bits + private void UpdateStateAtomically(int newBits, int updateBitsMask) + { + SpinWait sw = new SpinWait(); + + Debug.Assert((newBits | updateBitsMask) == updateBitsMask, "newBits do not fall within the updateBitsMask."); + + do + { + int oldState = m_combinedState; // cache the old value for testing in CAS + + // Procedure:(1) zero the updateBits. eg oldState = [11111111] flag= [00111000] newState = [11000111] + // then (2) map in the newBits. eg [11000111] newBits=00101000, newState=[11101111] + int newState = (oldState & ~updateBitsMask) | newBits; + + if (Interlocked.CompareExchange(ref m_combinedState, newState, oldState) == oldState) + { + return; + } + + sw.SpinOnce(); + } while (true); + } + + /// + /// Private helper method - performs Mask and shift, particular helpful to extract a field from a packed word. + /// eg ExtractStatePortionAndShiftRight(0x12345678, 0xFF000000, 24) => 0x12, ie extracting the top 8-bits as a simple integer + /// + /// ?? is there a common place to put this rather than being private to MRES? + /// + /// + /// + /// + /// + private static int ExtractStatePortionAndShiftRight(int state, int mask, int rightBitShiftCount) + { + //convert to uint before shifting so that right-shift does not replicate the sign-bit, + //then convert back to int. + return unchecked((int)(((uint)(state & mask)) >> rightBitShiftCount)); + } + + /// + /// Performs a Mask operation, but does not perform the shift. + /// This is acceptable for boolean values for which the shift is unnecessary + /// eg (val & Mask) != 0 is an appropriate way to extract a boolean rather than using + /// ((val & Mask) >> shiftAmount) == 1 + /// + /// ?? is there a common place to put this rather than being private to MRES? + /// + /// + /// + private static int ExtractStatePortion(int state, int mask) + { + return state & mask; + } + } +} diff --git a/src/System.Private.CoreLib/shared/System/Threading/SpinWait.cs b/src/System.Private.CoreLib/shared/System/Threading/SpinWait.cs index d23569294c4..414ad1852f8 100644 --- a/src/System.Private.CoreLib/shared/System/Threading/SpinWait.cs +++ b/src/System.Private.CoreLib/shared/System/Threading/SpinWait.cs @@ -255,7 +255,7 @@ public static void SpinUntil(Func condition) /// The argument is null. /// is a negative number /// other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater than - /// . + /// . public static bool SpinUntil(Func condition, TimeSpan timeout) { // Validate the timeout From c559acdbd6b1a5105bead6b16ee19445ed3c9402 Mon Sep 17 00:00:00 2001 From: HumanEquivalentUnit Date: Mon, 9 Jul 2018 16:22:38 +0100 Subject: [PATCH 63/69] Fix a comment in the string.ToLower() method (dotnet/coreclr#18832) Line 307 is lowercasing the current character, but the comment says "store the current character, upper-cased", fixed comment to say "store the current character, lower-cased". (Equivalent and correct "upper-cased" comment is on line 252) Signed-off-by: dotnet-bot --- .../shared/System/Globalization/TextInfo.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/System.Private.CoreLib/shared/System/Globalization/TextInfo.cs b/src/System.Private.CoreLib/shared/System/Globalization/TextInfo.cs index c5f392cb080..8073b4b56bb 100644 --- a/src/System.Private.CoreLib/shared/System/Globalization/TextInfo.cs +++ b/src/System.Private.CoreLib/shared/System/Globalization/TextInfo.cs @@ -302,7 +302,7 @@ private unsafe string ChangeCase(string source, bool toUpper) source.AsSpan(0, sourcePos).CopyTo(new Span(pResult, sourcePos)); } - // And store the current character, upper-cased. + // And store the current character, lower-cased. char* d = pResult + sourcePos; *d++ = (char)(c | 0x20); sourcePos++; From 5eb0ed9cc1debc9995122da53dc2f4ef27cb0a9b Mon Sep 17 00:00:00 2001 From: Anipik Date: Mon, 9 Jul 2018 10:47:41 -0700 Subject: [PATCH 64/69] Non-shared changes --- src/System.Private.CoreLib/src/System.Private.CoreLib.csproj | 1 - 1 file changed, 1 deletion(-) diff --git a/src/System.Private.CoreLib/src/System.Private.CoreLib.csproj b/src/System.Private.CoreLib/src/System.Private.CoreLib.csproj index 7b15dd84722..ac48c90adce 100644 --- a/src/System.Private.CoreLib/src/System.Private.CoreLib.csproj +++ b/src/System.Private.CoreLib/src/System.Private.CoreLib.csproj @@ -305,7 +305,6 @@ - From d5b01b3de438ab979fe6268af8b6c4114db51c7c Mon Sep 17 00:00:00 2001 From: Viktor Hofer Date: Mon, 9 Jul 2018 23:41:07 +0200 Subject: [PATCH 65/69] Fix serialization type in NotFiniteNumberException (dotnet/coreclr#18833) Signed-off-by: dotnet-bot --- .../shared/System/NotFiniteNumberException.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/System.Private.CoreLib/shared/System/NotFiniteNumberException.cs b/src/System.Private.CoreLib/shared/System/NotFiniteNumberException.cs index b9c9af06d31..9afc1045888 100644 --- a/src/System.Private.CoreLib/shared/System/NotFiniteNumberException.cs +++ b/src/System.Private.CoreLib/shared/System/NotFiniteNumberException.cs @@ -55,13 +55,13 @@ public NotFiniteNumberException(string message, double offendingNumber, Exceptio protected NotFiniteNumberException(SerializationInfo info, StreamingContext context) : base(info, context) { - _offendingNumber = info.GetInt32("OffendingNumber"); + _offendingNumber = info.GetDouble("OffendingNumber"); // Do not rename (binary serialization) } public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); - info.AddValue("OffendingNumber", _offendingNumber, typeof(int)); + info.AddValue("OffendingNumber", _offendingNumber, typeof(double)); // Do not rename (binary serialization) } public double OffendingNumber From ad60136a1591aa3d4c7652bb58d226e4de4391ae Mon Sep 17 00:00:00 2001 From: Jan Kotas Date: Mon, 9 Jul 2018 18:59:06 -0700 Subject: [PATCH 66/69] Fix In,Out marshaling for SafeHandles (#6074) Fixes #3291 #6071 --- .../src/TypeSystem/Interop/IL/Marshaller.cs | 75 +++++++++++-------- tests/src/Simple/PInvoke/PInvoke.cs | 15 ++++ tests/src/Simple/PInvoke/PInvokeNative.cpp | 10 ++- 3 files changed, 66 insertions(+), 34 deletions(-) diff --git a/src/Common/src/TypeSystem/Interop/IL/Marshaller.cs b/src/Common/src/TypeSystem/Interop/IL/Marshaller.cs index f3fbf3f6319..d7e88915d13 100644 --- a/src/Common/src/TypeSystem/Interop/IL/Marshaller.cs +++ b/src/Common/src/TypeSystem/Interop/IL/Marshaller.cs @@ -718,6 +718,9 @@ protected virtual void EmitMarshalArgumentManagedToNative() PropagateToByRefArg(_ilCodeStreams.UnmarshallingCodestream, _managedHome); } } + + // TODO This should be in finally block + // https://github.com/dotnet/corert/issues/6075 EmitCleanupManaged(_ilCodeStreams.UnmarshallingCodestream); } @@ -1690,14 +1693,30 @@ protected override void EmitMarshalArgumentManagedToNative() PropagateFromByRefArg(marshallingCodeStream, _managedHome); } - // TODO: https://github.com/dotnet/corert/issues/3291 - // We don't support [IN,OUT] together yet, either IN or OUT. - if (Out && In) + var safeHandleType = InteropTypes.GetSafeHandle(Context); + + if (In) { - throw new NotSupportedException("Marshalling an argument as both in and out not yet implemented"); - } + if (IsManagedByRef) + PropagateFromByRefArg(marshallingCodeStream, _managedHome); - var safeHandleType = InteropTypes.GetSafeHandle(Context); + var vAddRefed = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.Boolean)); + LoadManagedValue(marshallingCodeStream); + marshallingCodeStream.EmitLdLoca(vAddRefed); + marshallingCodeStream.Emit(ILOpcode.call, emitter.NewToken( + safeHandleType.GetKnownMethod("DangerousAddRef", null))); + + LoadManagedValue(marshallingCodeStream); + marshallingCodeStream.Emit(ILOpcode.call, emitter.NewToken( + safeHandleType.GetKnownMethod("DangerousGetHandle", null))); + StoreNativeValue(marshallingCodeStream); + + // TODO: This should be inside finally block and only executed if the handle was addrefed + // https://github.com/dotnet/corert/issues/6075 + LoadManagedValue(unmarshallingCodeStream); + unmarshallingCodeStream.Emit(ILOpcode.call, emitter.NewToken( + safeHandleType.GetKnownMethod("DangerousRelease", null))); + } if (Out && IsManagedByRef) { @@ -1708,42 +1727,36 @@ protected override void EmitMarshalArgumentManagedToNative() // 2) Initialize a local IntPtr that will be passed to the native call. // 3) After the native call, the new handle value is written into the output SafeHandle and that SafeHandle // is propagated back to the caller. - var vOutValue = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.IntPtr)); var vSafeHandle = emitter.NewLocal(ManagedType); AllocSafeHandle(marshallingCodeStream); marshallingCodeStream.EmitStLoc(vSafeHandle); - _ilCodeStreams.CallsiteSetupCodeStream.EmitLdLoca(vOutValue); + + var lSkipPropagation = emitter.NewCodeLabel(); + if (In) + { + // Propagate the value only if it has changed + ILLocalVariable vOriginalValue = emitter.NewLocal(NativeType); + LoadNativeValue(marshallingCodeStream); + marshallingCodeStream.EmitStLoc(vOriginalValue); + + unmarshallingCodeStream.EmitLdLoc(vOriginalValue); + LoadNativeValue(unmarshallingCodeStream); + unmarshallingCodeStream.Emit(ILOpcode.beq, lSkipPropagation); + } unmarshallingCodeStream.EmitLdLoc(vSafeHandle); - unmarshallingCodeStream.EmitLdLoc(vOutValue); + LoadNativeValue(unmarshallingCodeStream); unmarshallingCodeStream.Emit(ILOpcode.call, emitter.NewToken( - safeHandleType.GetKnownMethod("SetHandle", null))); + safeHandleType.GetKnownMethod("SetHandle", null))); + unmarshallingCodeStream.EmitLdArg(Index - 1); unmarshallingCodeStream.EmitLdLoc(vSafeHandle); - StoreManagedValue(unmarshallingCodeStream); + unmarshallingCodeStream.EmitStInd(ManagedType); - PropagateToByRefArg(unmarshallingCodeStream, _managedHome); + unmarshallingCodeStream.EmitLabel(lSkipPropagation); } - else - { - var vAddRefed = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.Boolean)); - LoadManagedValue(marshallingCodeStream); - marshallingCodeStream.EmitLdLoca(vAddRefed); - marshallingCodeStream.Emit(ILOpcode.call, emitter.NewToken( - safeHandleType.GetKnownMethod("DangerousAddRef", null))); - LoadManagedValue(marshallingCodeStream); - marshallingCodeStream.Emit(ILOpcode.call, emitter.NewToken( - safeHandleType.GetKnownMethod("DangerousGetHandle", null))); - StoreNativeValue(marshallingCodeStream); - - // TODO: This should be inside finally block and only executed it the handle was addrefed - LoadManagedValue(unmarshallingCodeStream); - unmarshallingCodeStream.Emit(ILOpcode.call, emitter.NewToken( - safeHandleType.GetKnownMethod("DangerousRelease", null))); - - LoadNativeArg(_ilCodeStreams.CallsiteSetupCodeStream); - } + LoadNativeArg(callsiteCodeStream); } } diff --git a/tests/src/Simple/PInvoke/PInvoke.cs b/tests/src/Simple/PInvoke/PInvoke.cs index d1112d01878..9a88170b67b 100644 --- a/tests/src/Simple/PInvoke/PInvoke.cs +++ b/tests/src/Simple/PInvoke/PInvoke.cs @@ -97,6 +97,9 @@ internal class Program [DllImport("*", CallingConvention = CallingConvention.StdCall)] public static extern int SafeHandleOutTest(out SafeMemoryHandle sh1); + [DllImport("*", CallingConvention = CallingConvention.StdCall)] + public static extern int SafeHandleRefTest(ref SafeMemoryHandle sh1, bool change); + [DllImport("*", CallingConvention = CallingConvention.StdCall, SetLastError = true)] public static extern bool LastErrorTest(); @@ -436,6 +439,18 @@ private static void TestSafeHandle() int actual = SafeHandleOutTest(out hnd2); int expected = unchecked((int)hnd2.DangerousGetHandle().ToInt64()); ThrowIfNotEquals(actual, expected, "SafeHandle out marshalling failed"); + + Console.WriteLine("Testing marshalling ref SafeHandle"); + SafeMemoryHandle hndOriginal = hnd2; + SafeHandleRefTest(ref hnd2, false); + ThrowIfNotEquals(hndOriginal, hnd2, "SafeHandle no-op ref marshalling failed"); + + int actual3 = SafeHandleRefTest(ref hnd2, true); + int expected3 = unchecked((int)hnd2.DangerousGetHandle().ToInt64()); + ThrowIfNotEquals(actual3, expected3, "SafeHandle ref marshalling failed"); + + hndOriginal.Dispose(); + hnd2.Dispose(); } private static void TestSizeParamIndex() diff --git a/tests/src/Simple/PInvoke/PInvokeNative.cpp b/tests/src/Simple/PInvoke/PInvokeNative.cpp index 90ea1dbff86..713fb4435ae 100644 --- a/tests/src/Simple/PInvoke/PInvokeNative.cpp +++ b/tests/src/Simple/PInvoke/PInvokeNative.cpp @@ -313,13 +313,17 @@ DLL_EXPORT bool __stdcall SafeHandleTest(HANDLE sh, long shValue) DLL_EXPORT long __stdcall SafeHandleOutTest(HANDLE **sh) { - if (sh == NULL) - return -1; - *sh = (HANDLE *)malloc(100); return (long)((size_t)(*sh)); } +DLL_EXPORT long __stdcall SafeHandleRefTest(HANDLE **sh, bool alloc) +{ + if (alloc) + *sh = (HANDLE *)malloc(100); + return (long)((size_t)(*sh)); +} + DLL_EXPORT bool __stdcall ReversePInvoke_Int(int(__stdcall *fnPtr) (int, int, int, int, int, int, int, int, int, int)) { return fnPtr(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) == 55; From f426c510234cd2172f433a6c1cdd97915a1777d3 Mon Sep 17 00:00:00 2001 From: Jan Kotas Date: Mon, 9 Jul 2018 19:49:52 -0700 Subject: [PATCH 67/69] Use uapaot mscorlib facade (#6068) This is required to use the correct forwarder for System.Runtime.InteropServices types that still have a different home between CoreCLR and CoreRT. Workaround for #3231 Fixes #6062 --- src/Framework/Framework-uapaot.depproj | 6 +++++- src/Framework/Framework.depproj | 6 +++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/Framework/Framework-uapaot.depproj b/src/Framework/Framework-uapaot.depproj index 38b8dfec98d..47fc83e40ff 100644 --- a/src/Framework/Framework-uapaot.depproj +++ b/src/Framework/Framework-uapaot.depproj @@ -19,9 +19,13 @@ + + + + + - diff --git a/src/Framework/Framework.depproj b/src/Framework/Framework.depproj index 9b5a29af43d..395b213e663 100644 --- a/src/Framework/Framework.depproj +++ b/src/Framework/Framework.depproj @@ -29,9 +29,13 @@ + + + + + - From 341380e5478a1285b51cdb416ada894e55248816 Mon Sep 17 00:00:00 2001 From: Marco Rossignoli Date: Tue, 10 Jul 2018 04:52:45 +0200 Subject: [PATCH 68/69] Add back most CreateInstance APIs to AppDomain and Activator (#6056) --- .../src/System/Activator.cs | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/src/System.Private.CoreLib/src/System/Activator.cs b/src/System.Private.CoreLib/src/System/Activator.cs index 8ecfa24b8ee..b098adfd52c 100644 --- a/src/System.Private.CoreLib/src/System/Activator.cs +++ b/src/System.Private.CoreLib/src/System/Activator.cs @@ -11,6 +11,7 @@ using System.Globalization; using System.Reflection; using System.Runtime.CompilerServices; +using System.Runtime.Remoting; using System.Runtime; using Internal.Reflection.Augments; @@ -147,6 +148,50 @@ public static object CreateInstance(Type type, BindingFlags bindingAttr, Binder } private const BindingFlags ConstructorDefault = BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance; + + public static ObjectHandle CreateInstance(string assemblyName, string typeName) + { + throw new PlatformNotSupportedException(); // https://github.com/dotnet/corefx/issues/30845 + } + + public static ObjectHandle CreateInstance(string assemblyName, + string typeName, + bool ignoreCase, + BindingFlags bindingAttr, + Binder binder, + object[] args, + CultureInfo culture, + object[] activationAttributes) + { + throw new PlatformNotSupportedException(); // https://github.com/dotnet/corefx/issues/30845 + } + + public static ObjectHandle CreateInstance(string assemblyName, string typeName, object[] activationAttributes) + { + throw new PlatformNotSupportedException(); // https://github.com/dotnet/corefx/issues/30845 + } + + public static ObjectHandle CreateInstanceFrom(string assemblyFile, string typeName) + { + throw new PlatformNotSupportedException(); + } + + public static ObjectHandle CreateInstanceFrom(string assemblyFile, + string typeName, + bool ignoreCase, + BindingFlags bindingAttr, + Binder binder, + object[] args, + CultureInfo culture, + object[] activationAttributes) + { + throw new PlatformNotSupportedException(); + } + + public static ObjectHandle CreateInstanceFrom(string assemblyFile, string typeName, object[] activationAttributes) + { + throw new PlatformNotSupportedException(); + } } } From cd4caf70e35eaa4654d8c9c4b1e8c602dee08e65 Mon Sep 17 00:00:00 2001 From: Jan Kotas Date: Tue, 10 Jul 2018 01:35:02 -0700 Subject: [PATCH 69/69] Regression test for inlined PInvoke with marshalling data (#6067) Extracted from #6060 --- tests/src/Simple/PInvoke/PInvoke.cs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/tests/src/Simple/PInvoke/PInvoke.cs b/tests/src/Simple/PInvoke/PInvoke.cs index 9a88170b67b..29e2def9205 100644 --- a/tests/src/Simple/PInvoke/PInvoke.cs +++ b/tests/src/Simple/PInvoke/PInvoke.cs @@ -3,9 +3,17 @@ // See the LICENSE file in the project root for more information. using System; +using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; +// Make sure the interop data are present even without reflection +namespace System.Runtime.CompilerServices +{ + [AttributeUsage(AttributeTargets.All)] + internal class __BlockAllReflectionAttribute : Attribute { } +} + // Name of namespace matches the name of the assembly on purpose to // ensure that we can handle this (mostly an issue for C++ code generation). namespace PInvokeTests @@ -107,6 +115,11 @@ internal class Program [DllImport("*", CallingConvention = CallingConvention.StdCall)] static extern bool ReversePInvoke_Int(Delegate_Int del); + delegate int Delegate_Int_AggressiveInlining(int a, int b, int c, int d, int e, int f, int g, int h, int i, int j); + [DllImport("*", CallingConvention = CallingConvention.StdCall, EntryPoint = "ReversePInvoke_Int")] + [MethodImpl(MethodImplOptions.AggressiveInlining)] + static extern bool ReversePInvoke_Int_AggressiveInlining(Delegate_Int_AggressiveInlining del); + [UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet=CharSet.Ansi)] delegate bool Delegate_String(string s); [DllImport("*", CallingConvention = CallingConvention.StdCall)] @@ -489,8 +502,13 @@ public bool GetString(String s) private static void TestDelegate() { Console.WriteLine("Testing Delegate"); + Delegate_Int del = new Delegate_Int(Sum); ThrowIfNotEquals(true, ReversePInvoke_Int(del), "Delegate marshalling failed."); + + Delegate_Int_AggressiveInlining del_aggressive = new Delegate_Int_AggressiveInlining(Sum); + ThrowIfNotEquals(true, ReversePInvoke_Int_AggressiveInlining(del_aggressive), "Delegate marshalling with aggressive inlining failed."); + unsafe { //