From 282ab8cf13f7448de8d97a40b6167fa466693122 Mon Sep 17 00:00:00 2001 From: EgorBo Date: Fri, 30 Jun 2023 20:59:37 +0200 Subject: [PATCH 1/2] Clean up Guid.DecodeByte --- .../System.Private.CoreLib/src/System/Guid.cs | 21 +++---------------- 1 file changed, 3 insertions(+), 18 deletions(-) diff --git a/src/libraries/System.Private.CoreLib/src/System/Guid.cs b/src/libraries/System.Private.CoreLib/src/System/Guid.cs index 6c31cf523c5032..435d754788ea58 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Guid.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Guid.cs @@ -729,25 +729,10 @@ private static bool TryParseExactX(ReadOnlySpan guidString, ref GuidResult [MethodImpl(MethodImplOptions.AggressiveInlining)] private static byte DecodeByte(nuint ch1, nuint ch2, ref int invalidIfNegative) { - // TODO https://github.com/dotnet/runtime/issues/13464: - // Replace the Unsafe.Add with HexConverter.FromChar once the bounds checks are eliminated. + int result = (CharToHexLookup[(byte)ch1] << 4) | CharToHexLookup[(byte)ch1]; - ReadOnlySpan lookup = HexConverter.CharToHexLookup; - - int h1 = -1; - if (ch1 < (nuint)lookup.Length) - { - h1 = (sbyte)Unsafe.Add(ref MemoryMarshal.GetReference(lookup), (nint)ch1); - } - h1 <<= 4; - - int h2 = -1; - if (ch2 < (nuint)lookup.Length) - { - h2 = (sbyte)Unsafe.Add(ref MemoryMarshal.GetReference(lookup), (nint)ch2); - } - - int result = h1 | h2; + // Result will be negative if ch1 or/and ch2 are greater than 0xFF + result = (ch1 | ch2) >> 8 == 0 ? result : -1; invalidIfNegative |= result; return (byte)result; } From 82e0d6981db011cb7d48fcc39afc1155736ecc00 Mon Sep 17 00:00:00 2001 From: EgorBo Date: Fri, 30 Jun 2023 22:15:19 +0200 Subject: [PATCH 2/2] cleanup --- src/libraries/System.Private.CoreLib/src/System/Guid.cs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/libraries/System.Private.CoreLib/src/System/Guid.cs b/src/libraries/System.Private.CoreLib/src/System/Guid.cs index 435d754788ea58..d541c106a29d8e 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Guid.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Guid.cs @@ -727,9 +727,14 @@ private static bool TryParseExactX(ReadOnlySpan guidString, ref GuidResult } [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static byte DecodeByte(nuint ch1, nuint ch2, ref int invalidIfNegative) + private static byte DecodeByte(char ch1, char ch2, ref int invalidIfNegative) { - int result = (CharToHexLookup[(byte)ch1] << 4) | CharToHexLookup[(byte)ch1]; + ReadOnlySpan lookup = HexConverter.CharToHexLookup; + Debug.Assert(lookup.Length == 256); + + int upper = (sbyte)lookup[(byte)ch1]; + int lower = (sbyte)lookup[(byte)ch2]; + int result = (upper << 4) | lower; // Result will be negative if ch1 or/and ch2 are greater than 0xFF result = (ch1 | ch2) >> 8 == 0 ? result : -1;