From 11ca9232160e0959edab3cae2d4e81724be01c40 Mon Sep 17 00:00:00 2001 From: Stephen Toub Date: Sun, 28 Jul 2024 07:37:31 -0400 Subject: [PATCH] Fix invalid IndexOutOfRangeException in Convert (#105339) --- .../System.Private.CoreLib/src/System/Convert.cs | 4 ++-- .../System/Convert.cs | 12 ++++++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/src/libraries/System.Private.CoreLib/src/System/Convert.cs b/src/libraries/System.Private.CoreLib/src/System/Convert.cs index d3b6f46783f27c..a0c74422853099 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Convert.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Convert.cs @@ -2397,7 +2397,7 @@ public static unsafe int ToBase64CharArray(byte[] inArray, int offsetIn, int len ArgumentOutOfRangeException.ThrowIfGreaterThan(offsetIn, inArrayLength - length); - if (inArrayLength == 0) + if (length == 0) return 0; // This is the maximally required length that must be available in the char array @@ -2798,7 +2798,7 @@ public static byte[] FromBase64CharArray(char[] inArray, int offset, int length) ArgumentOutOfRangeException.ThrowIfNegative(offset); ArgumentOutOfRangeException.ThrowIfGreaterThan(offset, inArray.Length - length); - if (inArray.Length == 0) + if (length == 0) { return Array.Empty(); } diff --git a/src/libraries/System.Runtime/tests/System.Runtime.Extensions.Tests/System/Convert.cs b/src/libraries/System.Runtime/tests/System.Runtime.Extensions.Tests/System/Convert.cs index 90833679760897..fa0233a2321264 100644 --- a/src/libraries/System.Runtime/tests/System.Runtime.Extensions.Tests/System/Convert.cs +++ b/src/libraries/System.Runtime/tests/System.Runtime.Extensions.Tests/System/Convert.cs @@ -32,6 +32,12 @@ public static void ToBase64CharArrayTest() Assert.Equal(344, length2); } + [Fact] + public static void ToBase64CharArray_NonEmptyInput_ZeroLength_Test() + { + Assert.Equal(0, Convert.ToBase64CharArray(new byte[1], 0, 0, new char[0], 0, Base64FormattingOptions.None)); + } + [Fact] public static void ToBase64StringTest() { @@ -77,6 +83,12 @@ public static void Base64_AllMethodsRoundtripConsistently() } } + [Fact] + public static void FromBase64CharArray_NonEmptyInputZeroLength_ReturnsEmptyArray() + { + Assert.Same(Array.Empty(), Convert.FromBase64CharArray(new char[42], 0, 0)); + } + [Fact] public void ToBooleanTests() {