Skip to content

Commit

Permalink
Add argument null check for ToHexString to keep same behavior between…
Browse files Browse the repository at this point in the history
… net9 and older version (#3605)

Co-authored-by: Jimmy <[email protected]>
  • Loading branch information
nan01ab and Jim8y authored Nov 30, 2024
1 parent 6cafc3b commit b8073d4
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/Neo.Extensions/ByteExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,16 @@ public static int XxHash3_32(this byte[] value, long seed = DefaultXxHash3Seed)
/// </summary>
/// <param name="value">The byte array to convert.</param>
/// <returns>The converted hex <see cref="string"/>.</returns>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="value"/> is null.</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string ToHexString(this byte[] value)
{
#if NET9_0_OR_GREATER
return Convert.ToHexStringLower(value);
#else
if (value is null)
throw new ArgumentNullException(nameof(value));

return string.Create(value.Length * 2, value, (span, bytes) =>
{
for (var i = 0; i < bytes.Length; i++)
Expand All @@ -74,12 +78,16 @@ public static string ToHexString(this byte[] value)
/// <param name="value">The byte array to convert.</param>
/// <param name="reverse">Indicates whether it should be converted in the reversed byte order.</param>
/// <returns>The converted hex <see cref="string"/>.</returns>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="value"/> is null.</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string ToHexString(this byte[] value, bool reverse = false)
{
if (!reverse)
return ToHexString(value);

if (value is null)
throw new ArgumentNullException(nameof(value));

return string.Create(value.Length * 2, value, (span, bytes) =>
{
for (var i = 0; i < bytes.Length; i++)
Expand Down
3 changes: 3 additions & 0 deletions tests/Neo.Extensions.Tests/UT_ByteExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ public void TestToHexString()
{
byte[] nullStr = null;
Assert.ThrowsException<ArgumentNullException>(() => nullStr.ToHexString());
Assert.ThrowsException<ArgumentNullException>(() => nullStr.ToHexString(false));
Assert.ThrowsException<ArgumentNullException>(() => nullStr.ToHexString(true));

byte[] empty = Array.Empty<byte>();
empty.ToHexString().Should().Be("");
empty.ToHexString(false).Should().Be("");
Expand Down

0 comments on commit b8073d4

Please sign in to comment.