From 8f42dae9501e4d810fec3af2112551fca8f556ed Mon Sep 17 00:00:00 2001 From: Buyaa Namnan Date: Wed, 3 Jul 2024 12:50:26 -0700 Subject: [PATCH] Write 2 values once --- .../Text/Base64Url/Base64UrlEncoder.cs | 31 ++++++++++++++++--- 1 file changed, 27 insertions(+), 4 deletions(-) diff --git a/src/libraries/System.Private.CoreLib/src/System/Buffers/Text/Base64Url/Base64UrlEncoder.cs b/src/libraries/System.Private.CoreLib/src/System/Buffers/Text/Base64Url/Base64UrlEncoder.cs index dbc179f24e9d77..e803962ee48d6a 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Buffers/Text/Base64Url/Base64UrlEncoder.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Buffers/Text/Base64Url/Base64UrlEncoder.cs @@ -254,6 +254,19 @@ public unsafe void EncodeOneOptionallyPadTwo(byte* oneByte, byte* dest, ref byte byte i0 = Unsafe.Add(ref encodingMap, (IntPtr)(i >> 10)); byte i1 = Unsafe.Add(ref encodingMap, (IntPtr)((i >> 4) & 0x3F)); + ushort result; + + if (BitConverter.IsLittleEndian) + { + result = (ushort)(i0 | (i1 << 8)); + } + else + { + result = (ushort)((i0 << 8) | i1); + } + + Unsafe.WriteUnaligned(dest, result); + dest[0] = i0; dest[1] = i1; } @@ -331,11 +344,21 @@ public unsafe void EncodeOneOptionallyPadTwo(byte* oneByte, ushort* dest, ref by uint i = t0 << 8; - ushort i0 = Unsafe.Add(ref encodingMap, (IntPtr)(i >> 10)); - ushort i1 = Unsafe.Add(ref encodingMap, (IntPtr)((i >> 4) & 0x3F)); + uint i0 = Unsafe.Add(ref encodingMap, (IntPtr)(i >> 10)); + uint i1 = Unsafe.Add(ref encodingMap, (IntPtr)((i >> 4) & 0x3F)); - dest[0] = i0; - dest[1] = i1; + uint result; + + if (BitConverter.IsLittleEndian) + { + result = (i0 | (i1 << 16)); + } + else + { + result = ((i0 << 16) | i1); + } + + Unsafe.WriteUnaligned(dest, result); } [MethodImpl(MethodImplOptions.AggressiveInlining)]