Simpler implementation from PR feedback.
[platform/upstream/coreclr.git] / src / System.Private.CoreLib / shared / System / Runtime / InteropServices / SafeBuffer.cs
index 455e413..74edae3 100644 (file)
@@ -77,7 +77,7 @@ namespace System.Runtime.InteropServices
     {
         // 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 @@ namespace System.Runtime.InteropServices
         [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,13 +110,14 @@ namespace System.Runtime.InteropServices
         [CLSCompliant(false)]
         public void Initialize(uint numElements, uint sizeOfEachElement)
         {
-            if (IntPtr.Size == 4 && numElements * sizeOfEachElement > UInt32.MaxValue)
+            try
+            {
+                _numBytes = checked((UIntPtr)((ulong)numElements * sizeOfEachElement));
+            }
+            catch (OverflowException)
+            {
                 throw new ArgumentOutOfRangeException("numBytes", SR.ArgumentOutOfRange_AddressSpace);
-
-            if (numElements * sizeOfEachElement >= (ulong)Uninitialized)
-                throw new ArgumentOutOfRangeException(nameof(numElements), SR.ArgumentOutOfRange_UIntPtrMax);
-
-            _numBytes = checked((UIntPtr)(numElements * sizeOfEachElement));
+            }
         }
 
         /// <summary>
@@ -198,7 +199,7 @@ namespace System.Runtime.InteropServices
             SpaceCheck(ptr, sizeofT);
 
             // return *(T*) (_ptr + byteOffset);
-            T value = default(T);
+            T value = default;
             bool mustCallRelease = false;
             try
             {