From b8073d429bde36579bb736abfff1d661b918ab0a Mon Sep 17 00:00:00 2001 From: nan01ab Date: Sun, 1 Dec 2024 07:13:38 +0800 Subject: [PATCH] Add argument null check for ToHexString to keep same behavior between net9 and older version (#3605) Co-authored-by: Jimmy --- src/Neo.Extensions/ByteExtensions.cs | 8 ++++++++ tests/Neo.Extensions.Tests/UT_ByteExtensions.cs | 3 +++ 2 files changed, 11 insertions(+) diff --git a/src/Neo.Extensions/ByteExtensions.cs b/src/Neo.Extensions/ByteExtensions.cs index 61cb5bde2e..702b71f109 100644 --- a/src/Neo.Extensions/ByteExtensions.cs +++ b/src/Neo.Extensions/ByteExtensions.cs @@ -50,12 +50,16 @@ public static int XxHash3_32(this byte[] value, long seed = DefaultXxHash3Seed) /// /// The byte array to convert. /// The converted hex . + /// Thrown when is null. [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++) @@ -74,12 +78,16 @@ public static string ToHexString(this byte[] value) /// The byte array to convert. /// Indicates whether it should be converted in the reversed byte order. /// The converted hex . + /// Thrown when is null. [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++) diff --git a/tests/Neo.Extensions.Tests/UT_ByteExtensions.cs b/tests/Neo.Extensions.Tests/UT_ByteExtensions.cs index bb12d00eed..87c4ad9bd8 100644 --- a/tests/Neo.Extensions.Tests/UT_ByteExtensions.cs +++ b/tests/Neo.Extensions.Tests/UT_ByteExtensions.cs @@ -26,6 +26,9 @@ public void TestToHexString() { byte[] nullStr = null; Assert.ThrowsException(() => nullStr.ToHexString()); + Assert.ThrowsException(() => nullStr.ToHexString(false)); + Assert.ThrowsException(() => nullStr.ToHexString(true)); + byte[] empty = Array.Empty(); empty.ToHexString().Should().Be(""); empty.ToHexString(false).Should().Be("");