< Summary

Line coverage
0%
Covered lines: 0
Uncovered lines: 1080
Coverable lines: 1080
Total lines: 3172
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 436
Branch coverage: 0%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Cyclomatic complexity NPath complexity Sequence coverage
File 1: DecodeFrom(...)0%80800%
File 1: InvalidDataFallback(TBase64Decoder,System.ReadOnlySpan`1<T>,System.Span`1<System.Byte>,System.Int32&,System.Int32&,System.Boolean)0%10100%
File 1: DecodeFromUtf8InPlace(...)0%48480%
File 1: DecodeWithWhiteSpaceBlockwise(...)0%30300%
File 1: DecodeWithWhiteSpaceBlockwise(...)0%30300%
File 1: GetPaddingCount(...)0%660%
File 1: GetPaddingCount(...)0%660%
File 1: DecodeWithWhiteSpaceFromUtf8InPlace(...)0%24240%
File 1: Avx512Decode(...)0%660%
File 1: Avx2Decode(...)0%660%
File 1: SimdShuffle(...)0%880%
File 1: Vector128Decode(...)0%22220%
File 1: WriteThreeLowOrderBytes(...)100%110%
File 1: IsWhiteSpace(...)0%220%
File 1: GetMaxDecodedLength(...)100%110%
File 1: IsInvalidLength(...)100%110%
File 1: IsValidPadding(...)100%110%
File 1: SrcLength(...)100%110%
File 1: TryDecode128Core(...)0%220%
File 1: TryDecode256Core(...)0%220%
File 1: TryLoadVector512(...)100%110%
File 1: TryLoadAvxVector256(...)100%110%
File 1: TryLoadVector128(...)100%110%
File 1: TryLoadArmVector128x4(...)100%110%
File 1: DecodeFourElements(...)100%110%
File 1: DecodeRemaining(...)0%660%
File 1: IndexOfAnyExceptWhiteSpace(...)0%440%
File 1: DecodeWithWhiteSpaceBlockwiseWrapper(...)100%110%
File 1: GetMaxDecodedLength(...)100%110%
File 1: IsInvalidLength(...)100%110%
File 1: IsValidPadding(...)100%110%
File 1: SrcLength(...)100%110%
File 1: TryDecode128Core(...)100%110%
File 1: TryDecode256Core(...)100%110%
File 1: TryLoadVector512(...)0%220%
File 1: TryLoadAvxVector256(...)0%220%
File 1: TryLoadVector128(...)0%220%
File 1: TryLoadArmVector128x4(...)0%220%
File 1: DecodeFourElements(...)0%220%
File 1: DecodeRemaining(...)0%880%
File 1: IndexOfAnyExceptWhiteSpace(...)0%440%
File 1: DecodeWithWhiteSpaceBlockwiseWrapper(...)100%110%
File 2: EncodeTo(...)0%40400%
File 2: Avx512Encode(...)0%440%
File 2: Avx2Encode(...)0%440%
File 2: Vector128Encode(...)0%14140%
File 2: EncodeToUtf8InPlace(...)0%10100%
File 2: Encode(...)100%110%
File 2: ConstructResult(...)100%110%
File 2: EncodeOneOptionallyPadTwo(...)100%110%
File 2: EncodeTwoOptionallyPadOne(...)100%110%
File 2: GetMaxSrcLength(...)0%440%
File 2: GetInPlaceDestinationLength(...)100%110%
File 2: GetMaxEncodedLength(...)100%110%
File 2: EncodeOneOptionallyPadTwo(...)100%110%
File 2: EncodeTwoOptionallyPadOne(...)100%110%
File 2: StoreVector512ToDestination(...)100%110%
File 2: StoreVector256ToDestination(...)100%110%
File 2: StoreVector128ToDestination(...)100%110%
File 2: StoreArmVector128x4ToDestination(...)100%110%
File 2: EncodeThreeAndWrite(...)100%110%
File 2: GetMaxSrcLength(...)100%110%
File 2: GetInPlaceDestinationLength(...)100%110%
File 2: GetMaxEncodedLength(...)100%110%
File 2: EncodeOneOptionallyPadTwo(...)100%110%
File 2: EncodeTwoOptionallyPadOne(...)100%110%
File 2: StoreVector512ToDestination(...)100%110%
File 2: StoreVector256ToDestination(...)100%110%
File 2: StoreVector128ToDestination(...)100%110%
File 2: StoreArmVector128x4ToDestination(...)100%110%
File 2: EncodeThreeAndWrite(...)100%110%
File 3: AssertRead(...)0%220%
File 3: AssertWrite(...)0%220%
File 3: AssertRead(...)0%220%
File 3: AssertWrite(...)0%220%
File 3: ThrowUnreachableException()100%110%
File 4: IsValid(...)0%28280%
File 4: .cctor()100%110%
File 4: IndexOfAnyExcept(...)100%110%
File 4: IsWhiteSpace(...)100%110%
File 4: IsEncodingPad(...)100%110%
File 4: ValidateAndDecodeLength(...)100%110%
File 4: .cctor()100%110%
File 4: IndexOfAnyExcept(...)100%110%
File 4: IsWhiteSpace(...)100%110%
File 4: IsEncodingPad(...)100%110%
File 4: ValidateAndDecodeLength(...)0%10100%

File(s)

https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/src/libraries/System.Private.CoreLib/src/System/Buffers/Text/Base64Helper/Base64DecoderHelper.cs

#LineLine coverage
 1// Licensed to the .NET Foundation under one or more agreements.
 2// The .NET Foundation licenses this file to you under the MIT license.
 3
 4using System.Diagnostics;
 5using System.Runtime.CompilerServices;
 6using System.Runtime.InteropServices;
 7using System.Text;
 8using System.Diagnostics.CodeAnalysis;
 9
 10#if NET
 11using System.Runtime.Intrinsics.Arm;
 12using System.Runtime.Intrinsics.Wasm;
 13using System.Runtime.Intrinsics.X86;
 14using System.Runtime.Intrinsics;
 15#endif
 16
 17namespace System.Buffers.Text
 18{
 19    // AVX2 version based on https://github.com/aklomp/base64/tree/e516d769a2a432c08404f1981e73b431566057be/lib/arch/avx
 20    // Vector128 version based on https://github.com/aklomp/base64/tree/e516d769a2a432c08404f1981e73b431566057be/lib/arc
 21    internal static partial class Base64Helper
 22    {
 23        internal static unsafe OperationStatus DecodeFrom<TBase64Decoder, T>(TBase64Decoder decoder, ReadOnlySpan<T> sou
 24            out int bytesConsumed, out int bytesWritten, bool isFinalBlock, bool ignoreWhiteSpace)
 25            where TBase64Decoder : IBase64Decoder<T>
 26            where T : unmanaged
 27        {
 28            if (source.IsEmpty)
 29            {
 030                bytesConsumed = 0;
 031                bytesWritten = 0;
 032                return OperationStatus.Done;
 33            }
 34
 035            fixed (T* srcBytes = &MemoryMarshal.GetReference(source))
 036            fixed (byte* destBytes = &MemoryMarshal.GetReference(bytes))
 37            {
 038                int srcLength = decoder.SrcLength(isFinalBlock, source.Length);
 039                int destLength = bytes.Length;
 040                int maxSrcLength = srcLength;
 041                int decodedLength = decoder.GetMaxDecodedLength(srcLength);
 42
 43                // max. 2 padding chars
 044                if (destLength < decodedLength - 2)
 45                {
 46                    // For overflow see comment below
 047                    maxSrcLength = destLength / 3 * 4;
 48                }
 49
 050                T* src = srcBytes;
 051                byte* dest = destBytes;
 052                T* srcEnd = srcBytes + (uint)srcLength;
 053                T* srcMax = srcBytes + (uint)maxSrcLength;
 54
 55#if NET
 056                if (maxSrcLength >= 24)
 57                {
 058                    T* end = srcMax - 88;
 059                    if (Vector512.IsHardwareAccelerated && Avx512Vbmi.IsSupported && (end >= src))
 60                    {
 061                        Avx512Decode(decoder, ref src, ref dest, end, maxSrcLength, destLength, srcBytes, destBytes);
 62
 063                        if (src == srcEnd)
 64                        {
 65                            goto DoneExit;
 66                        }
 67                    }
 68
 069                    end = srcMax - 45;
 070                    if (Avx2.IsSupported && (end >= src))
 71                    {
 072                        Avx2Decode(decoder, ref src, ref dest, end, maxSrcLength, destLength, srcBytes, destBytes);
 73
 074                        if (src == srcEnd)
 75                        {
 76                            goto DoneExit;
 77                        }
 78                    }
 79
 080                    end = srcMax - 66;
 81                    if (AdvSimd.Arm64.IsSupported && (end >= src))
 82                    {
 83                        AdvSimdDecode(decoder, ref src, ref dest, end, maxSrcLength, destLength, srcBytes, destBytes);
 84
 85                        if (src == srcEnd)
 86                        {
 87                            goto DoneExit;
 88                        }
 89                    }
 90
 091                    end = srcMax - 24;
 092                    if ((Ssse3.IsSupported || AdvSimd.Arm64.IsSupported || PackedSimd.IsSupported) && BitConverter.IsLit
 93                    {
 094                        Vector128Decode(decoder, ref src, ref dest, end, maxSrcLength, destLength, srcBytes, destBytes);
 95
 096                        if (src == srcEnd)
 97                        {
 98                            goto DoneExit;
 99                        }
 100                    }
 101                }
 102#endif
 103
 104                // Last bytes could have padding characters, so process them separately and treat them as valid only if 
 105                // if isFinalBlock is false, padding characters are considered invalid
 0106                int skipLastChunk = isFinalBlock ? 4 : 0;
 107
 0108                if (destLength >= decodedLength)
 109                {
 0110                    maxSrcLength = srcLength - skipLastChunk;
 111                }
 112                else
 113                {
 114                    // This should never overflow since destLength here is less than int.MaxValue / 4 * 3 (i.e. 16106127
 115                    // Therefore, (destLength / 3) * 4 will always be less than 2147483641
 0116                    Debug.Assert(destLength < (int.MaxValue / 4 * 3));
 117#if NET
 0118                    (maxSrcLength, int remainder) = int.DivRem(destLength, 3);
 0119                    maxSrcLength *= 4;
 120#else
 121                    maxSrcLength = (destLength / 3) * 4;
 122                    int remainder = (int)((uint)destLength % 3);
 123#endif
 0124                    if (isFinalBlock && remainder > 0)
 125                    {
 0126                        srcLength &= ~0x3; // In case of Base64UrlDecoder source can be not a multiple of 4, round down 
 127                    }
 128                }
 129
 0130                ref sbyte decodingMap = ref MemoryMarshal.GetReference(decoder.DecodingMap);
 0131                srcMax = srcBytes + maxSrcLength;
 132
 0133                while (src < srcMax)
 134                {
 0135                    int result = decoder.DecodeFourElements(src, ref decodingMap);
 136
 0137                    if (result < 0)
 138                    {
 139                        goto InvalidDataExit;
 140                    }
 141
 0142                    WriteThreeLowOrderBytes(dest, result);
 0143                    src += 4;
 0144                    dest += 3;
 145                }
 146
 0147                if (maxSrcLength != srcLength - skipLastChunk)
 148                {
 149                    goto DestinationTooSmallExit;
 150                }
 151
 0152                if (src == srcEnd)
 153                {
 0154                    if (isFinalBlock)
 155                    {
 156                        goto InvalidDataExit;
 157                    }
 158
 0159                    if (src == srcBytes + source.Length)
 160                    {
 0161                        goto DoneExit;
 162                    }
 163
 164                    goto NeedMoreDataExit;
 165                }
 166
 167                // if isFinalBlock is false, we will never reach this point
 168                // Handle remaining bytes, for Base64 its always 4 bytes, for Base64Url up to 8 bytes left.
 169                // If more than 4 bytes remained it will end up in DestinationTooSmallExit or InvalidDataExit (might suc
 0170                long remaining = srcEnd - src;
 0171                Debug.Assert(typeof(TBase64Decoder) == typeof(Base64DecoderByte) ? remaining == 4 : remaining < 8);
 0172                int i0 = decoder.DecodeRemaining(srcEnd, ref decodingMap, remaining, out uint t2, out uint t3);
 173
 0174                if (i0 < 0)
 175                {
 176                    goto InvalidDataExit;
 177                }
 178
 0179                byte* destMax = destBytes + (uint)destLength;
 180
 0181                if (!decoder.IsValidPadding(t3))
 182                {
 0183                    int i2 = Unsafe.Add(ref decodingMap, (IntPtr)t2);
 0184                    int i3 = Unsafe.Add(ref decodingMap, (IntPtr)t3);
 185
 0186                    i2 <<= 6;
 187
 0188                    i0 |= i3;
 0189                    i0 |= i2;
 190
 0191                    if (i0 < 0)
 192                    {
 193                        goto InvalidDataExit;
 194                    }
 0195                    if (dest + 3 > destMax)
 196                    {
 197                        goto DestinationTooSmallExit;
 198                    }
 199
 0200                    WriteThreeLowOrderBytes(dest, i0);
 0201                    dest += 3;
 0202                    src += 4;
 203                }
 0204                else if (!decoder.IsValidPadding(t2))
 205                {
 0206                    int i2 = Unsafe.Add(ref decodingMap, (IntPtr)t2);
 207
 0208                    i2 <<= 6;
 209
 0210                    i0 |= i2;
 211
 0212                    if ((i0 & 0x800000c0) != 0) // if negative or 2 unused bits are not 0.
 213                    {
 214                        goto InvalidDataExit;
 215                    }
 0216                    if (dest + 2 > destMax)
 217                    {
 218                        goto DestinationTooSmallExit;
 219                    }
 220
 0221                    dest[0] = (byte)(i0 >> 16);
 0222                    dest[1] = (byte)(i0 >> 8);
 0223                    dest += 2;
 0224                    src += remaining;
 225                }
 226                else
 227                {
 0228                    if ((i0 & 0x8000F000) != 0) // if negative or 4 unused bits are not 0.
 229                    {
 230                        goto InvalidDataExit;
 231                    }
 0232                    if (dest + 1 > destMax)
 233                    {
 234                        goto DestinationTooSmallExit;
 235                    }
 236
 0237                    dest[0] = (byte)(i0 >> 16);
 0238                    dest += 1;
 0239                    src += remaining;
 240                }
 241
 0242                if (srcLength != source.Length)
 243                {
 244                    goto InvalidDataExit;
 245                }
 246
 247            DoneExit:
 0248                bytesConsumed = (int)(src - srcBytes);
 0249                bytesWritten = (int)(dest - destBytes);
 0250                return OperationStatus.Done;
 251
 252            DestinationTooSmallExit:
 0253                if (srcLength != source.Length && isFinalBlock)
 254                {
 255                    goto InvalidDataExit; // if input is not a multiple of 4, and there is no more data, return invalid 
 256                }
 257
 0258                if (ignoreWhiteSpace)
 259                {
 260                    // Fall through to InvalidDataFallback which strips whitespace and re-evaluates destination size req
 261                    goto InvalidDataExit;
 262                }
 263
 0264                bytesConsumed = (int)(src - srcBytes);
 0265                bytesWritten = (int)(dest - destBytes);
 0266                return OperationStatus.DestinationTooSmall;
 267
 268            NeedMoreDataExit:
 0269                bytesConsumed = (int)(src - srcBytes);
 0270                bytesWritten = (int)(dest - destBytes);
 0271                return OperationStatus.NeedMoreData;
 272
 273            InvalidDataExit:
 0274                bytesConsumed = (int)(src - srcBytes);
 0275                bytesWritten = (int)(dest - destBytes);
 0276                return ignoreWhiteSpace ?
 0277                    InvalidDataFallback(decoder, source, bytes, ref bytesConsumed, ref bytesWritten, isFinalBlock) :
 0278                    OperationStatus.InvalidData;
 279            }
 280
 281            static OperationStatus InvalidDataFallback(TBase64Decoder decoder, ReadOnlySpan<T> source, Span<byte> bytes,
 282            {
 0283                source = source.Slice(bytesConsumed);
 0284                bytes = bytes.Slice(bytesWritten);
 285
 286                OperationStatus status;
 287                do
 288                {
 0289                    int localConsumed = decoder.IndexOfAnyExceptWhiteSpace(source);
 0290                    if (localConsumed < 0)
 291                    {
 292                        // The remainder of the input is all whitespace. Mark it all as having been consumed,
 293                        // and mark the operation as being done.
 0294                        bytesConsumed += source.Length;
 0295                        status = OperationStatus.Done;
 0296                        break;
 297                    }
 298
 0299                    if (localConsumed == 0)
 300                    {
 301                        // Non-whitespace was found at the beginning of the input. Since it wasn't consumed
 302                        // by the previous call to DecodeFromUtf8, it must be part of a Base64 sequence
 303                        // that was interrupted by whitespace or something else considered invalid.
 304                        // Fall back to block-wise decoding. This is very slow, but it's also very non-standard
 305                        // formatting of the input; whitespace is typically only found between blocks, such as
 306                        // when Convert.ToBase64String inserts a line break every 76 output characters.
 0307                        return decoder.DecodeWithWhiteSpaceBlockwiseWrapper(decoder, source, bytes, ref bytesConsumed, r
 308                    }
 309
 310                    // Skip over the starting whitespace and continue.
 0311                    bytesConsumed += localConsumed;
 0312                    source = source.Slice(localConsumed);
 313
 314                    // Try again after consumed whitespace
 0315                    status = DecodeFrom(decoder, source, bytes, out localConsumed, out int localWritten, isFinalBlock, i
 0316                    bytesConsumed += localConsumed;
 0317                    bytesWritten += localWritten;
 318
 0319                    if (status is OperationStatus.Done or OperationStatus.NeedMoreData)
 320                    {
 321                        break;
 322                    }
 323
 324                    // The DecodeFrom helper will return DestinationTooSmall if the destination is too small,
 325                    // regardless of whether it's actually too small once you skip whitespace characters.
 326                    // In that case we loop again and fall back to block-wise decoding if we can't make progress.
 327
 0328                    source = source.Slice(localConsumed);
 0329                    bytes = bytes.Slice(localWritten);
 330                }
 0331                while (!source.IsEmpty);
 332
 0333                return status;
 334            }
 335        }
 336
 337        internal static unsafe OperationStatus DecodeFromUtf8InPlace<TBase64Decoder>(TBase64Decoder decoder, Span<byte> 
 338            where TBase64Decoder : IBase64Decoder<byte>
 339        {
 340            if (buffer.IsEmpty)
 341            {
 0342                bytesWritten = 0;
 0343                return OperationStatus.Done;
 344            }
 345
 0346            fixed (byte* bufferBytes = &MemoryMarshal.GetReference(buffer))
 347            {
 0348                uint bufferLength = (uint)buffer.Length;
 0349                uint sourceIndex = 0;
 0350                uint destIndex = 0;
 351
 0352                if (decoder.IsInvalidLength(buffer.Length))
 353                {
 354                    goto InvalidExit;
 355                }
 356
 0357                ref sbyte decodingMap = ref MemoryMarshal.GetReference(decoder.DecodingMap);
 358
 359#if NET
 360                // Decode in place using the same vectorized helpers as DecodeFrom. This is safe because the
 361                // write cursor (dest) always trails the read cursor (src) by 25%, so each vector store -- including
 362                // its zero-padded overshoot -- ends at or before the next vector load and never clobbers source
 363                // that hasn't been read yet.
 0364                if (bufferLength >= 24)
 365                {
 0366                    byte* src = bufferBytes;
 0367                    byte* dest = bufferBytes;
 0368                    int length = (int)bufferLength;
 0369                    byte* srcMax = bufferBytes + length;
 370
 0371                    byte* end = srcMax - 88;
 0372                    if (Vector512.IsHardwareAccelerated && Avx512Vbmi.IsSupported && (end >= src))
 373                    {
 0374                        Avx512Decode(decoder, ref src, ref dest, end, length, length, bufferBytes, bufferBytes);
 375                    }
 376
 0377                    end = srcMax - 45;
 0378                    if (Avx2.IsSupported && (end >= src))
 379                    {
 0380                        Avx2Decode(decoder, ref src, ref dest, end, length, length, bufferBytes, bufferBytes);
 381                    }
 382
 0383                    end = srcMax - 66;
 384                    if (AdvSimd.Arm64.IsSupported && (end >= src))
 385                    {
 386                        AdvSimdDecode(decoder, ref src, ref dest, end, length, length, bufferBytes, bufferBytes);
 387                    }
 388
 0389                    end = srcMax - 24;
 0390                    if ((Ssse3.IsSupported || AdvSimd.Arm64.IsSupported || PackedSimd.IsSupported) && BitConverter.IsLit
 391                    {
 0392                        Vector128Decode(decoder, ref src, ref dest, end, length, length, bufferBytes, bufferBytes);
 393                    }
 394
 0395                    sourceIndex = (uint)(src - bufferBytes);
 0396                    destIndex = (uint)(dest - bufferBytes);
 397                }
 398#endif
 399
 0400                if (bufferLength > 4)
 401                {
 0402                    while (sourceIndex < bufferLength - 4)
 403                    {
 0404                        int result = decoder.DecodeFourElements(bufferBytes + sourceIndex, ref decodingMap);
 0405                        if (result < 0)
 406                        {
 407                            goto InvalidExit;
 408                        }
 409
 0410                        WriteThreeLowOrderBytes(bufferBytes + destIndex, result);
 0411                        destIndex += 3;
 0412                        sourceIndex += 4;
 413                    }
 414                }
 415
 416                uint t0;
 417                uint t1;
 418                uint t2;
 419                uint t3;
 420
 0421                switch (bufferLength - sourceIndex)
 422                {
 423                    case 2:
 0424                        t0 = bufferBytes[bufferLength - 2];
 0425                        t1 = bufferBytes[bufferLength - 1];
 0426                        t2 = EncodingPad;
 0427                        t3 = EncodingPad;
 0428                        break;
 429                    case 3:
 0430                        t0 = bufferBytes[bufferLength - 3];
 0431                        t1 = bufferBytes[bufferLength - 2];
 0432                        t2 = bufferBytes[bufferLength - 1];
 0433                        t3 = EncodingPad;
 0434                        break;
 435                    case 4:
 0436                        t0 = bufferBytes[bufferLength - 4];
 0437                        t1 = bufferBytes[bufferLength - 3];
 0438                        t2 = bufferBytes[bufferLength - 2];
 0439                        t3 = bufferBytes[bufferLength - 1];
 440                        break;
 441                    default:
 442                        goto InvalidExit;
 443                }
 444
 0445                int i0 = Unsafe.Add(ref decodingMap, (int)t0);
 0446                int i1 = Unsafe.Add(ref decodingMap, (int)t1);
 447
 0448                i0 <<= 18;
 0449                i1 <<= 12;
 450
 0451                i0 |= i1;
 452
 0453                if (!decoder.IsValidPadding(t3))
 454                {
 0455                    int i2 = Unsafe.Add(ref decodingMap, (int)t2);
 0456                    int i3 = Unsafe.Add(ref decodingMap, (int)t3);
 457
 0458                    i2 <<= 6;
 459
 0460                    i0 |= i3;
 0461                    i0 |= i2;
 462
 0463                    if (i0 < 0)
 464                    {
 465                        goto InvalidExit;
 466                    }
 467
 0468                    WriteThreeLowOrderBytes(bufferBytes + destIndex, i0);
 0469                    destIndex += 3;
 470                }
 0471                else if (!decoder.IsValidPadding(t2))
 472                {
 0473                    int i2 = Unsafe.Add(ref decodingMap, (int)t2);
 474
 0475                    i2 <<= 6;
 476
 0477                    i0 |= i2;
 478
 0479                    if ((i0 & 0x800000c0) != 0) // if negative or 2 unused bits are not 0.
 480                    {
 481                        goto InvalidExit;
 482                    }
 483
 0484                    bufferBytes[destIndex] = (byte)(i0 >> 16);
 0485                    bufferBytes[destIndex + 1] = (byte)(i0 >> 8);
 0486                    destIndex += 2;
 487                }
 488                else
 489                {
 0490                    if ((i0 & 0x8000F000) != 0) // if negative or 4 unused bits are not 0.
 491                    {
 492                        goto InvalidExit;
 493                    }
 494
 0495                    bufferBytes[destIndex] = (byte)(i0 >> 16);
 0496                    destIndex += 1;
 497                }
 498
 0499                bytesWritten = (int)destIndex;
 0500                return OperationStatus.Done;
 501
 502            InvalidExit:
 0503                bytesWritten = (int)destIndex;
 0504                return ignoreWhiteSpace ?
 0505                    DecodeWithWhiteSpaceFromUtf8InPlace<TBase64Decoder>(decoder, buffer, ref bytesWritten, sourceIndex) 
 0506                    OperationStatus.InvalidData;
 507            }
 508        }
 509
 510        internal static unsafe OperationStatus DecodeWithWhiteSpaceBlockwise<TBase64Decoder>(TBase64Decoder decoder, Rea
 511            where TBase64Decoder : IBase64Decoder<byte>
 512        {
 513            const int BlockSize = 4;
 0514            Span<byte> buffer = stackalloc byte[BlockSize];
 0515            OperationStatus status = OperationStatus.Done;
 516
 0517            while (!source.IsEmpty)
 518            {
 519                // Skip over any leading whitespace
 0520                if (IsWhiteSpace(source[0]))
 521                {
 0522                    source = source.Slice(1);
 0523                    bytesConsumed++;
 0524                    continue;
 525                }
 526
 0527                int encodedIdx = 0;
 0528                int bufferIdx = 0;
 0529                int skipped = 0;
 530
 0531                for (; encodedIdx < source.Length && (uint)bufferIdx < (uint)buffer.Length; ++encodedIdx)
 532                {
 0533                    if (IsWhiteSpace(source[encodedIdx]))
 534                    {
 0535                        skipped++;
 536                    }
 537                    else
 538                    {
 0539                        buffer[bufferIdx] = source[encodedIdx];
 0540                        bufferIdx++;
 541                    }
 542                }
 543
 0544                source = source.Slice(encodedIdx);
 0545                Debug.Assert(bufferIdx > 0);
 546
 547                bool hasAnotherBlock;
 548
 0549                if (typeof(TBase64Decoder) == typeof(Base64DecoderByte))
 550                {
 0551                    hasAnotherBlock = source.Length >= BlockSize;
 552                }
 553                else
 554                {
 0555                    hasAnotherBlock = source.Length > 1;
 556                }
 557
 0558                bool localIsFinalBlock = !hasAnotherBlock;
 559
 560                // If this block contains padding and there's another block, then only whitespace may follow for being v
 0561                if (hasAnotherBlock)
 562                {
 0563                    int paddingCount = GetPaddingCount(decoder, ref buffer[BlockSize - 1]);
 0564                    if (paddingCount > 0)
 565                    {
 0566                        hasAnotherBlock = false;
 0567                        localIsFinalBlock = true;
 568                    }
 569                }
 570
 0571                if (localIsFinalBlock && !isFinalBlock)
 572                {
 0573                    localIsFinalBlock = false;
 574                }
 575
 0576                status = DecodeFrom<TBase64Decoder, byte>(decoder, buffer.Slice(0, bufferIdx), bytes, out int localConsu
 577
 0578                if (status != OperationStatus.Done)
 579                {
 0580                    Debug.Assert(localConsumed == 0 && localWritten == 0, "On failure, should not have consumed or writt
 0581                    return status;
 582                }
 583
 0584                bytesConsumed += skipped;
 0585                bytesConsumed += localConsumed;
 0586                bytesWritten += localWritten;
 587
 588                // The remaining data must all be whitespace in order to be valid.
 0589                if (!hasAnotherBlock)
 590                {
 0591                    for (int i = 0; i < source.Length; ++i)
 592                    {
 0593                        if (!IsWhiteSpace(source[i]))
 594                        {
 595                            // Revert previous dest increment, since an invalid state followed.
 0596                            bytesConsumed -= localConsumed;
 0597                            bytesWritten -= localWritten;
 598
 0599                            return OperationStatus.InvalidData;
 600                        }
 601
 0602                        bytesConsumed++;
 603                    }
 604
 0605                    break;
 606                }
 607
 0608                bytes = bytes.Slice(localWritten);
 0609                Debug.Assert(!source.IsEmpty);
 610            }
 611
 0612            return status;
 613        }
 614
 615        internal static unsafe OperationStatus DecodeWithWhiteSpaceBlockwise<TBase64Decoder>(TBase64Decoder decoder, Rea
 616            where TBase64Decoder : IBase64Decoder<ushort>
 617        {
 618            const int BlockSize = 4;
 0619            Span<ushort> buffer = stackalloc ushort[BlockSize];
 0620            OperationStatus status = OperationStatus.Done;
 621
 0622            while (!source.IsEmpty)
 623            {
 624                // Skip over any leading whitespace
 0625                if (IsWhiteSpace(source[0]))
 626                {
 0627                    source = source.Slice(1);
 0628                    bytesConsumed++;
 0629                    continue;
 630                }
 631
 0632                int encodedIdx = 0;
 0633                int bufferIdx = 0;
 0634                int skipped = 0;
 635
 0636                for (; encodedIdx < source.Length && (uint)bufferIdx < (uint)buffer.Length; ++encodedIdx)
 637                {
 0638                    if (IsWhiteSpace(source[encodedIdx]))
 639                    {
 0640                        skipped++;
 641                    }
 642                    else
 643                    {
 0644                        buffer[bufferIdx] = source[encodedIdx];
 0645                        bufferIdx++;
 646                    }
 647                }
 648
 0649                source = source.Slice(encodedIdx);
 0650                Debug.Assert(bufferIdx > 0);
 651
 652                bool hasAnotherBlock;
 653
 0654                if (decoder is Base64DecoderChar)
 655                {
 0656                    hasAnotherBlock = source.Length >= BlockSize;
 657                }
 658                else
 659                {
 0660                    hasAnotherBlock = source.Length > 1;
 661                }
 662
 0663                bool localIsFinalBlock = !hasAnotherBlock;
 664
 665                // If this block contains padding and there's another block, then only whitespace may follow for being v
 0666                if (hasAnotherBlock)
 667                {
 0668                    int paddingCount = GetPaddingCount(decoder, ref buffer[BlockSize - 1]);
 0669                    if (paddingCount > 0)
 670                    {
 0671                        hasAnotherBlock = false;
 0672                        localIsFinalBlock = true;
 673                    }
 674                }
 675
 0676                if (localIsFinalBlock && !isFinalBlock)
 677                {
 0678                    localIsFinalBlock = false;
 679                }
 680
 0681                status = DecodeFrom(decoder, buffer.Slice(0, bufferIdx), bytes, out int localConsumed, out int localWrit
 682
 0683                if (status != OperationStatus.Done)
 684                {
 0685                    Debug.Assert(localConsumed == 0 && localWritten == 0, "On failure, should not have consumed or writt
 0686                    return status;
 687                }
 688
 0689                bytesConsumed += skipped;
 0690                bytesConsumed += localConsumed;
 0691                bytesWritten += localWritten;
 692
 693                // The remaining data must all be whitespace in order to be valid.
 0694                if (!hasAnotherBlock)
 695                {
 0696                    for (int i = 0; i < source.Length; ++i)
 697                    {
 0698                        if (!IsWhiteSpace(source[i]))
 699                        {
 700                            // Revert previous dest increment, since an invalid state followed.
 0701                            bytesConsumed -= localConsumed;
 0702                            bytesWritten -= localWritten;
 703
 0704                            return OperationStatus.InvalidData;
 705                        }
 706                    }
 707
 0708                    bytesConsumed += source.Length;
 0709                    break;
 710                }
 711
 0712                bytes = bytes.Slice(localWritten);
 0713                Debug.Assert(!source.IsEmpty);
 714            }
 715
 0716            return status;
 717        }
 718
 719        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 720        private static int GetPaddingCount<TBase64Decoder>(TBase64Decoder decoder, ref byte ptrToLastElement)
 721            where TBase64Decoder : IBase64Decoder<byte>
 722        {
 0723            int padding = 0;
 724
 0725            if (decoder.IsValidPadding(ptrToLastElement))
 726            {
 0727                padding++;
 728            }
 729
 0730            if (decoder.IsValidPadding(Unsafe.Subtract(ref ptrToLastElement, 1)))
 731            {
 0732                padding++;
 733            }
 734
 0735            return padding;
 736        }
 737
 738        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 739        private static int GetPaddingCount<TBase64Decoder>(TBase64Decoder decoder, ref ushort ptrToLastElement)
 740            where TBase64Decoder : IBase64Decoder<ushort>
 741        {
 0742            int padding = 0;
 743
 0744            if (decoder.IsValidPadding(ptrToLastElement))
 745            {
 0746                padding++;
 747            }
 748
 0749            if (decoder.IsValidPadding(Unsafe.Subtract(ref ptrToLastElement, 1)))
 750            {
 0751                padding++;
 752            }
 753
 0754            return padding;
 755        }
 756
 757        private static unsafe OperationStatus DecodeWithWhiteSpaceFromUtf8InPlace<TBase64Decoder>(TBase64Decoder decoder
 758            where TBase64Decoder : IBase64Decoder<byte>
 759        {
 0760            int BlockSize = Math.Min(source.Length - (int)sourceIndex, 4);
 0761            Span<byte> buffer = stackalloc byte[BlockSize];
 762
 0763            OperationStatus status = OperationStatus.Done;
 0764            int localDestIndex = destIndex;
 0765            bool hasPaddingBeenProcessed = false;
 0766            int localBytesWritten = 0;
 767
 0768            while (sourceIndex < (uint)source.Length)
 769            {
 0770                int bufferIdx = 0;
 771
 0772                while (bufferIdx < BlockSize && sourceIndex < (uint)source.Length)
 773                {
 0774                    if (!IsWhiteSpace(source[(int)sourceIndex]))
 775                    {
 0776                        buffer[bufferIdx] = source[(int)sourceIndex];
 0777                        bufferIdx++;
 778                    }
 779
 0780                    sourceIndex++;
 781                }
 782
 0783                if (bufferIdx == 0)
 784                {
 785                    continue;
 786                }
 787
 0788                if (bufferIdx != 4)
 789                {
 790                    // Base64 require 4 bytes, for Base64Url it can be less than 4 bytes but not 1 byte.
 0791                    if (decoder is Base64DecoderByte || bufferIdx == 1)
 792                    {
 0793                        status = OperationStatus.InvalidData;
 0794                        break;
 795                    }
 796                    else // For Base64Url fill empty slots in last block with padding
 797                    {
 0798                        while (bufferIdx < BlockSize)  // Can happen only for last block
 799                        {
 0800                            Debug.Assert(source.Length == sourceIndex);
 0801                            buffer[bufferIdx++] = (byte)EncodingPad;
 802                        }
 803                    }
 804                }
 805
 0806                if (hasPaddingBeenProcessed)
 807                {
 808                    // Padding has already been processed, a new valid block cannot be processed.
 809                    // Revert previous dest increment, since an invalid state followed.
 0810                    localDestIndex -= localBytesWritten;
 0811                    status = OperationStatus.InvalidData;
 0812                    break;
 813                }
 814
 0815                status = DecodeFromUtf8InPlace<TBase64Decoder>(decoder, buffer, out localBytesWritten, ignoreWhiteSpace:
 0816                localDestIndex += localBytesWritten;
 0817                hasPaddingBeenProcessed = localBytesWritten < 3;
 818
 0819                if (status != OperationStatus.Done)
 820                {
 821                    break;
 822                }
 823
 824                // Write result to source span in place.
 0825                for (int i = 0; i < localBytesWritten; i++)
 826                {
 0827                    source[localDestIndex - localBytesWritten + i] = buffer[i];
 828                }
 829            }
 830
 0831            destIndex = localDestIndex;
 0832            return status;
 833        }
 834
 835#if NET
 836        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 837        [CompExactlyDependsOn(typeof(Avx512BW))]
 838        [CompExactlyDependsOn(typeof(Avx512Vbmi))]
 839        private static unsafe void Avx512Decode<TBase64Decoder, T>(TBase64Decoder decoder, ref T* srcBytes, ref byte* de
 840            where TBase64Decoder : IBase64Decoder<T>
 841            where T : unmanaged
 842        {
 843            // Reference for VBMI implementation : https://github.com/WojciechMula/base64simd/tree/master/decode
 844            // If we have AVX512 support, pick off 64 bytes at a time for as long as we can,
 845            // but make sure that we quit before seeing any == markers at the end of the
 846            // string. Also, because we write 16 zeroes at the end of the output, ensure
 847            // that there are at least 22 valid bytes of input data remaining to close the
 848            // gap. 64 + 2 + 22 = 88 bytes.
 0849            T* src = srcBytes;
 0850            byte* dest = destBytes;
 851
 852            // The JIT won't hoist these "constants", so help it
 0853            Vector512<sbyte> vbmiLookup0 = Vector512.Create(decoder.VbmiLookup0).AsSByte();
 0854            Vector512<sbyte> vbmiLookup1 = Vector512.Create(decoder.VbmiLookup1).AsSByte();
 0855            Vector512<byte> vbmiPackedLanesControl = Vector512.Create(
 0856                0x06000102, 0x090a0405, 0x0c0d0e08, 0x16101112,
 0857                0x191a1415, 0x1c1d1e18, 0x26202122, 0x292a2425,
 0858                0x2c2d2e28, 0x36303132, 0x393a3435, 0x3c3d3e38,
 0859                0x00000000, 0x00000000, 0x00000000, 0x00000000).AsByte();
 860
 0861            Vector512<sbyte> mergeConstant0 = Vector512.Create(0x01400140).AsSByte();
 0862            Vector512<short> mergeConstant1 = Vector512.Create(0x00011000).AsInt16();
 863
 864            // This algorithm requires AVX512VBMI support.
 865            // Vbmi was first introduced in CannonLake and is available from IceLake on.
 866            do
 867            {
 0868                if (!decoder.TryLoadVector512(src, srcStart, sourceLength, out Vector512<sbyte> str))
 869                {
 870                    break;
 871                }
 872
 873                // Step 1: Translate encoded Base64 input to their original indices
 874                // This step also checks for invalid inputs and exits.
 875                // After this, we have indices which are verified to have upper 2 bits set to 0 in each byte.
 876                // origIndex      = [...|00dddddd|00cccccc|00bbbbbb|00aaaaaa]
 0877                Vector512<sbyte> origIndex = Avx512Vbmi.PermuteVar64x8x2(vbmiLookup0, str, vbmiLookup1);
 0878                Vector512<sbyte> errorVec = (origIndex.AsInt32() | str.AsInt32()).AsSByte();
 0879                if (errorVec.ExtractMostSignificantBits() != 0)
 880                {
 881                    break;
 882                }
 883
 884                // Step 2: Now we need to reshuffle bits to remove the 0 bits.
 885                // multiAdd1: [...|0000cccc|ccdddddd|0000aaaa|aabbbbbb]
 0886                Vector512<short> multiAdd1 = Avx512BW.MultiplyAddAdjacent(origIndex.AsByte(), mergeConstant0);
 887                // multiAdd1: [...|00000000|aaaaaabb|bbbbcccc|ccdddddd]
 0888                Vector512<int> multiAdd2 = Avx512BW.MultiplyAddAdjacent(multiAdd1, mergeConstant1);
 889
 890                // Step 3: Pack 48 bytes
 0891                str = Avx512Vbmi.PermuteVar64x8(multiAdd2.AsByte(), vbmiPackedLanesControl).AsSByte();
 892
 0893                AssertWrite<Vector512<sbyte>>(dest, destStart, destLength);
 0894                str.Store((sbyte*)dest);
 0895                src += 64;
 0896                dest += 48;
 897            }
 0898            while (src <= srcEnd);
 899
 0900            srcBytes = src;
 0901            destBytes = dest;
 0902        }
 903
 904        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 905        [CompExactlyDependsOn(typeof(Avx2))]
 906        private static unsafe void Avx2Decode<TBase64Decoder, T>(TBase64Decoder decoder, ref T* srcBytes, ref byte* dest
 907            where TBase64Decoder : IBase64Decoder<T>
 908            where T : unmanaged
 909        {
 910            // If we have AVX2 support, pick off 32 bytes at a time for as long as we can,
 911            // but make sure that we quit before seeing any == markers at the end of the
 912            // string. Also, because we write 8 zeroes at the end of the output, ensure
 913            // that there are at least 11 valid bytes of input data remaining to close the
 914            // gap. 32 + 2 + 11 = 45 bytes.
 915
 916            // See SSSE3-version below for an explanation of how the code works.
 917
 918            // The JIT won't hoist these "constants", so help it
 0919            Vector256<sbyte> lutHi = Vector256.Create(decoder.Avx2LutHigh);
 920
 0921            Vector256<sbyte> lutLo = Vector256.Create(decoder.Avx2LutLow);
 922
 0923            Vector256<sbyte> lutShift = Vector256.Create(decoder.Avx2LutShift);
 924
 0925            Vector256<sbyte> packBytesInLaneMask = Vector256.Create(
 0926                2, 1, 0, 6,
 0927                5, 4, 10, 9,
 0928                8, 14, 13, 12,
 0929                -1, -1, -1, -1,
 0930                2, 1, 0, 6,
 0931                5, 4, 10, 9,
 0932                8, 14, 13, 12,
 0933                -1, -1, -1, -1);
 934
 0935            Vector256<int> packLanesControl = Vector256.Create(
 0936                 0, 0, 0, 0,
 0937                1, 0, 0, 0,
 0938                2, 0, 0, 0,
 0939                4, 0, 0, 0,
 0940                5, 0, 0, 0,
 0941                6, 0, 0, 0,
 0942                -1, -1, -1, -1,
 0943                -1, -1, -1, -1).AsInt32();
 944
 0945            Vector256<sbyte> maskSlashOrUnderscore = Vector256.Create((sbyte)decoder.MaskSlashOrUnderscore);
 0946            Vector256<sbyte> shiftForUnderscore = Vector256.Create((sbyte)33);
 0947            Vector256<sbyte> mergeConstant0 = Vector256.Create(0x01400140).AsSByte();
 0948            Vector256<short> mergeConstant1 = Vector256.Create(0x00011000).AsInt16();
 949
 0950            T* src = srcBytes;
 0951            byte* dest = destBytes;
 952
 953            //while (remaining >= 45)
 954            do
 955            {
 0956                if (!decoder.TryLoadAvxVector256(src, srcStart, sourceLength, out Vector256<sbyte> str))
 957                {
 958                    break;
 959                }
 960
 0961                Vector256<sbyte> hiNibbles = ((str.AsInt32()) >>> 4).AsSByte() & maskSlashOrUnderscore;
 962
 0963                if (!decoder.TryDecode256Core(str, hiNibbles, maskSlashOrUnderscore, lutLo, lutHi, lutShift, shiftForUnd
 964                {
 965                    break;
 966                }
 967
 968                // in, lower lane, bits, upper case are most significant bits, lower case are least significant bits:
 969                // 00llllll 00kkkkLL 00jjKKKK 00JJJJJJ
 970                // 00iiiiii 00hhhhII 00ggHHHH 00GGGGGG
 971                // 00ffffff 00eeeeFF 00ddEEEE 00DDDDDD
 972                // 00cccccc 00bbbbCC 00aaBBBB 00AAAAAA
 973
 0974                Vector256<short> merge_ab_and_bc = Avx2.MultiplyAddAdjacent(str.AsByte(), mergeConstant0);
 975                // 0000kkkk LLllllll 0000JJJJ JJjjKKKK
 976                // 0000hhhh IIiiiiii 0000GGGG GGggHHHH
 977                // 0000eeee FFffffff 0000DDDD DDddEEEE
 978                // 0000bbbb CCcccccc 0000AAAA AAaaBBBB
 979
 0980                Vector256<int> output = Avx2.MultiplyAddAdjacent(merge_ab_and_bc, mergeConstant1);
 981                // 00000000 JJJJJJjj KKKKkkkk LLllllll
 982                // 00000000 GGGGGGgg HHHHhhhh IIiiiiii
 983                // 00000000 DDDDDDdd EEEEeeee FFffffff
 984                // 00000000 AAAAAAaa BBBBbbbb CCcccccc
 985
 986                // Pack bytes together in each lane:
 0987                output = Avx2.Shuffle(output.AsSByte(), packBytesInLaneMask).AsInt32();
 988                // 00000000 00000000 00000000 00000000
 989                // LLllllll KKKKkkkk JJJJJJjj IIiiiiii
 990                // HHHHhhhh GGGGGGgg FFffffff EEEEeeee
 991                // DDDDDDdd CCcccccc BBBBbbbb AAAAAAaa
 992
 993                // Pack lanes
 0994                str = Avx2.PermuteVar8x32(output, packLanesControl).AsSByte();
 995
 0996                AssertWrite<Vector256<sbyte>>(dest, destStart, destLength);
 0997                Avx.Store(dest, str.AsByte());
 998
 0999                src += 32;
 01000                dest += 24;
 1001            }
 01002            while (src <= srcEnd);
 1003
 01004            srcBytes = src;
 01005            destBytes = dest;
 01006        }
 1007
 1008        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1009        [CompExactlyDependsOn(typeof(Ssse3))]
 1010        [CompExactlyDependsOn(typeof(AdvSimd.Arm64))]
 1011        [CompExactlyDependsOn(typeof(PackedSimd))]
 1012        internal static Vector128<byte> SimdShuffle(Vector128<byte> left, Vector128<byte> right, Vector128<byte> mask8F)
 1013        {
 1014            Debug.Assert((Ssse3.IsSupported || AdvSimd.Arm64.IsSupported || PackedSimd.IsSupported) && BitConverter.IsLi
 1015
 01016            if (Ssse3.IsSupported)
 1017            {
 01018                return Ssse3.Shuffle(left, right);
 1019            }
 1020            else if (PackedSimd.IsSupported)
 1021            {
 1022                return PackedSimd.Swizzle(left, right & mask8F);
 1023            }
 1024            else
 1025            {
 01026                return AdvSimd.Arm64.VectorTableLookup(left, right & mask8F);
 1027            }
 1028        }
 1029
 1030        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1031        [CompExactlyDependsOn(typeof(AdvSimd.Arm64))]
 1032        private static unsafe void AdvSimdDecode<TBase64Decoder, T>(TBase64Decoder decoder, ref T* srcBytes, ref byte* d
 1033            where TBase64Decoder : IBase64Decoder<T>
 1034            where T : unmanaged
 1035        {
 1036            // C# implementation of https://github.com/aklomp/base64/blob/3a5add8652076612a8407627a42c768736a4263f/lib/a
 1037            // If we have AdvSimd support, pick off 64 bytes at a time for as long as we can,
 1038            // but make sure that we quit before seeing any == markers at the end of the
 1039            // string. 64 + 2 = 66 bytes.
 1040
 1041            // In the decoding process, we want to map each byte, representing a Base64 value, to its 6-bit (0-63) repre
 1042            // It uses the following mapping. Values outside the following groups are invalid and, we abort decoding whe
 1043            //
 1044            // #    From       To         Char
 1045            // 1    [43]       [62]       +
 1046            // 2    [47]       [63]       /
 1047            // 3    [48..57]   [52..61]   0..9
 1048            // 4    [65..90]   [0..25]    A..Z
 1049            // 5    [97..122]  [26..51]   a..z
 1050            //
 1051            // To map an input value to its Base64 representation, we use look-up tables 'decLutOne' and 'decLutTwo'.
 1052            // 'decLutOne' helps to map groups 1, 2 and 3 while 'decLutTwo' maps groups 4 and 5 in the above list.
 1053            // After mapping, each value falls between 0-63. Consequently, the last six bits of each byte now hold a val
 1054            // We then compress four such bytes (with valid 4 * 6 = 24 bits) to three UTF8 bytes (3 * 8 = 24 bits).
 1055            // For faster decoding, we use SIMD operations that allow the processing of multiple bytes together.
 1056            // However, the compress operation on adjacent values of a vector could be slower. Thus, we de-interleave wh
 1057            // the input bytes that store adjacent bytes in separate vectors. This later simplifies the compress step wi
 1058            // of logical operations. This requires interleaving while storing the decoded result.
 1059
 1060            // Values in 'decLutOne' maps input values from 0 to 63.
 1061            //   255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255
 1062            //   255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255
 1063            //   255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,  62, 255, 255, 255,  63
 1064            //    52,  53,  54,  55,  56,  57,  58,  59,  60,  61, 255, 255, 255, 255, 255, 255
 1065            var decLutOne = (Vector128<byte>.AllBitsSet,
 1066                             Vector128<byte>.AllBitsSet,
 1067                             Vector128.Create(decoder.AdvSimdLutOne3).AsByte(),
 1068                             Vector128.Create(0x37363534, 0x3B3A3938, 0xFFFF3D3C, 0xFFFFFFFF).AsByte());
 1069
 1070            // Values in 'decLutTwo' maps input values from 63 to 127.
 1071            //    0, 255,   0,   1,   2,   3,   4,   5,   6,   7,   8,   9,  10,  11,  12,  13
 1072            //   14,  15,  16,  17,  18,  19,  20,  21,  22,  23,  24,  25, 255, 255, 255, 255
 1073            //  255, 255,  26,  27,  28,  29,  30,  31,  32,  33,  34,  35,  36,  37,  38,  39
 1074            //   40,  41,  42,  43,  44,  45,  46,  47,  48,  49,  50,  51, 255, 255, 255, 255
 1075            var decLutTwo = (Vector128.Create(0x0100FF00, 0x05040302, 0x09080706, 0x0D0C0B0A).AsByte(),
 1076                             Vector128.Create(0x11100F0E, 0x15141312, 0x19181716, 0xFFFFFFFF).AsByte(),
 1077                             Vector128.Create(decoder.AdvSimdLutTwo3Uint1, 0x1F1E1D1C, 0x23222120, 0x27262524).AsByte(),
 1078                             Vector128.Create(0x2B2A2928, 0x2F2E2D2C, 0x33323130, 0xFFFFFFFF).AsByte());
 1079
 1080            T* src = srcBytes;
 1081            byte* dest = destBytes;
 1082            Vector128<byte> offset = Vector128.Create<byte>(63);
 1083
 1084            do
 1085            {
 1086                // Step 1: Load 64 bytes and de-interleave.
 1087                if (!decoder.TryLoadArmVector128x4(src, srcStart, sourceLength,
 1088                    out Vector128<byte> str1, out Vector128<byte> str2, out Vector128<byte> str3, out Vector128<byte> st
 1089                {
 1090                    break;
 1091                }
 1092
 1093                // Step 2: Map each valid input to its Base64 value.
 1094                // We use two look-ups to compute partial results and combine them later.
 1095
 1096                // Step 2.1: Detect valid Base64 values from the first three groups. Maps input as,
 1097                //  0 to  63 (Invalid) => 255
 1098                //  0 to  63 (Valid)   => Their Base64 equivalent
 1099                // 64 to 255           => 0
 1100
 1101                // Each input value acts as an index in the look-up table 'decLutOne'.
 1102                // e.g., for group 1: index 43 maps to 62 (Base64 '+').
 1103                // Group 4 and 5 values are out-of-range (>64), so they are mapped to zero.
 1104                // Other valid indices but invalid values are mapped to 255.
 1105                Vector128<byte> decOne1 = AdvSimd.Arm64.VectorTableLookup(decLutOne, str1);
 1106                Vector128<byte> decOne2 = AdvSimd.Arm64.VectorTableLookup(decLutOne, str2);
 1107                Vector128<byte> decOne3 = AdvSimd.Arm64.VectorTableLookup(decLutOne, str3);
 1108                Vector128<byte> decOne4 = AdvSimd.Arm64.VectorTableLookup(decLutOne, str4);
 1109
 1110                // Step 2.2: Detect valid Base64 values from groups 4 and 5. Maps input as,
 1111                //   0 to  63           => 0
 1112                //  64 to 122 (Valid)   => Their Base64 equivalent
 1113                //  64 to 122 (Invalid) => 255
 1114                // 123 to 255           => Remains unchanged
 1115
 1116                // Subtract/offset each input value by 63 so that it can be used as a valid offset.
 1117                // Subtract saturate makes values from the first three groups set to zero that are
 1118                // then mapped to zero in the subsequent look-up.
 1119                Vector128<byte> decTwo1 = AdvSimd.SubtractSaturate(str1, offset);
 1120                Vector128<byte> decTwo2 = AdvSimd.SubtractSaturate(str2, offset);
 1121                Vector128<byte> decTwo3 = AdvSimd.SubtractSaturate(str3, offset);
 1122                Vector128<byte> decTwo4 = AdvSimd.SubtractSaturate(str4, offset);
 1123
 1124                // We use VTBX to map values where out-of-range indices are unchanged.
 1125                decTwo1 = AdvSimd.Arm64.VectorTableLookupExtension(decTwo1, decLutTwo, decTwo1);
 1126                decTwo2 = AdvSimd.Arm64.VectorTableLookupExtension(decTwo2, decLutTwo, decTwo2);
 1127                decTwo3 = AdvSimd.Arm64.VectorTableLookupExtension(decTwo3, decLutTwo, decTwo3);
 1128                decTwo4 = AdvSimd.Arm64.VectorTableLookupExtension(decTwo4, decLutTwo, decTwo4);
 1129
 1130                // Step 3: Combine the partial result.
 1131                // Each look-up above maps valid values to their Base64 equivalent or zero.
 1132                // Thus the intermediate results 'decOne' and 'decTwo' could be OR-ed to get final values.
 1133                str1 = (decOne1 | decTwo1);
 1134                str2 = (decOne2 | decTwo2);
 1135                str3 = (decOne3 | decTwo3);
 1136                str4 = (decOne4 | decTwo4);
 1137
 1138                // Step 4: Detect an invalid input value.
 1139                // Invalid values < 122 are set to 255 while the ones above 122 are unchanged.
 1140                // Check for invalid input, any value larger than 63.
 1141                Vector128<byte> classified = (Vector128.GreaterThan(str1, offset)
 1142                                            | Vector128.GreaterThan(str2, offset)
 1143                                            | Vector128.GreaterThan(str3, offset)
 1144                                            | Vector128.GreaterThan(str4, offset));
 1145
 1146                // Check that all bits are zero.
 1147                if (classified != Vector128<byte>.Zero)
 1148                {
 1149                    break;
 1150                }
 1151
 1152                // Step 5: Compress four bytes into three.
 1153                Vector128<byte> res1 = ((str1 << 2) | (str2 >> 4));
 1154                Vector128<byte> res2 = ((str2 << 4) | (str3 >> 2));
 1155                Vector128<byte> res3 = ((str3 << 6) | str4);
 1156
 1157                // Step 6: Interleave and store decoded results.
 1158                AssertWrite<Vector128<byte>>(dest, destStart, destLength);
 1159                AdvSimd.Arm64.StoreVectorAndZip(dest, (res1, res2, res3));
 1160
 1161                src += 64;
 1162                dest += 48;
 1163            }
 1164            while (src <= srcEnd);
 1165
 1166            srcBytes = src;
 1167            destBytes = dest;
 1168        }
 1169
 1170        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1171        [CompExactlyDependsOn(typeof(AdvSimd.Arm64))]
 1172        [CompExactlyDependsOn(typeof(Ssse3))]
 1173        [CompExactlyDependsOn(typeof(PackedSimd))]
 1174        private static unsafe void Vector128Decode<TBase64Decoder, T>(TBase64Decoder decoder, ref T* srcBytes, ref byte*
 1175            where TBase64Decoder : IBase64Decoder<T>
 1176            where T : unmanaged
 1177        {
 1178            Debug.Assert((Ssse3.IsSupported || AdvSimd.Arm64.IsSupported || PackedSimd.IsSupported) && BitConverter.IsLi
 1179
 1180            // If we have Vector128 support, pick off 16 bytes at a time for as long as we can,
 1181            // but make sure that we quit before seeing any == markers at the end of the
 1182            // string. Also, because we write four zeroes at the end of the output, ensure
 1183            // that there are at least 6 valid bytes of input data remaining to close the
 1184            // gap. 16 + 2 + 6 = 24 bytes.
 1185
 1186            // The input consists of six character sets in the Base64 alphabet,
 1187            // which we need to map back to the 6-bit values they represent.
 1188            // There are three ranges, two singles, and then there's the rest.
 1189            //
 1190            //  #  From       To        Add  Characters
 1191            //  1  [43]       [62]      +19  +
 1192            //  2  [47]       [63]      +16  /
 1193            //  3  [48..57]   [52..61]   +4  0..9
 1194            //  4  [65..90]   [0..25]   -65  A..Z
 1195            //  5  [97..122]  [26..51]  -71  a..z
 1196            // (6) Everything else => invalid input
 1197
 1198            // We will use LUTS for character validation & offset computation
 1199            // Remember that 0x2X and 0x0X are the same index for _mm_shuffle_epi8,
 1200            // this allows to mask with 0x2F instead of 0x0F and thus save one constant declaration (register and/or mem
 1201
 1202            // For offsets:
 1203            // Perfect hash for lut = ((src>>4)&0x2F)+((src==0x2F)?0xFF:0x00)
 1204            // 0000 = garbage
 1205            // 0001 = /
 1206            // 0010 = +
 1207            // 0011 = 0-9
 1208            // 0100 = A-Z
 1209            // 0101 = A-Z
 1210            // 0110 = a-z
 1211            // 0111 = a-z
 1212            // 1000 >= garbage
 1213
 1214            // For validation, here's the table.
 1215            // A character is valid if and only if the AND of the 2 lookups equals 0:
 1216
 1217            // hi \ lo              0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111
 1218            //      LUT             0x15 0x11 0x11 0x11 0x11 0x11 0x11 0x11 0x11 0x11 0x13 0x1A 0x1B 0x1B 0x1B 0x1A
 1219
 1220            // 0000 0X10 char        NUL  SOH  STX  ETX  EOT  ENQ  ACK  BEL   BS   HT   LF   VT   FF   CR   SO   SI
 1221            //           andlut     0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10
 1222
 1223            // 0001 0x10 char        DLE  DC1  DC2  DC3  DC4  NAK  SYN  ETB  CAN   EM  SUB  ESC   FS   GS   RS   US
 1224            //           andlut     0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10
 1225
 1226            // 0010 0x01 char               !    "    #    $    %    &    '    (    )    *    +    ,    -    .    /
 1227            //           andlut     0x01 0x01 0x01 0x01 0x01 0x01 0x01 0x01 0x01 0x01 0x01 0x00 0x01 0x01 0x01 0x00
 1228
 1229            // 0011 0x02 char          0    1    2    3    4    5    6    7    8    9    :    ;    <    =    >    ?
 1230            //           andlut     0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x02 0x02 0x02 0x02 0x02 0x02
 1231
 1232            // 0100 0x04 char          @    A    B    C    D    E    F    G    H    I    J    K    L    M    N    0
 1233            //           andlut     0x04 0x00 0x00 0x00 0X00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00
 1234
 1235            // 0101 0x08 char          P    Q    R    S    T    U    V    W    X    Y    Z    [    \    ]    ^    _
 1236            //           andlut     0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x08 0x08 0x08 0x08 0x08
 1237
 1238            // 0110 0x04 char          `    a    b    c    d    e    f    g    h    i    j    k    l    m    n    o
 1239            //           andlut     0x04 0x00 0x00 0x00 0X00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00
 1240            // 0111 0X08 char          p    q    r    s    t    u    v    w    x    y    z    {    |    }    ~
 1241            //           andlut     0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x08 0x08 0x08 0x08 0x08
 1242
 1243            // 1000 0x10 andlut     0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10
 1244            // 1001 0x10 andlut     0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10
 1245            // 1010 0x10 andlut     0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10
 1246            // 1011 0x10 andlut     0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10
 1247            // 1100 0x10 andlut     0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10
 1248            // 1101 0x10 andlut     0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10
 1249            // 1110 0x10 andlut     0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10
 1250            // 1111 0x10 andlut     0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10
 1251
 1252            // The JIT won't hoist these "constants", so help it
 01253            Vector128<byte> lutHi = Vector128.Create(decoder.Vector128LutHigh).AsByte();
 01254            Vector128<byte> lutLo = Vector128.Create(decoder.Vector128LutLow).AsByte();
 01255            Vector128<sbyte> lutShift = Vector128.Create(decoder.Vector128LutShift).AsSByte();
 01256            Vector128<sbyte> packBytesMask = Vector128.Create(0x06000102, 0x090A0405, 0x0C0D0E08, 0xffffffff).AsSByte();
 01257            Vector128<byte> mergeConstant0 = Vector128.Create(0x01400140).AsByte();
 01258            Vector128<short> mergeConstant1 = Vector128.Create(0x00011000).AsInt16();
 01259            Vector128<byte> one = Vector128<byte>.One;
 01260            Vector128<byte> mask2F = Vector128.Create(decoder.MaskSlashOrUnderscore);
 01261            Vector128<byte> mask8F = Vector128.Create((byte)0x8F);
 01262            Vector128<byte> shiftForUnderscore = Vector128.Create((byte)33);
 01263            T* src = srcBytes;
 01264            byte* dest = destBytes;
 1265
 1266            //while (remaining >= 24)
 1267            do
 1268            {
 01269                if (!decoder.TryLoadVector128(src, srcStart, sourceLength, out Vector128<byte> str))
 1270                {
 1271                    break;
 1272                }
 1273
 1274                // lookup
 01275                Vector128<byte> hiNibbles = Vector128.ShiftRightLogical(str.AsInt32(), 4).AsByte() & mask2F;
 1276
 01277                if (!decoder.TryDecode128Core(str, hiNibbles, mask2F, mask8F, lutLo, lutHi, lutShift, shiftForUnderscore
 1278                {
 1279                    break;
 1280                }
 1281
 1282                // in, bits, upper case are most significant bits, lower case are least significant bits
 1283                // 00llllll 00kkkkLL 00jjKKKK 00JJJJJJ
 1284                // 00iiiiii 00hhhhII 00ggHHHH 00GGGGGG
 1285                // 00ffffff 00eeeeFF 00ddEEEE 00DDDDDD
 1286                // 00cccccc 00bbbbCC 00aaBBBB 00AAAAAA
 1287
 1288                Vector128<short> merge_ab_and_bc;
 01289                if (Ssse3.IsSupported)
 1290                {
 01291                    merge_ab_and_bc = Ssse3.MultiplyAddAdjacent(str.AsByte(), mergeConstant0.AsSByte());
 1292                }
 1293                else if (AdvSimd.Arm64.IsSupported)
 1294                {
 1295                    Vector128<ushort> evens = AdvSimd.ShiftLeftLogicalWideningLower(AdvSimd.Arm64.UnzipEven(str, one).Ge
 1296                    Vector128<ushort> odds = AdvSimd.Arm64.TransposeOdd(str, Vector128<byte>.Zero).AsUInt16();
 1297                    merge_ab_and_bc = Vector128.Add(evens, odds).AsInt16();
 1298                }
 1299                else if (PackedSimd.IsSupported)
 1300                {
 1301                    // MultiplyAddAdjacent by {64,1,...} is the even byte (low of each u16 lane) times 64 plus the odd b
 1302                    Vector128<ushort> u = str.AsUInt16();
 1303                    Vector128<ushort> evens = Vector128.ShiftLeft(u & Vector128.Create((ushort)0x00FF), 6);
 1304                    Vector128<ushort> odds = Vector128.ShiftRightLogical(u, 8);
 1305                    merge_ab_and_bc = (evens + odds).AsInt16();
 1306                }
 1307                else
 1308                {
 1309                    // We explicitly recheck each IsSupported query to ensure that the trimmer can see which paths are l
 01310                    ThrowUnreachableException();
 1311                    merge_ab_and_bc = default;
 1312                }
 1313                // 0000kkkk LLllllll 0000JJJJ JJjjKKKK
 1314                // 0000hhhh IIiiiiii 0000GGGG GGggHHHH
 1315                // 0000eeee FFffffff 0000DDDD DDddEEEE
 1316                // 0000bbbb CCcccccc 0000AAAA AAaaBBBB
 1317
 1318                Vector128<int> output;
 01319                if (Ssse3.IsSupported)
 1320                {
 01321                    output = Sse2.MultiplyAddAdjacent(merge_ab_and_bc, mergeConstant1);
 1322                }
 1323                else if (AdvSimd.Arm64.IsSupported)
 1324                {
 1325                    Vector128<int> ievens = AdvSimd.ShiftLeftLogicalWideningLower(AdvSimd.Arm64.UnzipEven(merge_ab_and_b
 1326                    Vector128<int> iodds = AdvSimd.Arm64.TransposeOdd(merge_ab_and_bc, Vector128<short>.Zero).AsInt32();
 1327                    output = Vector128.Add(ievens, iodds).AsInt32();
 1328                }
 1329                else if (PackedSimd.IsSupported)
 1330                {
 1331                    // MultiplyAddAdjacent by {4096,1,...} is the even i16 (low of each i32 lane) times 4096 plus the od
 1332                    Vector128<uint> m = merge_ab_and_bc.AsUInt32();
 1333                    Vector128<uint> ievens = Vector128.ShiftLeft(m & Vector128.Create(0x0000FFFFu), 12);
 1334                    Vector128<uint> iodds = Vector128.ShiftRightLogical(m, 16);
 1335                    output = (ievens + iodds).AsInt32();
 1336                }
 1337                else
 1338                {
 1339                    // We explicitly recheck each IsSupported query to ensure that the trimmer can see which paths are l
 01340                    ThrowUnreachableException();
 1341                    output = default;
 1342                }
 1343                // 00000000 JJJJJJjj KKKKkkkk LLllllll
 1344                // 00000000 GGGGGGgg HHHHhhhh IIiiiiii
 1345                // 00000000 DDDDDDdd EEEEeeee FFffffff
 1346                // 00000000 AAAAAAaa BBBBbbbb CCcccccc
 1347
 1348                // Pack bytes together:
 01349                str = SimdShuffle(output.AsByte(), packBytesMask.AsByte(), mask8F);
 1350                // 00000000 00000000 00000000 00000000
 1351                // LLllllll KKKKkkkk JJJJJJjj IIiiiiii
 1352                // HHHHhhhh GGGGGGgg FFffffff EEEEeeee
 1353                // DDDDDDdd CCcccccc BBBBbbbb AAAAAAaa
 1354
 01355                AssertWrite<Vector128<sbyte>>(dest, destStart, destLength);
 01356                str.Store(dest);
 1357
 01358                src += 16;
 01359                dest += 12;
 1360            }
 01361            while (src <= srcEnd);
 1362
 01363            srcBytes = src;
 01364            destBytes = dest;
 01365        }
 1366#endif
 1367
 1368        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1369        private static unsafe void WriteThreeLowOrderBytes(byte* destination, int value)
 1370        {
 01371            destination[0] = (byte)(value >> 16);
 01372            destination[1] = (byte)(value >> 8);
 01373            destination[2] = (byte)value;
 01374        }
 1375
 1376        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1377        internal static bool IsWhiteSpace(int value)
 1378        {
 01379            Debug.Assert(value >= 0 && value <= ushort.MaxValue);
 1380            uint charMinusLowUInt32;
 01381            return (int)((0xC8000100U << (short)(charMinusLowUInt32 = (ushort)(value - '\t'))) & (charMinusLowUInt32 - 3
 1382        }
 1383
 1384        internal readonly struct Base64DecoderByte : IBase64Decoder<byte>
 1385        {
 1386            // Pre-computing this table using a custom string(s_characters) and GenerateDecodingMapAndVerify (found in t
 1387            public ReadOnlySpan<sbyte> DecodingMap =>
 01388                [
 01389                    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
 01390                    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
 01391                    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,         //62 is placed at index 43 (
 01392                    52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,         //52-61 are placed at index 
 01393                    -1,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
 01394                    15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,         //0-25 are placed at index 6
 01395                    -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
 01396                    41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1,         //26-51 are placed at index 
 01397                    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,         // Bytes over 122 ('z') are 
 01398                    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,         // Hence, padding the map wi
 01399                    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
 01400                    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
 01401                    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
 01402                    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
 01403                    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
 01404                    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
 01405                ];
 1406
 1407            public ReadOnlySpan<uint> VbmiLookup0 =>
 01408                [
 01409                    0x80808080, 0x80808080, 0x80808080, 0x80808080,
 01410                    0x80808080, 0x80808080, 0x80808080, 0x80808080,
 01411                    0x80808080, 0x80808080, 0x3e808080, 0x3f808080,
 01412                    0x37363534, 0x3b3a3938, 0x80803d3c, 0x80808080
 01413                ];
 1414
 1415            public ReadOnlySpan<uint> VbmiLookup1 =>
 01416                [
 01417                    0x02010080, 0x06050403, 0x0a090807, 0x0e0d0c0b,
 01418                    0x1211100f, 0x16151413, 0x80191817, 0x80808080,
 01419                    0x1c1b1a80, 0x201f1e1d, 0x24232221, 0x28272625,
 01420                    0x2c2b2a29, 0x302f2e2d, 0x80333231, 0x80808080
 01421                ];
 1422
 1423            public ReadOnlySpan<sbyte> Avx2LutHigh =>
 01424                [
 01425                    0x10, 0x10, 0x01, 0x02,
 01426                    0x04, 0x08, 0x04, 0x08,
 01427                    0x10, 0x10, 0x10, 0x10,
 01428                    0x10, 0x10, 0x10, 0x10,
 01429                    0x10, 0x10, 0x01, 0x02,
 01430                    0x04, 0x08, 0x04, 0x08,
 01431                    0x10, 0x10, 0x10, 0x10,
 01432                    0x10, 0x10, 0x10, 0x10
 01433                ];
 1434
 1435            public ReadOnlySpan<sbyte> Avx2LutLow =>
 01436                [
 01437                    0x15, 0x11, 0x11, 0x11,
 01438                    0x11, 0x11, 0x11, 0x11,
 01439                    0x11, 0x11, 0x13, 0x1A,
 01440                    0x1B, 0x1B, 0x1B, 0x1A,
 01441                    0x15, 0x11, 0x11, 0x11,
 01442                    0x11, 0x11, 0x11, 0x11,
 01443                    0x11, 0x11, 0x13, 0x1A,
 01444                    0x1B, 0x1B, 0x1B, 0x1A
 01445                ];
 1446
 1447            public ReadOnlySpan<sbyte> Avx2LutShift =>
 01448                [
 01449                    0, 16, 19, 4,
 01450                    -65, -65, -71, -71,
 01451                    0, 0, 0, 0,
 01452                    0, 0, 0, 0,
 01453                    0, 16, 19, 4,
 01454                    -65, -65, -71, -71,
 01455                    0, 0, 0, 0,
 01456                    0, 0, 0, 0
 01457                ];
 1458
 01459            public byte MaskSlashOrUnderscore => (byte)'/';
 1460
 01461            public ReadOnlySpan<int> Vector128LutHigh => [0x02011010, 0x08040804, 0x10101010, 0x10101010];
 1462
 01463            public ReadOnlySpan<int> Vector128LutLow => [0x11111115, 0x11111111, 0x1A131111, 0x1A1B1B1B];
 1464
 01465            public ReadOnlySpan<uint> Vector128LutShift => [0x04131000, 0xb9b9bfbf, 0x00000000, 0x00000000];
 1466
 01467            public ReadOnlySpan<uint> AdvSimdLutOne3 => [0xFFFFFFFF, 0xFFFFFFFF, 0x3EFFFFFF, 0x3FFFFFFF];
 1468
 01469            public uint AdvSimdLutTwo3Uint1 => 0x1B1AFFFF;
 1470
 01471            public int GetMaxDecodedLength(int utf8Length) => Base64.GetMaxDecodedFromUtf8Length(utf8Length);
 1472
 01473            public bool IsInvalidLength(int bufferLength) => bufferLength % 4 != 0; // only decode input if it is a mult
 1474
 01475            public bool IsValidPadding(uint padChar) => padChar == EncodingPad;
 1476
 01477            public int SrcLength(bool _, int utf8Length) => utf8Length & ~0x3;  // only decode input up to the closest m
 1478
 1479#if NET
 1480            [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1481            [CompExactlyDependsOn(typeof(AdvSimd.Arm64))]
 1482            [CompExactlyDependsOn(typeof(Ssse3))]
 1483            [CompExactlyDependsOn(typeof(PackedSimd))]
 1484            public bool TryDecode128Core(
 1485                Vector128<byte> str,
 1486                Vector128<byte> hiNibbles,
 1487                Vector128<byte> maskSlashOrUnderscore,
 1488                Vector128<byte> mask8F,
 1489                Vector128<byte> lutLow,
 1490                Vector128<byte> lutHigh,
 1491                Vector128<sbyte> lutShift,
 1492                Vector128<byte> _,
 1493                out Vector128<byte> result)
 1494            {
 01495                Vector128<byte> loNibbles = str & maskSlashOrUnderscore;
 01496                Vector128<byte> hi = SimdShuffle(lutHigh, hiNibbles, mask8F);
 01497                Vector128<byte> lo = SimdShuffle(lutLow, loNibbles, mask8F);
 1498
 1499                // Check for invalid input: if any "and" values from lo and hi are not zero,
 1500                // fall back on bytewise code to do error checking and reporting:
 01501                if ((lo & hi) != Vector128<byte>.Zero)
 1502                {
 01503                    result = default;
 01504                    return false;
 1505                }
 1506
 01507                Vector128<byte> eq2F = Vector128.Equals(str, maskSlashOrUnderscore);
 01508                Vector128<byte> shift = SimdShuffle(lutShift.AsByte(), (eq2F + hiNibbles), mask8F);
 1509
 1510                // Now simply add the delta values to the input:
 01511                result = str + shift;
 1512
 01513                return true;
 1514            }
 1515
 1516            [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1517            [CompExactlyDependsOn(typeof(Avx2))]
 1518            public bool TryDecode256Core(
 1519                Vector256<sbyte> str,
 1520                Vector256<sbyte> hiNibbles,
 1521                Vector256<sbyte> maskSlashOrUnderscore,
 1522                Vector256<sbyte> lutLow,
 1523                Vector256<sbyte> lutHigh,
 1524                Vector256<sbyte> lutShift,
 1525                Vector256<sbyte> _,
 1526                out Vector256<sbyte> result)
 1527            {
 01528                Vector256<sbyte> loNibbles = str & maskSlashOrUnderscore;
 01529                Vector256<sbyte> hi = Avx2.Shuffle(lutHigh, hiNibbles);
 01530                Vector256<sbyte> lo = Avx2.Shuffle(lutLow, loNibbles);
 1531
 01532                if ((lo & hi) != Vector256<sbyte>.Zero)
 1533                {
 01534                    result = default;
 01535                    return false;
 1536                }
 1537
 01538                Vector256<sbyte> eq2F = Avx2.CompareEqual(str, maskSlashOrUnderscore);
 01539                Vector256<sbyte> shift = Avx2.Shuffle(lutShift, eq2F + hiNibbles);
 1540
 01541                result = str + shift;
 1542
 01543                return true;
 1544            }
 1545
 1546            [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1547            public unsafe bool TryLoadVector512(byte* src, byte* srcStart, int sourceLength, out Vector512<sbyte> str)
 1548            {
 01549                AssertRead<Vector512<sbyte>>(src, srcStart, sourceLength);
 01550                str = Vector512.Load(src).AsSByte();
 01551                return true;
 1552            }
 1553
 1554            [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1555            [CompExactlyDependsOn(typeof(Avx2))]
 1556            public unsafe bool TryLoadAvxVector256(byte* src, byte* srcStart, int sourceLength, out Vector256<sbyte> str
 1557            {
 01558                AssertRead<Vector256<sbyte>>(src, srcStart, sourceLength);
 01559                str = Avx.LoadVector256(src).AsSByte();
 01560                return true;
 1561            }
 1562
 1563            [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1564            public unsafe bool TryLoadVector128(byte* src, byte* srcStart, int sourceLength, out Vector128<byte> str)
 1565            {
 01566                AssertRead<Vector128<sbyte>>(src, srcStart, sourceLength);
 01567                str = Vector128.LoadUnsafe(ref *src);
 01568                return true;
 1569            }
 1570
 1571            [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1572            [CompExactlyDependsOn(typeof(AdvSimd.Arm64))]
 1573            public unsafe bool TryLoadArmVector128x4(byte* src, byte* srcStart, int sourceLength,
 1574                out Vector128<byte> str1, out Vector128<byte> str2, out Vector128<byte> str3, out Vector128<byte> str4)
 1575            {
 01576                AssertRead<Vector128<byte>>(src, srcStart, sourceLength);
 01577                (str1, str2, str3, str4) = AdvSimd.Arm64.Load4xVector128AndUnzip(src);
 1578
 01579                return true;
 1580            }
 1581#endif // NET
 1582
 1583            [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1584            public unsafe int DecodeFourElements(byte* source, ref sbyte decodingMap)
 1585            {
 1586                // The 'source' span expected to have at least 4 elements, and the 'decodingMap' consists 256 sbytes
 01587                uint t0 = source[0];
 01588                uint t1 = source[1];
 01589                uint t2 = source[2];
 01590                uint t3 = source[3];
 1591
 01592                int i0 = Unsafe.Add(ref decodingMap, (int)t0);
 01593                int i1 = Unsafe.Add(ref decodingMap, (int)t1);
 01594                int i2 = Unsafe.Add(ref decodingMap, (int)t2);
 01595                int i3 = Unsafe.Add(ref decodingMap, (int)t3);
 1596
 01597                i0 <<= 18;
 01598                i1 <<= 12;
 01599                i2 <<= 6;
 1600
 01601                i0 |= i3;
 01602                i1 |= i2;
 1603
 01604                i0 |= i1;
 01605                return i0;
 1606            }
 1607
 1608            [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1609            public unsafe int DecodeRemaining(byte* srcEnd, ref sbyte decodingMap, long remaining, out uint t2, out uint
 1610            {
 1611                uint t0;
 1612                uint t1;
 01613                t2 = EncodingPad;
 01614                t3 = EncodingPad;
 1615                switch (remaining)
 1616                {
 1617                    case 2:
 01618                        t0 = srcEnd[-2];
 01619                        t1 = srcEnd[-1];
 01620                        break;
 1621                    case 3:
 01622                        t0 = srcEnd[-3];
 01623                        t1 = srcEnd[-2];
 01624                        t2 = srcEnd[-1];
 01625                        break;
 1626                    case 4:
 01627                        t0 = srcEnd[-4];
 01628                        t1 = srcEnd[-3];
 01629                        t2 = srcEnd[-2];
 01630                        t3 = srcEnd[-1];
 01631                        break;
 1632                    default:
 01633                        return -1;
 1634                }
 1635
 01636                int i0 = Unsafe.Add(ref decodingMap, (IntPtr)t0);
 01637                int i1 = Unsafe.Add(ref decodingMap, (IntPtr)t1);
 1638
 01639                i0 <<= 18;
 01640                i1 <<= 12;
 1641
 01642                i0 |= i1;
 01643                return i0;
 1644            }
 1645
 1646            [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1647            public int IndexOfAnyExceptWhiteSpace(ReadOnlySpan<byte> span)
 1648            {
 01649                for (int i = 0; i < span.Length; i++)
 1650                {
 01651                    if (!IsWhiteSpace(span[i]))
 1652                    {
 01653                        return i;
 1654                    }
 1655                }
 1656
 01657                return -1;
 1658            }
 1659
 1660            [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1661            public OperationStatus DecodeWithWhiteSpaceBlockwiseWrapper<TBase64Decoder>(TBase64Decoder decoder, ReadOnly
 1662                Span<byte> bytes, ref int bytesConsumed, ref int bytesWritten, bool isFinalBlock = true)
 1663                where TBase64Decoder : IBase64Decoder<byte> =>
 01664                DecodeWithWhiteSpaceBlockwise(decoder, utf8, bytes, ref bytesConsumed, ref bytesWritten, isFinalBlock);
 1665        }
 1666
 1667        internal readonly struct Base64DecoderChar : IBase64Decoder<ushort>
 1668        {
 01669            public ReadOnlySpan<sbyte> DecodingMap => default(Base64DecoderByte).DecodingMap;
 1670
 01671            public ReadOnlySpan<uint> VbmiLookup0 => default(Base64DecoderByte).VbmiLookup0;
 1672
 01673            public ReadOnlySpan<uint> VbmiLookup1 => default(Base64DecoderByte).VbmiLookup1;
 1674
 01675            public ReadOnlySpan<sbyte> Avx2LutHigh => default(Base64DecoderByte).Avx2LutHigh;
 1676
 01677            public ReadOnlySpan<sbyte> Avx2LutLow => default(Base64DecoderByte).Avx2LutLow;
 1678
 01679            public ReadOnlySpan<sbyte> Avx2LutShift => default(Base64DecoderByte).Avx2LutShift;
 1680
 01681            public byte MaskSlashOrUnderscore => default(Base64DecoderByte).MaskSlashOrUnderscore;
 1682
 01683            public ReadOnlySpan<int> Vector128LutHigh => default(Base64DecoderByte).Vector128LutHigh;
 1684
 01685            public ReadOnlySpan<int> Vector128LutLow => default(Base64DecoderByte).Vector128LutLow;
 1686
 01687            public ReadOnlySpan<uint> Vector128LutShift => default(Base64DecoderByte).Vector128LutShift;
 1688
 01689            public ReadOnlySpan<uint> AdvSimdLutOne3 => default(Base64DecoderByte).AdvSimdLutOne3;
 1690
 01691            public uint AdvSimdLutTwo3Uint1 => default(Base64DecoderByte).AdvSimdLutTwo3Uint1;
 1692
 01693            public int GetMaxDecodedLength(int sourceLength) => Base64.GetMaxDecodedFromUtf8Length(sourceLength);
 1694
 01695            public bool IsInvalidLength(int bufferLength) => bufferLength % 4 != 0;
 1696
 01697            public bool IsValidPadding(uint padChar) => padChar == EncodingPad;
 1698
 01699            public int SrcLength(bool _, int sourceLength) => sourceLength & ~0x3;
 1700
 1701#if NET
 1702            [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1703            [CompExactlyDependsOn(typeof(AdvSimd.Arm64))]
 1704            [CompExactlyDependsOn(typeof(Ssse3))]
 1705            [CompExactlyDependsOn(typeof(PackedSimd))]
 1706            public bool TryDecode128Core(Vector128<byte> str, Vector128<byte> hiNibbles, Vector128<byte> maskSlashOrUnde
 1707                Vector128<byte> lutLow, Vector128<byte> lutHigh, Vector128<sbyte> lutShift, Vector128<byte> shiftForUnde
 01708                default(Base64DecoderByte).TryDecode128Core(str, hiNibbles, maskSlashOrUnderscore, mask8F, lutLow, lutHi
 1709
 1710            [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1711            [CompExactlyDependsOn(typeof(Avx2))]
 1712            public bool TryDecode256Core(Vector256<sbyte> str, Vector256<sbyte> hiNibbles, Vector256<sbyte> maskSlashOrU
 1713                Vector256<sbyte> lutHigh, Vector256<sbyte> lutShift, Vector256<sbyte> shiftForUnderscore, out Vector256<
 01714                default(Base64DecoderByte).TryDecode256Core(str, hiNibbles, maskSlashOrUnderscore, lutLow, lutHigh, lutS
 1715
 1716            [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1717            public unsafe bool TryLoadVector512(ushort* src, ushort* srcStart, int sourceLength, out Vector512<sbyte> st
 1718            {
 01719                AssertRead<Vector512<ushort>>(src, srcStart, sourceLength);
 01720                Vector512<ushort> utf16VectorLower = Vector512.Load(src);
 01721                Vector512<ushort> utf16VectorUpper = Vector512.Load(src + 32);
 01722                if (Ascii.VectorContainsNonAsciiChar(utf16VectorLower | utf16VectorUpper))
 1723                {
 01724                    str = default;
 01725                    return false;
 1726                }
 1727
 01728                str = Ascii.ExtractAsciiVector(utf16VectorLower, utf16VectorUpper).AsSByte();
 01729                return true;
 1730            }
 1731
 1732            [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1733            [CompExactlyDependsOn(typeof(Avx2))]
 1734            public unsafe bool TryLoadAvxVector256(ushort* src, ushort* srcStart, int sourceLength, out Vector256<sbyte>
 1735            {
 01736                AssertRead<Vector256<sbyte>>(src, srcStart, sourceLength);
 01737                Vector256<ushort> utf16VectorLower = Avx.LoadVector256(src);
 01738                Vector256<ushort> utf16VectorUpper = Avx.LoadVector256(src + 16);
 1739
 01740                if (Ascii.VectorContainsNonAsciiChar(utf16VectorLower | utf16VectorUpper))
 1741                {
 01742                    str = default;
 01743                    return false;
 1744                }
 1745
 01746                str = Ascii.ExtractAsciiVector(utf16VectorLower, utf16VectorUpper).AsSByte();
 01747                return true;
 1748            }
 1749
 1750            [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1751            public unsafe bool TryLoadVector128(ushort* src, ushort* srcStart, int sourceLength, out Vector128<byte> str
 1752            {
 01753                AssertRead<Vector128<sbyte>>(src, srcStart, sourceLength);
 01754                Vector128<ushort> utf16VectorLower = Vector128.LoadUnsafe(ref *src);
 01755                Vector128<ushort> utf16VectorUpper = Vector128.LoadUnsafe(ref *src, 8);
 01756                if (Ascii.VectorContainsNonAsciiChar(utf16VectorLower | utf16VectorUpper))
 1757                {
 01758                    str = default;
 01759                    return false;
 1760                }
 1761
 01762                str = Ascii.ExtractAsciiVector(utf16VectorLower, utf16VectorUpper);
 01763                return true;
 1764            }
 1765
 1766            [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1767            [CompExactlyDependsOn(typeof(AdvSimd.Arm64))]
 1768            public unsafe bool TryLoadArmVector128x4(ushort* src, ushort* srcStart, int sourceLength,
 1769                out Vector128<byte> str1, out Vector128<byte> str2, out Vector128<byte> str3, out Vector128<byte> str4)
 1770            {
 01771                AssertRead<Vector128<sbyte>>(src, srcStart, sourceLength);
 01772                var (s11, s12, s21, s22) = AdvSimd.Arm64.Load4xVector128AndUnzip(src);
 01773                var (s31, s32, s41, s42) = AdvSimd.Arm64.Load4xVector128AndUnzip(src + 32);
 1774
 01775                if (Ascii.VectorContainsNonAsciiChar(s11 | s12 | s21 | s22 | s31 | s32 | s41 | s42))
 1776                {
 01777                    str1 = str2 = str3 = str4 = default;
 01778                    return false;
 1779                }
 1780
 01781                str1 = Ascii.ExtractAsciiVector(s11, s31);
 01782                str2 = Ascii.ExtractAsciiVector(s12, s32);
 01783                str3 = Ascii.ExtractAsciiVector(s21, s41);
 01784                str4 = Ascii.ExtractAsciiVector(s22, s42);
 1785
 01786                return true;
 1787            }
 1788#endif // NET
 1789
 1790            [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1791            public unsafe int DecodeFourElements(ushort* source, ref sbyte decodingMap)
 1792            {
 1793                // The 'source' span expected to have at least 4 elements, and the 'decodingMap' consists 256 sbytes
 01794                uint t0 = source[0];
 01795                uint t1 = source[1];
 01796                uint t2 = source[2];
 01797                uint t3 = source[3];
 1798
 01799                if (((t0 | t1 | t2 | t3) & 0xffffff00) != 0)
 1800                {
 01801                    return -1; // One or more chars falls outside the 00..ff range, invalid Base64 character.
 1802                }
 1803
 01804                int i0 = Unsafe.Add(ref decodingMap, (int)t0);
 01805                int i1 = Unsafe.Add(ref decodingMap, (int)t1);
 01806                int i2 = Unsafe.Add(ref decodingMap, (int)t2);
 01807                int i3 = Unsafe.Add(ref decodingMap, (int)t3);
 1808
 01809                i0 <<= 18;
 01810                i1 <<= 12;
 01811                i2 <<= 6;
 1812
 01813                i0 |= i3;
 01814                i1 |= i2;
 1815
 01816                i0 |= i1;
 01817                return i0;
 1818            }
 1819
 1820            [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1821            public unsafe int DecodeRemaining(ushort* srcEnd, ref sbyte decodingMap, long remaining, out uint t2, out ui
 1822            {
 1823                uint t0;
 1824                uint t1;
 01825                t2 = EncodingPad;
 01826                t3 = EncodingPad;
 1827                switch (remaining)
 1828                {
 1829                    case 2:
 01830                        t0 = srcEnd[-2];
 01831                        t1 = srcEnd[-1];
 01832                        break;
 1833                    case 3:
 01834                        t0 = srcEnd[-3];
 01835                        t1 = srcEnd[-2];
 01836                        t2 = srcEnd[-1];
 01837                        break;
 1838                    case 4:
 01839                        t0 = srcEnd[-4];
 01840                        t1 = srcEnd[-3];
 01841                        t2 = srcEnd[-2];
 01842                        t3 = srcEnd[-1];
 01843                        break;
 1844                    default:
 01845                        return -1;
 1846                }
 1847
 01848                if (((t0 | t1 | t2 | t3) & 0xffffff00) != 0)
 1849                {
 01850                    return -1;
 1851                }
 1852
 01853                int i0 = Unsafe.Add(ref decodingMap, (IntPtr)t0);
 01854                int i1 = Unsafe.Add(ref decodingMap, (IntPtr)t1);
 1855
 01856                i0 <<= 18;
 01857                i1 <<= 12;
 1858
 01859                i0 |= i1;
 01860                return i0;
 1861            }
 1862
 1863            [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1864            public int IndexOfAnyExceptWhiteSpace(ReadOnlySpan<ushort> span)
 1865            {
 01866                for (int i = 0; i < span.Length; i++)
 1867                {
 01868                    if (!IsWhiteSpace(span[i]))
 1869                    {
 01870                        return i;
 1871                    }
 1872                }
 1873
 01874                return -1;
 1875            }
 1876
 1877            [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1878            public OperationStatus DecodeWithWhiteSpaceBlockwiseWrapper<TBase64Decoder>(TBase64Decoder decoder, ReadOnly
 1879                Span<byte> bytes, ref int bytesConsumed, ref int bytesWritten, bool isFinalBlock = true) where TBase64De
 01880                DecodeWithWhiteSpaceBlockwise(default(Base64DecoderChar), source, bytes, ref bytesConsumed, ref bytesWri
 1881        }
 1882    }
 1883}
 1884

https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/src/libraries/System.Private.CoreLib/src/System/Buffers/Text/Base64Helper/Base64EncoderHelper.cs

#LineLine coverage
 1// Licensed to the .NET Foundation under one or more agreements.
 2// The .NET Foundation licenses this file to you under the MIT license.
 3
 4using System.Diagnostics.CodeAnalysis;
 5using System.Runtime.CompilerServices;
 6using System.Runtime.InteropServices;
 7#if NET
 8using System.Runtime.Intrinsics;
 9using System.Runtime.Intrinsics.Arm;
 10using System.Runtime.Intrinsics.Wasm;
 11using System.Runtime.Intrinsics.X86;
 12#endif
 13
 14namespace System.Buffers.Text
 15{
 16    // AVX2 version based on https://github.com/aklomp/base64/tree/e516d769a2a432c08404f1981e73b431566057be/lib/arch/avx
 17    // Vector128 version based on https://github.com/aklomp/base64/tree/e516d769a2a432c08404f1981e73b431566057be/lib/arc
 18    internal static partial class Base64Helper
 19    {
 20        internal static unsafe OperationStatus EncodeTo<TBase64Encoder, T>(TBase64Encoder encoder, ReadOnlySpan<byte> so
 21            Span<T> destination, out int bytesConsumed, out int bytesWritten, bool isFinalBlock = true)
 22            where TBase64Encoder : IBase64Encoder<T>
 23            where T : unmanaged
 24        {
 25            if (source.IsEmpty)
 26            {
 027                bytesConsumed = 0;
 028                bytesWritten = 0;
 029                return OperationStatus.Done;
 30            }
 31
 032            fixed (byte* srcBytes = &MemoryMarshal.GetReference(source))
 033            fixed (T* destBytes = &MemoryMarshal.GetReference(destination))
 34            {
 035                int srcLength = source.Length;
 036                int destLength = destination.Length;
 037                int maxSrcLength = encoder.GetMaxSrcLength(srcLength, destLength);
 38
 039                byte* src = srcBytes;
 040                T* dest = destBytes;
 041                byte* srcEnd = srcBytes + (uint)srcLength;
 042                byte* srcMax = srcBytes + (uint)maxSrcLength;
 43
 44#if NET
 045                if (maxSrcLength >= 16)
 46                {
 047                    byte* end = srcMax - 64;
 048                    if (Vector512.IsHardwareAccelerated && Avx512Vbmi.IsSupported && (end >= src))
 49                    {
 050                        Avx512Encode(encoder, ref src, ref dest, end, maxSrcLength, destLength, srcBytes, destBytes);
 51
 052                        if (src == srcEnd)
 53                            goto DoneExit;
 54                    }
 55
 056                    end = srcMax - 32;
 057                    if (Avx2.IsSupported && (end >= src))
 58                    {
 059                        Avx2Encode(encoder, ref src, ref dest, end, maxSrcLength, destLength, srcBytes, destBytes);
 60
 061                        if (src == srcEnd)
 62                            goto DoneExit;
 63                    }
 64
 065                    end = srcMax - 48;
 66                    if (AdvSimd.Arm64.IsSupported && (end >= src))
 67                    {
 68                        AdvSimdEncode(encoder, ref src, ref dest, end, maxSrcLength, destLength, srcBytes, destBytes);
 69
 70                        if (src == srcEnd)
 71                            goto DoneExit;
 72                    }
 73
 074                    end = srcMax - 16;
 075                    if ((Ssse3.IsSupported || AdvSimd.Arm64.IsSupported || PackedSimd.IsSupported) && BitConverter.IsLit
 76                    {
 077                        Vector128Encode(encoder, ref src, ref dest, end, maxSrcLength, destLength, srcBytes, destBytes);
 78
 079                        if (src == srcEnd)
 80                            goto DoneExit;
 81                    }
 82                }
 83#endif
 084                ref byte encodingMap = ref MemoryMarshal.GetReference(encoder.EncodingMap);
 85
 086                srcMax -= 2;
 087                while (src < srcMax)
 88                {
 089                    encoder.EncodeThreeAndWrite(src, dest, ref encodingMap);
 090                    src += 3;
 091                    dest += 4;
 92                }
 93
 094                if (srcMax + 2 != srcEnd)
 95                    goto DestinationTooSmallExit;
 96
 097                if (!isFinalBlock)
 98                {
 099                    if (src == srcEnd)
 0100                        goto DoneExit;
 101
 102                    goto NeedMoreData;
 103                }
 104
 0105                if (src + 1 == srcEnd)
 106                {
 0107                    encoder.EncodeOneOptionallyPadTwo(src, dest, ref encodingMap);
 0108                    src += 1;
 0109                    dest += encoder.IncrementPadTwo;
 110                }
 0111                else if (src + 2 == srcEnd)
 112                {
 0113                    encoder.EncodeTwoOptionallyPadOne(src, dest, ref encodingMap);
 0114                    src += 2;
 0115                    dest += encoder.IncrementPadOne;
 116                }
 117
 118            DoneExit:
 0119                bytesConsumed = (int)(src - srcBytes);
 0120                bytesWritten = (int)(dest - destBytes);
 0121                return OperationStatus.Done;
 122
 123            DestinationTooSmallExit:
 0124                bytesConsumed = (int)(src - srcBytes);
 0125                bytesWritten = (int)(dest - destBytes);
 0126                return OperationStatus.DestinationTooSmall;
 127
 128            NeedMoreData:
 0129                bytesConsumed = (int)(src - srcBytes);
 0130                bytesWritten = (int)(dest - destBytes);
 0131                return OperationStatus.NeedMoreData;
 132            }
 133        }
 134
 135#if NET
 136        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 137        [CompExactlyDependsOn(typeof(Avx512BW))]
 138        [CompExactlyDependsOn(typeof(Avx512Vbmi))]
 139        private static unsafe void Avx512Encode<TBase64Encoder, T>(TBase64Encoder encoder, ref byte* srcBytes, ref T* de
 140            where TBase64Encoder : IBase64Encoder<T>
 141            where T : unmanaged
 142        {
 143            // Reference for VBMI implementation : https://github.com/WojciechMula/base64simd/tree/master/encode
 144            // If we have AVX512 support, pick off 48 bytes at a time for as long as we can.
 145            // But because we read 64 bytes at a time, ensure we have enough room to do a
 146            // full 64-byte read without segfaulting.
 147
 0148            byte* src = srcBytes;
 0149            T* dest = destBytes;
 150
 151            // The JIT won't hoist these "constants", so help it
 0152            Vector512<sbyte> shuffleVecVbmi = Vector512.Create(
 0153                0x01020001, 0x04050304, 0x07080607, 0x0a0b090a,
 0154                0x0d0e0c0d, 0x10110f10, 0x13141213, 0x16171516,
 0155                0x191a1819, 0x1c1d1b1c, 0x1f201e1f, 0x22232122,
 0156                0x25262425, 0x28292728, 0x2b2c2a2b, 0x2e2f2d2e).AsSByte();
 0157            Vector512<sbyte> vbmiLookup = Vector512.Create(encoder.EncodingMap).AsSByte();
 158
 0159            Vector512<ushort> maskAC = Vector512.Create((uint)0x0fc0fc00).AsUInt16();
 0160            Vector512<uint> maskBB = Vector512.Create((uint)0x3f003f00);
 0161            Vector512<ushort> shiftAC = Vector512.Create((uint)0x0006000a).AsUInt16();
 0162            Vector512<ushort> shiftBB = Vector512.Create((uint)0x00080004).AsUInt16();
 163
 0164            AssertRead<Vector256<sbyte>>(src, srcStart, sourceLength);
 165
 166            // This algorithm requires AVX512VBMI support.
 167            // Vbmi was first introduced in CannonLake and is available from IceLake on.
 168
 169            // str = [...|PONM|LKJI|HGFE|DCBA]
 0170            Vector512<sbyte> str = Vector512.Load(src).AsSByte();
 171
 0172            while (true)
 173            {
 174                // Step 1 : Split 48 bytes into 64 bytes with each byte using 6-bits from input
 175                // str = [...|KLJK|HIGH|EFDE|BCAB]
 0176                str = Avx512Vbmi.PermuteVar64x8(str, shuffleVecVbmi);
 177
 178                // TO-DO- This can be achieved faster with multishift
 179                // Consider the first 4 bytes - BCAB
 180                // temp1    = [...|0000cccc|cc000000|aaaaaa00|00000000]
 0181                Vector512<ushort> temp1 = (str.AsUInt16() & maskAC);
 182
 183                // temp2    = [...|00000000|00cccccc|00000000|00aaaaaa]
 0184                Vector512<ushort> temp2 = Avx512BW.ShiftRightLogicalVariable(temp1, shiftAC).AsUInt16();
 185
 186                // temp3    = [...|ccdddddd|00000000|aabbbbbb|cccc0000]
 0187                Vector512<ushort> temp3 = Avx512BW.ShiftLeftLogicalVariable(str.AsUInt16(), shiftBB).AsUInt16();
 188
 189                // str      = [...|00dddddd|00cccccc|00bbbbbb|00aaaaaa]
 0190                str = Vector512.ConditionalSelect(maskBB, temp3.AsUInt32(), temp2.AsUInt32()).AsSByte();
 191
 192                // Step 2: Now we have the indices calculated. Next step is to use these indices to translate.
 0193                str = Avx512Vbmi.PermuteVar64x8(vbmiLookup, str);
 194
 0195                encoder.StoreVector512ToDestination(dest, destStart, destLength, str.AsByte());
 196
 0197                src += 48;
 0198                dest += 64;
 199
 0200                if (src > srcEnd)
 201                    break;
 202
 0203                AssertRead<Vector512<sbyte>>(src, srcStart, sourceLength);
 0204                str = Vector512.Load(src).AsSByte();
 205            }
 206
 0207            srcBytes = src;
 0208            destBytes = dest;
 0209        }
 210
 211        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 212        [CompExactlyDependsOn(typeof(Avx2))]
 213        private static unsafe void Avx2Encode<TBase64Encoder, T>(TBase64Encoder encoder, ref byte* srcBytes, ref T* dest
 214            where TBase64Encoder : IBase64Encoder<T>
 215            where T : unmanaged
 216        {
 217            // If we have AVX2 support, pick off 24 bytes at a time for as long as we can.
 218            // But because we read 32 bytes at a time, ensure we have enough room to do a
 219            // full 32-byte read without segfaulting.
 220
 221            // translation from SSSE3 into AVX2 of procedure
 222            // This one works with shifted (4 bytes) input in order to
 223            // be able to work efficiently in the 2 128-bit lanes
 224
 225            // srcBytes, bytes MSB to LSB:
 226            // 0 0 0 0 x w v u t s r q p o n m
 227            // l k j i h g f e d c b a 0 0 0 0
 228
 229            // The JIT won't hoist these "constants", so help it
 0230            Vector256<sbyte> shuffleVec = Vector256.Create(
 0231                5, 4, 6, 5,
 0232                8, 7, 9, 8,
 0233                11, 10, 12, 11,
 0234                14, 13, 15, 14,
 0235                1, 0, 2, 1,
 0236                4, 3, 5, 4,
 0237                7, 6, 8, 7,
 0238                10, 9, 11, 10);
 239
 0240            Vector256<sbyte> lut = Vector256.Create(
 0241                65, 71, -4, -4,
 0242                -4, -4, -4, -4,
 0243                -4, -4, -4, -4,
 0244                encoder.Avx2LutChar62, encoder.Avx2LutChar63, 0, 0,
 0245                65, 71, -4, -4,
 0246                -4, -4, -4, -4,
 0247                -4, -4, -4, -4,
 0248                encoder.Avx2LutChar62, encoder.Avx2LutChar63, 0, 0);
 249
 0250            Vector256<sbyte> maskAC = Vector256.Create(0x0fc0fc00).AsSByte();
 0251            Vector256<sbyte> maskBB = Vector256.Create(0x003f03f0).AsSByte();
 0252            Vector256<ushort> shiftAC = Vector256.Create(0x04000040).AsUInt16();
 0253            Vector256<short> shiftBB = Vector256.Create(0x01000010).AsInt16();
 0254            Vector256<byte> const51 = Vector256.Create((byte)51);
 0255            Vector256<sbyte> const25 = Vector256.Create((sbyte)25);
 256
 0257            byte* src = srcBytes;
 0258            T* dest = destBytes;
 259
 260            // first load is done at c-0 not to get a segfault
 0261            AssertRead<Vector256<sbyte>>(src, srcStart, sourceLength);
 0262            Vector256<sbyte> str = Avx.LoadVector256(src).AsSByte();
 263
 264            // shift by 4 bytes, as required by Reshuffle
 0265            str = Avx2.PermuteVar8x32(str.AsInt32(), Vector256.Create(
 0266                0, 0, 0, 0,
 0267                0, 0, 0, 0,
 0268                1, 0, 0, 0,
 0269                2, 0, 0, 0,
 0270                3, 0, 0, 0,
 0271                4, 0, 0, 0,
 0272                5, 0, 0, 0,
 0273                6, 0, 0, 0).AsInt32()).AsSByte();
 274
 275            // Next loads are done at src-4, as required by Reshuffle, so shift it once
 0276            src -= 4;
 277
 0278            while (true)
 279            {
 280                // Reshuffle
 0281                str = Avx2.Shuffle(str, shuffleVec);
 282                // str, bytes MSB to LSB:
 283                // w x v w
 284                // t u s t
 285                // q r p q
 286                // n o m n
 287                // k l j k
 288                // h i g h
 289                // e f d e
 290                // b c a b
 291
 0292                Vector256<sbyte> t0 = str & maskAC;
 293                // bits, upper case are most significant bits, lower case are least significant bits.
 294                // 0000wwww XX000000 VVVVVV00 00000000
 295                // 0000tttt UU000000 SSSSSS00 00000000
 296                // 0000qqqq RR000000 PPPPPP00 00000000
 297                // 0000nnnn OO000000 MMMMMM00 00000000
 298                // 0000kkkk LL000000 JJJJJJ00 00000000
 299                // 0000hhhh II000000 GGGGGG00 00000000
 300                // 0000eeee FF000000 DDDDDD00 00000000
 301                // 0000bbbb CC000000 AAAAAA00 00000000
 302
 0303                Vector256<sbyte> t2 = str & maskBB;
 304                // 00000000 00xxxxxx 000000vv WWWW0000
 305                // 00000000 00uuuuuu 000000ss TTTT0000
 306                // 00000000 00rrrrrr 000000pp QQQQ0000
 307                // 00000000 00oooooo 000000mm NNNN0000
 308                // 00000000 00llllll 000000jj KKKK0000
 309                // 00000000 00iiiiii 000000gg HHHH0000
 310                // 00000000 00ffffff 000000dd EEEE0000
 311                // 00000000 00cccccc 000000aa BBBB0000
 312
 0313                Vector256<ushort> t1 = Avx2.MultiplyHigh(t0.AsUInt16(), shiftAC);
 314                // 00000000 00wwwwXX 00000000 00VVVVVV
 315                // 00000000 00ttttUU 00000000 00SSSSSS
 316                // 00000000 00qqqqRR 00000000 00PPPPPP
 317                // 00000000 00nnnnOO 00000000 00MMMMMM
 318                // 00000000 00kkkkLL 00000000 00JJJJJJ
 319                // 00000000 00hhhhII 00000000 00GGGGGG
 320                // 00000000 00eeeeFF 00000000 00DDDDDD
 321                // 00000000 00bbbbCC 00000000 00AAAAAA
 322
 0323                Vector256<short> t3 = t2.AsInt16() * shiftBB;
 324                // 00xxxxxx 00000000 00vvWWWW 00000000
 325                // 00uuuuuu 00000000 00ssTTTT 00000000
 326                // 00rrrrrr 00000000 00ppQQQQ 00000000
 327                // 00oooooo 00000000 00mmNNNN 00000000
 328                // 00llllll 00000000 00jjKKKK 00000000
 329                // 00iiiiii 00000000 00ggHHHH 00000000
 330                // 00ffffff 00000000 00ddEEEE 00000000
 331                // 00cccccc 00000000 00aaBBBB 00000000
 332
 0333                str = t1.AsSByte() | t3.AsSByte();
 334                // 00xxxxxx 00wwwwXX 00vvWWWW 00VVVVVV
 335                // 00uuuuuu 00ttttUU 00ssTTTT 00SSSSSS
 336                // 00rrrrrr 00qqqqRR 00ppQQQQ 00PPPPPP
 337                // 00oooooo 00nnnnOO 00mmNNNN 00MMMMMM
 338                // 00llllll 00kkkkLL 00jjKKKK 00JJJJJJ
 339                // 00iiiiii 00hhhhII 00ggHHHH 00GGGGGG
 340                // 00ffffff 00eeeeFF 00ddEEEE 00DDDDDD
 341                // 00cccccc 00bbbbCC 00aaBBBB 00AAAAAA
 342
 343                // Translation
 344                // LUT contains Absolute offset for all ranges:
 345                // Translate values 0..63 to the Base64 alphabet. There are five sets:
 346                // #  From      To         Abs    Index  Characters
 347                // 0  [0..25]   [65..90]   +65        0  ABCDEFGHIJKLMNOPQRSTUVWXYZ
 348                // 1  [26..51]  [97..122]  +71        1  abcdefghijklmnopqrstuvwxyz
 349                // 2  [52..61]  [48..57]    -4  [2..11]  0123456789
 350                // 3  [62]      [43]       -19       12  +
 351                // 4  [63]      [47]       -16       13  /
 352
 353                // Create LUT indices from input:
 354                // the index for range #0 is right, others are 1 less than expected:
 0355                Vector256<byte> indices = Avx2.SubtractSaturate(str.AsByte(), const51);
 356
 357                // mask is 0xFF (-1) for range #[1..4] and 0x00 for range #0:
 0358                Vector256<sbyte> mask = Avx2.CompareGreaterThan(str, const25);
 359
 360                // subtract -1, so add 1 to indices for range #[1..4], All indices are now correct:
 0361                Vector256<sbyte> tmp = indices.AsSByte() - mask;
 362
 363                // Add offsets to input values:
 0364                str += Avx2.Shuffle(lut, tmp);
 365
 0366                encoder.StoreVector256ToDestination(dest, destStart, destLength, str.AsByte());
 367
 0368                src += 24;
 0369                dest += 32;
 370
 0371                if (src > srcEnd)
 372                    break;
 373
 374                // Load at src-4, as required by Reshuffle (already shifted by -4)
 0375                AssertRead<Vector256<sbyte>>(src, srcStart, sourceLength);
 0376                str = Avx.LoadVector256(src).AsSByte();
 377            }
 378
 0379            srcBytes = src + 4;
 0380            destBytes = dest;
 0381        }
 382
 383        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 384        [CompExactlyDependsOn(typeof(AdvSimd.Arm64))]
 385        private static unsafe void AdvSimdEncode<TBase64Encoder, T>(TBase64Encoder encoder, ref byte* srcBytes, ref T* d
 386            where TBase64Encoder : IBase64Encoder<T>
 387            where T : unmanaged
 388        {
 389            // C# implementation of https://github.com/aklomp/base64/blob/3a5add8652076612a8407627a42c768736a4263f/lib/a
 390            Vector128<byte> str1;
 391            Vector128<byte> str2;
 392            Vector128<byte> str3;
 393            Vector128<byte> res1;
 394            Vector128<byte> res2;
 395            Vector128<byte> res3;
 396            Vector128<byte> res4;
 397            Vector128<byte> tblEnc1 = Vector128.Create("ABCDEFGHIJKLMNOP"u8).AsByte();
 398            Vector128<byte> tblEnc2 = Vector128.Create("QRSTUVWXYZabcdef"u8).AsByte();
 399            Vector128<byte> tblEnc3 = Vector128.Create("ghijklmnopqrstuv"u8).AsByte();
 400            Vector128<byte> tblEnc4 = Vector128.Create(encoder.AdvSimdLut4).AsByte();
 401            byte* src = srcBytes;
 402            T* dest = destBytes;
 403
 404            // If we have Neon support, pick off 48 bytes at a time for as long as we can.
 405            do
 406            {
 407                // Load 48 bytes and deinterleave:
 408                AssertRead<Vector128<byte>>(src, srcStart, sourceLength);
 409                (str1, str2, str3) = AdvSimd.Arm64.Load3xVector128AndUnzip(src);
 410
 411                // Divide bits of three input bytes over four output bytes:
 412                res1 = str1 >>> 2;
 413                res2 = str2 >>> 4;
 414                res3 = str3 >>> 6;
 415                res2 = AdvSimd.ShiftLeftAndInsert(res2, str1, 4);
 416                res3 = AdvSimd.ShiftLeftAndInsert(res3, str2, 2);
 417
 418                // Clear top two bits:
 419                res2 &= AdvSimd.DuplicateToVector128((byte)0x3F);
 420                res3 &= AdvSimd.DuplicateToVector128((byte)0x3F);
 421                res4 = str3 & AdvSimd.DuplicateToVector128((byte)0x3F);
 422
 423                // The bits have now been shifted to the right locations;
 424                // translate their values 0..63 to the Base64 alphabet.
 425                // Use a 64-byte table lookup:
 426                res1 = AdvSimd.Arm64.VectorTableLookup((tblEnc1, tblEnc2, tblEnc3, tblEnc4), res1);
 427                res2 = AdvSimd.Arm64.VectorTableLookup((tblEnc1, tblEnc2, tblEnc3, tblEnc4), res2);
 428                res3 = AdvSimd.Arm64.VectorTableLookup((tblEnc1, tblEnc2, tblEnc3, tblEnc4), res3);
 429                res4 = AdvSimd.Arm64.VectorTableLookup((tblEnc1, tblEnc2, tblEnc3, tblEnc4), res4);
 430
 431                // Interleave and store result:
 432                encoder.StoreArmVector128x4ToDestination(dest, destStart, destLength, res1, res2, res3, res4);
 433
 434                src += 48;
 435                dest += 64;
 436            } while (src <= srcEnd);
 437
 438            srcBytes = src;
 439            destBytes = dest;
 440        }
 441
 442        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 443        [CompExactlyDependsOn(typeof(Ssse3))]
 444        [CompExactlyDependsOn(typeof(AdvSimd.Arm64))]
 445        [CompExactlyDependsOn(typeof(PackedSimd))]
 446        private static unsafe void Vector128Encode<TBase64Encoder, T>(TBase64Encoder encoder, ref byte* srcBytes, ref T*
 447            where TBase64Encoder : IBase64Encoder<T>
 448            where T : unmanaged
 449        {
 450            // If we have SSSE3 support, pick off 12 bytes at a time for as long as we can.
 451            // But because we read 16 bytes at a time, ensure we have enough room to do a
 452            // full 16-byte read without segfaulting.
 453
 454            // srcBytes, bytes MSB to LSB:
 455            // 0 0 0 0 l k j i h g f e d c b a
 456
 457            // The JIT won't hoist these "constants", so help it
 458            Vector128<byte> shuffleVec = Vector128.Create(0x01020001, 0x04050304, 0x07080607, 0x0A0B090A).AsByte();
 0459            Vector128<byte> lut = Vector128.Create(0xFCFC4741, 0xFCFCFCFC, 0xFCFCFCFC, encoder.Ssse3AdvSimdLutE3).AsByte
 0460            Vector128<byte> maskAC = Vector128.Create(0x0fc0fc00).AsByte();
 0461            Vector128<byte> maskBB = Vector128.Create(0x003f03f0).AsByte();
 0462            Vector128<ushort> shiftAC = Vector128.Create(0x04000040).AsUInt16();
 0463            Vector128<short> shiftBB = Vector128.Create(0x01000010).AsInt16();
 0464            Vector128<byte> const51 = Vector128.Create((byte)51);
 0465            Vector128<sbyte> const25 = Vector128.Create((sbyte)25);
 0466            Vector128<byte> mask8F = Vector128.Create((byte)0x8F);
 467
 0468            byte* src = srcBytes;
 0469            T* dest = destBytes;
 470
 471            //while (remaining >= 16)
 472            do
 473            {
 0474                AssertRead<Vector128<sbyte>>(src, srcStart, sourceLength);
 0475                Vector128<byte> str = Vector128.LoadUnsafe(ref *src);
 476
 477                // Reshuffle
 0478                str = SimdShuffle(str, shuffleVec, mask8F);
 479                // str, bytes MSB to LSB:
 480                // k l j k
 481                // h i g h
 482                // e f d e
 483                // b c a b
 484
 0485                Vector128<byte> t0 = str & maskAC;
 486                // bits, upper case are most significant bits, lower case are least significant bits
 487                // 0000kkkk LL000000 JJJJJJ00 00000000
 488                // 0000hhhh II000000 GGGGGG00 00000000
 489                // 0000eeee FF000000 DDDDDD00 00000000
 490                // 0000bbbb CC000000 AAAAAA00 00000000
 491
 0492                Vector128<byte> t2 = str & maskBB;
 493                // 00000000 00llllll 000000jj KKKK0000
 494                // 00000000 00iiiiii 000000gg HHHH0000
 495                // 00000000 00ffffff 000000dd EEEE0000
 496                // 00000000 00cccccc 000000aa BBBB0000
 497
 498                Vector128<ushort> t1;
 0499                if (Ssse3.IsSupported)
 500                {
 0501                    t1 = Sse2.MultiplyHigh(t0.AsUInt16(), shiftAC);
 502                }
 503                else if (AdvSimd.Arm64.IsSupported)
 504                {
 505                    Vector128<ushort> odd = Vector128.ShiftRightLogical(AdvSimd.Arm64.UnzipOdd(t0.AsUInt16(), t0.AsUInt1
 506                    Vector128<ushort> even = Vector128.ShiftRightLogical(AdvSimd.Arm64.UnzipEven(t0.AsUInt16(), t0.AsUIn
 507                    t1 = AdvSimd.Arm64.ZipLow(even, odd);
 508                }
 509                else if (PackedSimd.IsSupported)
 510                {
 511                    // MultiplyHigh by {2^6, 2^10} is a right shift of the even u16 lanes by 10 and the odd lanes by 6.
 512                    Vector128<ushort> shr6 = Vector128.ShiftRightLogical(t0.AsUInt16(), 6);
 513                    Vector128<ushort> shr10 = Vector128.ShiftRightLogical(t0.AsUInt16(), 10);
 514                    t1 = Vector128.ConditionalSelect(Vector128.Create(0x0000FFFFu).AsUInt16(), shr10, shr6);
 515                }
 516                else
 517                {
 518                    // We explicitly recheck each IsSupported query to ensure that the trimmer can see which paths are l
 0519                    ThrowUnreachableException();
 520                    t1 = default;
 521                }
 522                // 00000000 00kkkkLL 00000000 00JJJJJJ
 523                // 00000000 00hhhhII 00000000 00GGGGGG
 524                // 00000000 00eeeeFF 00000000 00DDDDDD
 525                // 00000000 00bbbbCC 00000000 00AAAAAA
 526
 0527                Vector128<short> t3 = t2.AsInt16() * shiftBB;
 528                // 00llllll 00000000 00jjKKKK 00000000
 529                // 00iiiiii 00000000 00ggHHHH 00000000
 530                // 00ffffff 00000000 00ddEEEE 00000000
 531                // 00cccccc 00000000 00aaBBBB 00000000
 532
 0533                str = t1.AsByte() | t3.AsByte();
 534                // 00llllll 00kkkkLL 00jjKKKK 00JJJJJJ
 535                // 00iiiiii 00hhhhII 00ggHHHH 00GGGGGG
 536                // 00ffffff 00eeeeFF 00ddEEEE 00DDDDDD
 537                // 00cccccc 00bbbbCC 00aaBBBB 00AAAAAA
 538
 539                // Translation
 540                // LUT contains Absolute offset for all ranges:
 541                // Translate values 0..63 to the Base64 alphabet. There are five sets:
 542                // #  From      To         Abs    Index  Characters
 543                // 0  [0..25]   [65..90]   +65        0  ABCDEFGHIJKLMNOPQRSTUVWXYZ
 544                // 1  [26..51]  [97..122]  +71        1  abcdefghijklmnopqrstuvwxyz
 545                // 2  [52..61]  [48..57]    -4  [2..11]  0123456789
 546                // 3  [62]      [43]       -19       12  +
 547                // 4  [63]      [47]       -16       13  /
 548
 549                // Create LUT indices from input:
 550                // the index for range #0 is right, others are 1 less than expected:
 551                Vector128<byte> indices;
 0552                if (Ssse3.IsSupported)
 553                {
 0554                    indices = Sse2.SubtractSaturate(str.AsByte(), const51);
 555                }
 556                else if (AdvSimd.IsSupported)
 557                {
 558                    indices = AdvSimd.SubtractSaturate(str.AsByte(), const51);
 559                }
 560                else if (PackedSimd.IsSupported)
 561                {
 562                    indices = PackedSimd.SubtractSaturate(str.AsByte(), const51);
 563                }
 564                else
 565                {
 566                    // We explicitly recheck each IsSupported query to ensure that the trimmer can see which paths are l
 0567                    ThrowUnreachableException();
 568                    indices = default;
 569                }
 570
 571                // mask is 0xFF (-1) for range #[1..4] and 0x00 for range #0:
 0572                Vector128<sbyte> mask = Vector128.GreaterThan(str.AsSByte(), const25);
 573
 574                // subtract -1, so add 1 to indices for range #[1..4], All indices are now correct:
 0575                Vector128<sbyte> tmp = indices.AsSByte() - mask;
 576
 577                // Add offsets to input values:
 0578                str += SimdShuffle(lut, tmp.AsByte(), mask8F);
 579
 0580                encoder.StoreVector128ToDestination(dest, destStart, destLength, str);
 581
 0582                src += 12;
 0583                dest += 16;
 584            }
 0585            while (src <= srcEnd);
 586
 0587            srcBytes = src;
 0588            destBytes = dest;
 0589        }
 590#endif
 591
 592        internal static unsafe OperationStatus EncodeToUtf8InPlace<TBase64Encoder>(TBase64Encoder encoder, Span<byte> bu
 593            where TBase64Encoder : IBase64Encoder<byte>
 594        {
 0595            if (buffer.IsEmpty)
 596            {
 0597                bytesWritten = 0;
 0598                return OperationStatus.Done;
 599            }
 600
 0601            fixed (byte* bufferBytes = &MemoryMarshal.GetReference(buffer))
 602            {
 0603                int encodedLength = encoder.GetMaxEncodedLength(dataLength);
 0604                if (buffer.Length < encodedLength)
 605                {
 0606                    bytesWritten = 0;
 0607                    return OperationStatus.DestinationTooSmall;
 608                }
 609
 0610                int leftover = (int)((uint)dataLength % 3); // how many bytes after packs of 3
 611
 0612                uint destinationIndex = encoder.GetInPlaceDestinationLength(encodedLength, leftover);
 0613                uint sourceIndex = (uint)(dataLength - leftover);
 0614                ref byte encodingMap = ref MemoryMarshal.GetReference(encoder.EncodingMap);
 615
 616                // encode last pack to avoid conditional in the main loop
 0617                if (leftover != 0)
 618                {
 0619                    if (leftover == 1)
 620                    {
 0621                        encoder.EncodeOneOptionallyPadTwo(bufferBytes + sourceIndex, bufferBytes + destinationIndex, ref
 622                    }
 623                    else
 624                    {
 0625                        encoder.EncodeTwoOptionallyPadOne(bufferBytes + sourceIndex, bufferBytes + destinationIndex, ref
 626                    }
 627
 0628                    destinationIndex -= 4;
 629                }
 630
 0631                sourceIndex -= 3;
 0632                while ((int)sourceIndex >= 0)
 633                {
 0634                    uint result = Encode(bufferBytes + sourceIndex, ref encodingMap);
 0635                    Unsafe.WriteUnaligned(bufferBytes + destinationIndex, result);
 0636                    destinationIndex -= 4;
 0637                    sourceIndex -= 3;
 638                }
 639
 0640                bytesWritten = encodedLength;
 0641                return OperationStatus.Done;
 642            }
 643        }
 644
 645        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 646        private static unsafe uint Encode(byte* threeBytes, ref byte encodingMap)
 647        {
 0648            uint t0 = threeBytes[0];
 0649            uint t1 = threeBytes[1];
 0650            uint t2 = threeBytes[2];
 651
 0652            uint i = (t0 << 16) | (t1 << 8) | t2;
 653
 0654            uint i0 = Unsafe.Add(ref encodingMap, (IntPtr)(i >> 18));
 0655            uint i1 = Unsafe.Add(ref encodingMap, (IntPtr)((i >> 12) & 0x3F));
 0656            uint i2 = Unsafe.Add(ref encodingMap, (IntPtr)((i >> 6) & 0x3F));
 0657            uint i3 = Unsafe.Add(ref encodingMap, (IntPtr)(i & 0x3F));
 658
 0659            return ConstructResult(i0, i1, i2, i3);
 660        }
 661
 662        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 663        private static uint ConstructResult(uint i0, uint i1, uint i2, uint i3)
 664        {
 665            if (BitConverter.IsLittleEndian)
 666            {
 0667                return i0 | (i1 << 8) | (i2 << 16) | (i3 << 24);
 668            }
 669            else
 670            {
 671                return (i0 << 24) | (i1 << 16) | (i2 << 8) | i3;
 672            }
 673        }
 674
 675        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 676        public static unsafe void EncodeOneOptionallyPadTwo(byte* oneByte, ushort* dest, ref byte encodingMap)
 677        {
 678            uint t0 = oneByte[0];
 679
 0680            uint i = t0 << 8;
 681
 0682            uint i0 = Unsafe.Add(ref encodingMap, (IntPtr)(i >> 10));
 0683            uint i1 = Unsafe.Add(ref encodingMap, (IntPtr)((i >> 4) & 0x3F));
 684
 685            uint result;
 686
 0687            if (BitConverter.IsLittleEndian)
 688            {
 0689                result = (i0 | (i1 << 16));
 690            }
 691            else
 692            {
 693                result = ((i0 << 16) | i1);
 694            }
 695
 0696            Unsafe.WriteUnaligned(dest, result);
 0697        }
 698
 699        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 700        public static unsafe void EncodeTwoOptionallyPadOne(byte* twoBytes, ushort* dest, ref byte encodingMap)
 701        {
 0702            uint t0 = twoBytes[0];
 0703            uint t1 = twoBytes[1];
 704
 0705            uint i = (t0 << 16) | (t1 << 8);
 706
 0707            ushort i0 = Unsafe.Add(ref encodingMap, (IntPtr)(i >> 18));
 0708            ushort i1 = Unsafe.Add(ref encodingMap, (IntPtr)((i >> 12) & 0x3F));
 0709            ushort i2 = Unsafe.Add(ref encodingMap, (IntPtr)((i >> 6) & 0x3F));
 710
 0711            dest[0] = i0;
 0712            dest[1] = i1;
 0713            dest[2] = i2;
 0714        }
 715
 716        internal const uint EncodingPad = '='; // '=', for padding
 717
 718        internal const int MaximumEncodeLength = (int.MaxValue / 4) * 3; // 1610612733
 719
 720        internal readonly struct Base64EncoderByte : IBase64Encoder<byte>
 721        {
 0722            public ReadOnlySpan<byte> EncodingMap => "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"u
 723
 0724            public sbyte Avx2LutChar62 => -19;  // char '+' diff
 725
 0726            public sbyte Avx2LutChar63 => -16;   // char '/' diff
 727
 0728            public ReadOnlySpan<byte> AdvSimdLut4 => "wxyz0123456789+/"u8;
 729
 0730            public uint Ssse3AdvSimdLutE3 => 0x0000F0ED;
 731
 0732            public int IncrementPadTwo => 4;
 733
 0734            public int IncrementPadOne => 4;
 735
 736            [MethodImpl(MethodImplOptions.AggressiveInlining)]
 737            public int GetMaxSrcLength(int srcLength, int destLength) =>
 0738                srcLength <= MaximumEncodeLength && destLength >= Base64.GetMaxEncodedToUtf8Length(srcLength) ?
 0739                srcLength : (destLength >> 2) * 3;
 740
 0741            public uint GetInPlaceDestinationLength(int encodedLength, int _) => (uint)(encodedLength - 4);
 742
 0743            public int GetMaxEncodedLength(int srcLength) => Base64.GetMaxEncodedToUtf8Length(srcLength);
 744
 745            [MethodImpl(MethodImplOptions.AggressiveInlining)]
 746            public unsafe void EncodeOneOptionallyPadTwo(byte* oneByte, byte* dest, ref byte encodingMap)
 747            {
 0748                uint t0 = oneByte[0];
 749
 0750                uint i = t0 << 8;
 751
 0752                uint i0 = Unsafe.Add(ref encodingMap, (IntPtr)(i >> 10));
 0753                uint i1 = Unsafe.Add(ref encodingMap, (IntPtr)((i >> 4) & 0x3F));
 754
 0755                uint result = ConstructResult(i0, i1, EncodingPad, EncodingPad);
 0756                Unsafe.WriteUnaligned(dest, result);
 0757            }
 758
 759            [MethodImpl(MethodImplOptions.AggressiveInlining)]
 760            public unsafe void EncodeTwoOptionallyPadOne(byte* twoBytes, byte* dest, ref byte encodingMap)
 761            {
 0762                uint t0 = twoBytes[0];
 0763                uint t1 = twoBytes[1];
 764
 0765                uint i = (t0 << 16) | (t1 << 8);
 766
 0767                uint i0 = Unsafe.Add(ref encodingMap, (IntPtr)(i >> 18));
 0768                uint i1 = Unsafe.Add(ref encodingMap, (IntPtr)((i >> 12) & 0x3F));
 0769                uint i2 = Unsafe.Add(ref encodingMap, (IntPtr)((i >> 6) & 0x3F));
 770
 0771                uint result = ConstructResult(i0, i1, i2, EncodingPad);
 0772                Unsafe.WriteUnaligned(dest, result);
 0773            }
 774
 775#if NET
 776            [MethodImpl(MethodImplOptions.AggressiveInlining)]
 777            public unsafe void StoreVector512ToDestination(byte* dest, byte* destStart, int destLength, Vector512<byte> 
 778            {
 0779                AssertWrite<Vector512<sbyte>>(dest, destStart, destLength);
 0780                str.Store(dest);
 0781            }
 782
 783            [MethodImpl(MethodImplOptions.AggressiveInlining)]
 784            [CompExactlyDependsOn(typeof(Avx2))]
 785            public unsafe void StoreVector256ToDestination(byte* dest, byte* destStart, int destLength, Vector256<byte> 
 786            {
 0787                AssertWrite<Vector256<sbyte>>(dest, destStart, destLength);
 0788                Avx.Store(dest, str.AsByte());
 0789            }
 790
 791            [MethodImpl(MethodImplOptions.AggressiveInlining)]
 792            public unsafe void StoreVector128ToDestination(byte* dest, byte* destStart, int destLength, Vector128<byte> 
 793            {
 0794                AssertWrite<Vector128<sbyte>>(dest, destStart, destLength);
 0795                str.Store(dest);
 0796            }
 797
 798            [MethodImpl(MethodImplOptions.AggressiveInlining)]
 799            [CompExactlyDependsOn(typeof(AdvSimd.Arm64))]
 800            public unsafe void StoreArmVector128x4ToDestination(byte* dest, byte* destStart, int destLength,
 801                Vector128<byte> res1, Vector128<byte> res2, Vector128<byte> res3, Vector128<byte> res4)
 802            {
 0803                AssertWrite<Vector128<byte>>(dest, destStart, destLength);
 0804                AdvSimd.Arm64.StoreVectorAndZip(dest, (res1, res2, res3, res4));
 0805            }
 806#endif // NET
 807
 808            [MethodImpl(MethodImplOptions.AggressiveInlining)]
 809            public unsafe void EncodeThreeAndWrite(byte* threeBytes, byte* destination, ref byte encodingMap)
 810            {
 0811                uint result = Encode(threeBytes, ref encodingMap);
 0812                Unsafe.WriteUnaligned(destination, result);
 0813            }
 814        }
 815
 816        internal readonly struct Base64EncoderChar : IBase64Encoder<ushort>
 817        {
 0818            public ReadOnlySpan<byte> EncodingMap => default(Base64EncoderByte).EncodingMap;
 819
 0820            public sbyte Avx2LutChar62 => default(Base64EncoderByte).Avx2LutChar62;
 821
 0822            public sbyte Avx2LutChar63 => default(Base64EncoderByte).Avx2LutChar63;
 823
 0824            public ReadOnlySpan<byte> AdvSimdLut4 => default(Base64EncoderByte).AdvSimdLut4;
 825
 0826            public uint Ssse3AdvSimdLutE3 => default(Base64EncoderByte).Ssse3AdvSimdLutE3;
 827
 0828            public int IncrementPadTwo => default(Base64EncoderByte).IncrementPadTwo;
 829
 0830            public int IncrementPadOne => default(Base64EncoderByte).IncrementPadOne;
 831
 832            public int GetMaxSrcLength(int srcLength, int destLength) =>
 0833                default(Base64EncoderByte).GetMaxSrcLength(srcLength, destLength);
 834
 0835            public uint GetInPlaceDestinationLength(int encodedLength, int _) => 0; // not used for char encoding
 836
 0837            public int GetMaxEncodedLength(int _) => 0;  // not used for char encoding
 838
 839            [MethodImpl(MethodImplOptions.AggressiveInlining)]
 840            public unsafe void EncodeOneOptionallyPadTwo(byte* oneByte, ushort* dest, ref byte encodingMap)
 841            {
 0842                Base64Helper.EncodeOneOptionallyPadTwo(oneByte, dest, ref encodingMap);
 0843                dest[2] = (ushort)EncodingPad;
 0844                dest[3] = (ushort)EncodingPad;
 0845            }
 846
 847            [MethodImpl(MethodImplOptions.AggressiveInlining)]
 848            public unsafe void EncodeTwoOptionallyPadOne(byte* twoBytes, ushort* dest, ref byte encodingMap)
 849            {
 0850                Base64Helper.EncodeTwoOptionallyPadOne(twoBytes, dest, ref encodingMap);
 0851                dest[3] = (ushort)EncodingPad;
 0852            }
 853
 854#if NET
 855            [MethodImpl(MethodImplOptions.AggressiveInlining)]
 856            public unsafe void StoreVector512ToDestination(ushort* dest, ushort* destStart, int destLength, Vector512<by
 857            {
 0858                AssertWrite<Vector512<short>>(dest, destStart, destLength);
 0859                (Vector512<ushort> utf16LowVector, Vector512<ushort> utf16HighVector) = Vector512.Widen(str);
 0860                utf16LowVector.Store(dest);
 0861                utf16HighVector.Store(dest + 32);
 0862            }
 863
 864            [MethodImpl(MethodImplOptions.AggressiveInlining)]
 865            public unsafe void StoreVector256ToDestination(ushort* dest, ushort* destStart, int destLength, Vector256<by
 866            {
 0867                AssertWrite<Vector256<short>>(dest, destStart, destLength);
 0868                (Vector256<ushort> utf16LowVector, Vector256<ushort> utf16HighVector) = Vector256.Widen(str);
 0869                utf16LowVector.Store(dest);
 0870                utf16HighVector.Store(dest + 16);
 0871            }
 872
 873            [MethodImpl(MethodImplOptions.AggressiveInlining)]
 874            public unsafe void StoreVector128ToDestination(ushort* dest, ushort* destStart, int destLength, Vector128<by
 875            {
 0876                AssertWrite<Vector128<short>>(dest, destStart, destLength);
 0877                (Vector128<ushort> utf16LowVector, Vector128<ushort> utf16HighVector) = Vector128.Widen(str);
 0878                utf16LowVector.Store(dest);
 0879                utf16HighVector.Store(dest + 8);
 0880            }
 881
 882            [MethodImpl(MethodImplOptions.AggressiveInlining)]
 883            [CompExactlyDependsOn(typeof(AdvSimd.Arm64))]
 884            public unsafe void StoreArmVector128x4ToDestination(ushort* dest, ushort* destStart, int destLength,
 885                Vector128<byte> res1, Vector128<byte> res2, Vector128<byte> res3, Vector128<byte> res4)
 886            {
 0887                AssertWrite<Vector128<short>>(dest, destStart, destLength);
 0888                (Vector128<ushort> utf16LowVector1, Vector128<ushort> utf16HighVector1) = Vector128.Widen(res1);
 0889                (Vector128<ushort> utf16LowVector2, Vector128<ushort> utf16HighVector2) = Vector128.Widen(res2);
 0890                (Vector128<ushort> utf16LowVector3, Vector128<ushort> utf16HighVector3) = Vector128.Widen(res3);
 0891                (Vector128<ushort> utf16LowVector4, Vector128<ushort> utf16HighVector4) = Vector128.Widen(res4);
 0892                AdvSimd.Arm64.StoreVectorAndZip(dest, (utf16LowVector1, utf16LowVector2, utf16LowVector3, utf16LowVector
 0893                AdvSimd.Arm64.StoreVectorAndZip(dest + 32, (utf16HighVector1, utf16HighVector2, utf16HighVector3, utf16H
 0894            }
 895#endif // NET
 896
 897            [MethodImpl(MethodImplOptions.AggressiveInlining)]
 898            public unsafe void EncodeThreeAndWrite(byte* threeBytes, ushort* destination, ref byte encodingMap)
 899            {
 900                uint t0 = threeBytes[0];
 0901                uint t1 = threeBytes[1];
 0902                uint t2 = threeBytes[2];
 903
 0904                uint i = (t0 << 16) | (t1 << 8) | t2;
 905
 0906                ulong i0 = Unsafe.Add(ref encodingMap, (IntPtr)(i >> 18));
 0907                ulong i1 = Unsafe.Add(ref encodingMap, (IntPtr)((i >> 12) & 0x3F));
 0908                ulong i2 = Unsafe.Add(ref encodingMap, (IntPtr)((i >> 6) & 0x3F));
 0909                ulong i3 = Unsafe.Add(ref encodingMap, (IntPtr)(i & 0x3F));
 910
 911                ulong result;
 0912                if (BitConverter.IsLittleEndian)
 913                {
 0914                    result = i0 | (i1 << 16) | (i2 << 32) | (i3 << 48);
 915                }
 916                else
 917                {
 918                    result = (i0 << 48) | (i1 << 32) | (i2 << 16) | i3;
 919                }
 920
 0921                Unsafe.WriteUnaligned(destination, result);
 0922            }
 923        }
 924    }
 925}
 926

https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/src/libraries/System.Private.CoreLib/src/System/Buffers/Text/Base64Helper/Base64Helper.cs

#LineLine coverage
 1// Licensed to the .NET Foundation under one or more agreements.
 2// The .NET Foundation licenses this file to you under the MIT license.
 3
 4using System.Diagnostics;
 5using System.Diagnostics.CodeAnalysis;
 6using System.Runtime.CompilerServices;
 7#if NET
 8using System.Runtime.Intrinsics;
 9#endif
 10
 11namespace System.Buffers.Text
 12{
 13    internal static partial class Base64Helper
 14    {
 15        [Conditional("DEBUG")]
 16        internal static unsafe void AssertRead<TVector>(byte* src, byte* srcStart, int srcLength)
 17        {
 018            int vectorElements = sizeof(TVector);
 019            byte* readEnd = src + vectorElements;
 020            byte* srcEnd = srcStart + srcLength;
 21
 022            if (readEnd > srcEnd)
 23            {
 024                int srcIndex = (int)(src - srcStart);
 025                Debug.Fail($"Read for {typeof(TVector)} is not within safe bounds. srcIndex: {srcIndex}, srcLength: {src
 26            }
 027        }
 28
 29        [Conditional("DEBUG")]
 30        internal static unsafe void AssertWrite<TVector>(byte* dest, byte* destStart, int destLength)
 31        {
 032            int vectorElements = sizeof(TVector);
 033            byte* writeEnd = dest + vectorElements;
 034            byte* destEnd = destStart + destLength;
 35
 036            if (writeEnd > destEnd)
 37            {
 038                int destIndex = (int)(dest - destStart);
 039                Debug.Fail($"Write for {typeof(TVector)} is not within safe bounds. destIndex: {destIndex}, destLength: 
 40            }
 041        }
 42
 43        [Conditional("DEBUG")]
 44        internal static unsafe void AssertRead<TVector>(ushort* src, ushort* srcStart, int srcLength)
 45        {
 046            int vectorElements = sizeof(TVector);
 047            ushort* readEnd = src + vectorElements;
 048            ushort* srcEnd = srcStart + srcLength;
 49
 050            if (readEnd > srcEnd)
 51            {
 052                int srcIndex = (int)(src - srcStart);
 053                Debug.Fail($"Read for {typeof(TVector)} is not within safe bounds. srcIndex: {srcIndex}, srcLength: {src
 54            }
 055        }
 56
 57        [Conditional("DEBUG")]
 58        internal static unsafe void AssertWrite<TVector>(ushort* dest, ushort* destStart, int destLength)
 59        {
 060            int vectorElements = sizeof(TVector);
 061            ushort* writeEnd = dest + vectorElements;
 062            ushort* destEnd = destStart + destLength;
 63
 064            if (writeEnd > destEnd)
 65            {
 066                int destIndex = (int)(dest - destStart);
 067                Debug.Fail($"Write for {typeof(TVector)} is not within safe bounds. destIndex: {destIndex}, destLength: 
 68            }
 069        }
 70
 71        [DoesNotReturn]
 72        internal static void ThrowUnreachableException()
 73        {
 74#if NET
 075            throw new UnreachableException();
 76#else
 77            throw new Exception("Unreachable");
 78#endif
 79        }
 80
 81        internal interface IBase64Encoder<T> where T : unmanaged
 82        {
 83            ReadOnlySpan<byte> EncodingMap { get; }
 84            sbyte Avx2LutChar62 { get; }
 85            sbyte Avx2LutChar63 { get; }
 86            ReadOnlySpan<byte> AdvSimdLut4 { get; }
 87            uint Ssse3AdvSimdLutE3 { get; }
 88            int GetMaxSrcLength(int srcLength, int destLength);
 89            int GetMaxEncodedLength(int srcLength);
 90            uint GetInPlaceDestinationLength(int encodedLength, int leftOver);
 91            unsafe void EncodeOneOptionallyPadTwo(byte* oneByte, T* dest, ref byte encodingMap);
 92            unsafe void EncodeTwoOptionallyPadOne(byte* oneByte, T* dest, ref byte encodingMap);
 93            unsafe void EncodeThreeAndWrite(byte* threeBytes, T* destination, ref byte encodingMap);
 94            int IncrementPadTwo { get; }
 95            int IncrementPadOne { get; }
 96#if NET
 97            unsafe void StoreVector512ToDestination(T* dest, T* destStart, int destLength, Vector512<byte> str);
 98            unsafe void StoreVector256ToDestination(T* dest, T* destStart, int destLength, Vector256<byte> str);
 99            unsafe void StoreVector128ToDestination(T* dest, T* destStart, int destLength, Vector128<byte> str);
 100            unsafe void StoreArmVector128x4ToDestination(T* dest, T* destStart, int destLength, Vector128<byte> res1,
 101                Vector128<byte> res2, Vector128<byte> res3, Vector128<byte> res4);
 102#endif // NET
 103        }
 104
 105        internal interface IBase64Decoder<T> where T : unmanaged
 106        {
 107            ReadOnlySpan<sbyte> DecodingMap { get; }
 108            ReadOnlySpan<uint> VbmiLookup0 { get; }
 109            ReadOnlySpan<uint> VbmiLookup1 { get; }
 110            ReadOnlySpan<sbyte> Avx2LutHigh { get; }
 111            ReadOnlySpan<sbyte> Avx2LutLow { get; }
 112            ReadOnlySpan<sbyte> Avx2LutShift { get; }
 113            byte MaskSlashOrUnderscore { get; }
 114            ReadOnlySpan<int> Vector128LutHigh { get; }
 115            ReadOnlySpan<int> Vector128LutLow { get; }
 116            ReadOnlySpan<uint> Vector128LutShift { get; }
 117            ReadOnlySpan<uint> AdvSimdLutOne3 { get; }
 118            uint AdvSimdLutTwo3Uint1 { get; }
 119            int SrcLength(bool isFinalBlock, int sourceLength);
 120            int GetMaxDecodedLength(int sourceLength);
 121            bool IsInvalidLength(int bufferLength);
 122            bool IsValidPadding(uint padChar);
 123#if NET
 124            bool TryDecode128Core(
 125                Vector128<byte> str,
 126                Vector128<byte> hiNibbles,
 127                Vector128<byte> maskSlashOrUnderscore,
 128                Vector128<byte> mask8F,
 129                Vector128<byte> lutLow,
 130                Vector128<byte> lutHigh,
 131                Vector128<sbyte> lutShift,
 132                Vector128<byte> shiftForUnderscore,
 133                out Vector128<byte> result);
 134            bool TryDecode256Core(
 135                Vector256<sbyte> str,
 136                Vector256<sbyte> hiNibbles,
 137                Vector256<sbyte> maskSlashOrUnderscore,
 138                Vector256<sbyte> lutLow,
 139                Vector256<sbyte> lutHigh,
 140                Vector256<sbyte> lutShift,
 141                Vector256<sbyte> shiftForUnderscore,
 142                out Vector256<sbyte> result);
 143            unsafe bool TryLoadVector512(T* src, T* srcStart, int sourceLength, out Vector512<sbyte> str);
 144            unsafe bool TryLoadAvxVector256(T* src, T* srcStart, int sourceLength, out Vector256<sbyte> str);
 145            unsafe bool TryLoadVector128(T* src, T* srcStart, int sourceLength, out Vector128<byte> str);
 146            unsafe bool TryLoadArmVector128x4(T* src, T* srcStart, int sourceLength,
 147                out Vector128<byte> str1, out Vector128<byte> str2, out Vector128<byte> str3, out Vector128<byte> str4);
 148#endif // NET
 149            unsafe int DecodeFourElements(T* source, ref sbyte decodingMap);
 150            unsafe int DecodeRemaining(T* srcEnd, ref sbyte decodingMap, long remaining, out uint t2, out uint t3);
 151            int IndexOfAnyExceptWhiteSpace(ReadOnlySpan<T> span);
 152            OperationStatus DecodeWithWhiteSpaceBlockwiseWrapper<TTBase64Decoder>(TTBase64Decoder decoder, ReadOnlySpan<
 153                Span<byte> bytes, ref int bytesConsumed, ref int bytesWritten, bool isFinalBlock = true)
 154                where TTBase64Decoder : IBase64Decoder<T>;
 155        }
 156    }
 157}
 158

https://raw.githubusercontent.com/dotnet/runtime/811a7eabb75c42db53440e8ba3f60c07511cfd1f/src/libraries/System.Private.CoreLib/src/System/Buffers/Text/Base64Helper/Base64ValidatorHelper.cs

#LineLine coverage
 1// Licensed to the .NET Foundation under one or more agreements.
 2// The .NET Foundation licenses this file to you under the MIT license.
 3
 4using System.Runtime.CompilerServices;
 5
 6namespace System.Buffers.Text
 7{
 8    internal static partial class Base64Helper
 9    {
 10        internal static bool IsValid<T, TBase64Validatable>(TBase64Validatable validatable, ReadOnlySpan<T> base64Text, 
 11            where TBase64Validatable : IBase64Validatable<T>
 12            where T : struct
 13        {
 014            int length = 0, paddingCount = 0;
 015            T lastChar = default;
 16
 017            if (!base64Text.IsEmpty)
 18            {
 19#if NET
 020                while (!base64Text.IsEmpty)
 21                {
 022                    int index = validatable.IndexOfAnyExcept(base64Text);
 023                    if ((uint)index >= (uint)base64Text.Length)
 24                    {
 025                        length += base64Text.Length;
 026                        lastChar = base64Text[base64Text.Length - 1];
 027                        break;
 28                    }
 29
 030                    length += index;
 031                    if (index != 0)
 32                    {
 033                        lastChar = base64Text[index - 1];
 34                    }
 35
 036                    T charToValidate = base64Text[index];
 037                    base64Text = base64Text.Slice(index + 1);
 38
 039                    if (validatable.IsWhiteSpace(charToValidate))
 40                    {
 41                        // It's common if there's whitespace for there to be multiple whitespace characters in a row,
 42                        // e.g. \r\n.  Optimize for that case by looping here.
 043                        while (!base64Text.IsEmpty && validatable.IsWhiteSpace(base64Text[0]))
 44                        {
 045                            base64Text = base64Text.Slice(1);
 46                        }
 047                        continue;
 48                    }
 49
 050                    if (!validatable.IsEncodingPad(charToValidate))
 51                    {
 52                        // Invalid char was found.
 53                        goto Fail;
 54                    }
 55
 56                    // Encoding pad found. Determine if padding is valid, then stop processing.
 057                    paddingCount = 1;
 058                    foreach (T charToValidateInPadding in base64Text)
 59                    {
 60#else
 61                for (int i = 0; i < base64Text.Length; i++)
 62                {
 63                    T charToValidate = base64Text[i];
 64                    int value = validatable.DecodeValue(charToValidate);
 65                    if (value == -2)
 66                    {
 67                        // Not an Ascii char
 68                        goto Fail;
 69                    }
 70
 71                    if (value >= 0) // valid char
 72                    {
 73                        length++;
 74                        lastChar = charToValidate;
 75                        continue;
 76                    }
 77                    if (validatable.IsWhiteSpace(charToValidate))
 78                    {
 79                        continue;
 80                    }
 81
 82                    if (!validatable.IsEncodingPad(charToValidate))
 83                    {
 84                        // Invalid char was found.
 85                        goto Fail;
 86                    }
 87
 88                    // Encoding pad found. Determine if padding is valid, then stop processing.
 89                    paddingCount = 1;
 90                    for (i++; i < base64Text.Length; i++)
 91                    {
 92                        T charToValidateInPadding = base64Text[i];
 93#endif
 094                        if (validatable.IsEncodingPad(charToValidateInPadding))
 95                        {
 96                            // There can be at most 2 padding chars.
 097                            if (paddingCount >= 2)
 98                            {
 99                                goto Fail;
 100                            }
 101
 0102                            paddingCount++;
 103                        }
 0104                        else if (!validatable.IsWhiteSpace(charToValidateInPadding))
 105                        {
 106                            // Invalid char was found.
 107                            goto Fail;
 108                        }
 109                    }
 110
 0111                    length += paddingCount;
 0112                    break;
 113                }
 114
 0115                if (!validatable.ValidateAndDecodeLength(lastChar, length, paddingCount, out decodedLength))
 116                {
 117                    goto Fail;
 118                }
 119
 0120                return true;
 121            }
 122
 0123            decodedLength = 0;
 0124            return true;
 125
 126        Fail:
 0127            decodedLength = 0;
 0128            return false;
 129        }
 130
 131        internal interface IBase64Validatable<T>
 132        {
 133#if NET
 134            int IndexOfAnyExcept(ReadOnlySpan<T> span);
 135#else
 136            int DecodeValue(T value);
 137#endif
 138            bool IsWhiteSpace(T value);
 139            bool IsEncodingPad(T value);
 140            bool ValidateAndDecodeLength(T lastChar, int length, int paddingCount, out int decodedLength);
 141        }
 142
 143        internal readonly struct Base64CharValidatable : IBase64Validatable<char>
 144        {
 145#if NET
 0146            private static readonly SearchValues<char> s_validBase64Chars = SearchValues.Create("ABCDEFGHIJKLMNOPQRSTUVW
 147
 0148            public int IndexOfAnyExcept(ReadOnlySpan<char> span) => span.IndexOfAnyExcept(s_validBase64Chars);
 149#else
 150            [MethodImpl(MethodImplOptions.AggressiveInlining)]
 151            public int DecodeValue(char value)
 152            {
 153                if (value > byte.MaxValue)
 154                {
 155                    // Invalid char was found.
 156                    return -2;
 157                }
 158
 159                return default(Base64DecoderByte).DecodingMap[value];
 160            }
 161#endif
 0162            public bool IsWhiteSpace(char value) => Base64Helper.IsWhiteSpace(value);
 0163            public bool IsEncodingPad(char value) => value == EncodingPad;
 164            public bool ValidateAndDecodeLength(char lastChar, int length, int paddingCount, out int decodedLength) =>
 0165                default(Base64ByteValidatable).ValidateAndDecodeLength((byte)lastChar, length, paddingCount, out decoded
 166        }
 167
 168        internal readonly struct Base64ByteValidatable : IBase64Validatable<byte>
 169        {
 170#if NET
 0171            private static readonly SearchValues<byte> s_validBase64Chars = SearchValues.Create(default(Base64EncoderByt
 172
 0173            public int IndexOfAnyExcept(ReadOnlySpan<byte> span) => span.IndexOfAnyExcept(s_validBase64Chars);
 174#else
 175            public int DecodeValue(byte value) => default(Base64DecoderByte).DecodingMap[value];
 176#endif
 0177            public bool IsWhiteSpace(byte value) => Base64Helper.IsWhiteSpace(value);
 0178            public bool IsEncodingPad(byte value) => value == EncodingPad;
 179            [MethodImpl(MethodImplOptions.AggressiveInlining)]
 180            public bool ValidateAndDecodeLength(byte lastChar, int length, int paddingCount, out int decodedLength)
 181            {
 0182                if (length % 4 == 0)
 183                {
 0184                    int decoded = default(Base64DecoderByte).DecodingMap[lastChar];
 0185                    if ((paddingCount == 1 && (decoded & 0x03) != 0) ||
 0186                        (paddingCount == 2 && (decoded & 0x0F) != 0))
 187                    {
 188                        // unused lower bits are not 0, reject input
 0189                        decodedLength = 0;
 0190                        return false;
 191                    }
 192
 193                    // Remove padding to get exact length.
 0194                    decodedLength = (int)((uint)length / 4 * 3) - paddingCount;
 0195                    return true;
 196                }
 197
 0198                decodedLength = 0;
 0199                return false;
 200            }
 201        }
 202    }
 203}
 204

Methods/Properties

DecodeFrom(TBase64Decoder,System.ReadOnlySpan`1<T>,System.Span`1<System.Byte>,System.Int32&,System.Int32&,System.Boolean,System.Boolean)
InvalidDataFallback(TBase64Decoder,System.ReadOnlySpan`1<T>,System.Span`1<System.Byte>,System.Int32&,System.Int32&,System.Boolean)
DecodeFromUtf8InPlace(TBase64Decoder,System.Span`1<System.Byte>,System.Int32&,System.Boolean)
DecodeWithWhiteSpaceBlockwise(TBase64Decoder,System.ReadOnlySpan`1<System.Byte>,System.Span`1<System.Byte>,System.Int32&,System.Int32&,System.Boolean)
DecodeWithWhiteSpaceBlockwise(TBase64Decoder,System.ReadOnlySpan`1<System.UInt16>,System.Span`1<System.Byte>,System.Int32&,System.Int32&,System.Boolean)
GetPaddingCount(TBase64Decoder,System.Byte&)
GetPaddingCount(TBase64Decoder,System.UInt16&)
DecodeWithWhiteSpaceFromUtf8InPlace(TBase64Decoder,System.Span`1<System.Byte>,System.Int32&,System.UInt32)
Avx512Decode(TBase64Decoder,T*&,System.Byte*&,T*,System.Int32,System.Int32,T*,System.Byte*)
Avx2Decode(TBase64Decoder,T*&,System.Byte*&,T*,System.Int32,System.Int32,T*,System.Byte*)
SimdShuffle(System.Runtime.Intrinsics.Vector128`1<System.Byte>,System.Runtime.Intrinsics.Vector128`1<System.Byte>,System.Runtime.Intrinsics.Vector128`1<System.Byte>)
Vector128Decode(TBase64Decoder,T*&,System.Byte*&,T*,System.Int32,System.Int32,T*,System.Byte*)
WriteThreeLowOrderBytes(System.Byte*,System.Int32)
IsWhiteSpace(System.Int32)
DecodingMap()
VbmiLookup0()
VbmiLookup1()
Avx2LutHigh()
Avx2LutLow()
Avx2LutShift()
MaskSlashOrUnderscore()
Vector128LutHigh()
Vector128LutLow()
Vector128LutShift()
AdvSimdLutOne3()
AdvSimdLutTwo3Uint1()
GetMaxDecodedLength(System.Int32)
IsInvalidLength(System.Int32)
IsValidPadding(System.UInt32)
SrcLength(System.Boolean,System.Int32)
TryDecode128Core(System.Runtime.Intrinsics.Vector128`1<System.Byte>,System.Runtime.Intrinsics.Vector128`1<System.Byte>,System.Runtime.Intrinsics.Vector128`1<System.Byte>,System.Runtime.Intrinsics.Vector128`1<System.Byte>,System.Runtime.Intrinsics.Vector128`1<System.Byte>,System.Runtime.Intrinsics.Vector128`1<System.Byte>,System.Runtime.Intrinsics.Vector128`1<System.SByte>,System.Runtime.Intrinsics.Vector128`1<System.Byte>,System.Runtime.Intrinsics.Vector128`1<System.Byte>&)
TryDecode256Core(System.Runtime.Intrinsics.Vector256`1<System.SByte>,System.Runtime.Intrinsics.Vector256`1<System.SByte>,System.Runtime.Intrinsics.Vector256`1<System.SByte>,System.Runtime.Intrinsics.Vector256`1<System.SByte>,System.Runtime.Intrinsics.Vector256`1<System.SByte>,System.Runtime.Intrinsics.Vector256`1<System.SByte>,System.Runtime.Intrinsics.Vector256`1<System.SByte>,System.Runtime.Intrinsics.Vector256`1<System.SByte>&)
TryLoadVector512(System.Byte*,System.Byte*,System.Int32,System.Runtime.Intrinsics.Vector512`1<System.SByte>&)
TryLoadAvxVector256(System.Byte*,System.Byte*,System.Int32,System.Runtime.Intrinsics.Vector256`1<System.SByte>&)
TryLoadVector128(System.Byte*,System.Byte*,System.Int32,System.Runtime.Intrinsics.Vector128`1<System.Byte>&)
TryLoadArmVector128x4(System.Byte*,System.Byte*,System.Int32,System.Runtime.Intrinsics.Vector128`1<System.Byte>&,System.Runtime.Intrinsics.Vector128`1<System.Byte>&,System.Runtime.Intrinsics.Vector128`1<System.Byte>&,System.Runtime.Intrinsics.Vector128`1<System.Byte>&)
DecodeFourElements(System.Byte*,System.SByte&)
DecodeRemaining(System.Byte*,System.SByte&,System.Int64,System.UInt32&,System.UInt32&)
IndexOfAnyExceptWhiteSpace(System.ReadOnlySpan`1<System.Byte>)
DecodeWithWhiteSpaceBlockwiseWrapper(TBase64Decoder,System.ReadOnlySpan`1<System.Byte>,System.Span`1<System.Byte>,System.Int32&,System.Int32&,System.Boolean)
DecodingMap()
VbmiLookup0()
VbmiLookup1()
Avx2LutHigh()
Avx2LutLow()
Avx2LutShift()
MaskSlashOrUnderscore()
Vector128LutHigh()
Vector128LutLow()
Vector128LutShift()
AdvSimdLutOne3()
AdvSimdLutTwo3Uint1()
GetMaxDecodedLength(System.Int32)
IsInvalidLength(System.Int32)
IsValidPadding(System.UInt32)
SrcLength(System.Boolean,System.Int32)
TryDecode128Core(System.Runtime.Intrinsics.Vector128`1<System.Byte>,System.Runtime.Intrinsics.Vector128`1<System.Byte>,System.Runtime.Intrinsics.Vector128`1<System.Byte>,System.Runtime.Intrinsics.Vector128`1<System.Byte>,System.Runtime.Intrinsics.Vector128`1<System.Byte>,System.Runtime.Intrinsics.Vector128`1<System.Byte>,System.Runtime.Intrinsics.Vector128`1<System.SByte>,System.Runtime.Intrinsics.Vector128`1<System.Byte>,System.Runtime.Intrinsics.Vector128`1<System.Byte>&)
TryDecode256Core(System.Runtime.Intrinsics.Vector256`1<System.SByte>,System.Runtime.Intrinsics.Vector256`1<System.SByte>,System.Runtime.Intrinsics.Vector256`1<System.SByte>,System.Runtime.Intrinsics.Vector256`1<System.SByte>,System.Runtime.Intrinsics.Vector256`1<System.SByte>,System.Runtime.Intrinsics.Vector256`1<System.SByte>,System.Runtime.Intrinsics.Vector256`1<System.SByte>,System.Runtime.Intrinsics.Vector256`1<System.SByte>&)
TryLoadVector512(System.UInt16*,System.UInt16*,System.Int32,System.Runtime.Intrinsics.Vector512`1<System.SByte>&)
TryLoadAvxVector256(System.UInt16*,System.UInt16*,System.Int32,System.Runtime.Intrinsics.Vector256`1<System.SByte>&)
TryLoadVector128(System.UInt16*,System.UInt16*,System.Int32,System.Runtime.Intrinsics.Vector128`1<System.Byte>&)
TryLoadArmVector128x4(System.UInt16*,System.UInt16*,System.Int32,System.Runtime.Intrinsics.Vector128`1<System.Byte>&,System.Runtime.Intrinsics.Vector128`1<System.Byte>&,System.Runtime.Intrinsics.Vector128`1<System.Byte>&,System.Runtime.Intrinsics.Vector128`1<System.Byte>&)
DecodeFourElements(System.UInt16*,System.SByte&)
DecodeRemaining(System.UInt16*,System.SByte&,System.Int64,System.UInt32&,System.UInt32&)
IndexOfAnyExceptWhiteSpace(System.ReadOnlySpan`1<System.UInt16>)
DecodeWithWhiteSpaceBlockwiseWrapper(TBase64Decoder,System.ReadOnlySpan`1<System.UInt16>,System.Span`1<System.Byte>,System.Int32&,System.Int32&,System.Boolean)
EncodeTo(TBase64Encoder,System.ReadOnlySpan`1<System.Byte>,System.Span`1<T>,System.Int32&,System.Int32&,System.Boolean)
Avx512Encode(TBase64Encoder,System.Byte*&,T*&,System.Byte*,System.Int32,System.Int32,System.Byte*,T*)
Avx2Encode(TBase64Encoder,System.Byte*&,T*&,System.Byte*,System.Int32,System.Int32,System.Byte*,T*)
Vector128Encode(TBase64Encoder,System.Byte*&,T*&,System.Byte*,System.Int32,System.Int32,System.Byte*,T*)
EncodeToUtf8InPlace(TBase64Encoder,System.Span`1<System.Byte>,System.Int32,System.Int32&)
Encode(System.Byte*,System.Byte&)
ConstructResult(System.UInt32,System.UInt32,System.UInt32,System.UInt32)
EncodeOneOptionallyPadTwo(System.Byte*,System.UInt16*,System.Byte&)
EncodeTwoOptionallyPadOne(System.Byte*,System.UInt16*,System.Byte&)
EncodingMap()
Avx2LutChar62()
Avx2LutChar63()
AdvSimdLut4()
Ssse3AdvSimdLutE3()
IncrementPadTwo()
IncrementPadOne()
GetMaxSrcLength(System.Int32,System.Int32)
GetInPlaceDestinationLength(System.Int32,System.Int32)
GetMaxEncodedLength(System.Int32)
EncodeOneOptionallyPadTwo(System.Byte*,System.Byte*,System.Byte&)
EncodeTwoOptionallyPadOne(System.Byte*,System.Byte*,System.Byte&)
StoreVector512ToDestination(System.Byte*,System.Byte*,System.Int32,System.Runtime.Intrinsics.Vector512`1<System.Byte>)
StoreVector256ToDestination(System.Byte*,System.Byte*,System.Int32,System.Runtime.Intrinsics.Vector256`1<System.Byte>)
StoreVector128ToDestination(System.Byte*,System.Byte*,System.Int32,System.Runtime.Intrinsics.Vector128`1<System.Byte>)
StoreArmVector128x4ToDestination(System.Byte*,System.Byte*,System.Int32,System.Runtime.Intrinsics.Vector128`1<System.Byte>,System.Runtime.Intrinsics.Vector128`1<System.Byte>,System.Runtime.Intrinsics.Vector128`1<System.Byte>,System.Runtime.Intrinsics.Vector128`1<System.Byte>)
EncodeThreeAndWrite(System.Byte*,System.Byte*,System.Byte&)
EncodingMap()
Avx2LutChar62()
Avx2LutChar63()
AdvSimdLut4()
Ssse3AdvSimdLutE3()
IncrementPadTwo()
IncrementPadOne()
GetMaxSrcLength(System.Int32,System.Int32)
GetInPlaceDestinationLength(System.Int32,System.Int32)
GetMaxEncodedLength(System.Int32)
EncodeOneOptionallyPadTwo(System.Byte*,System.UInt16*,System.Byte&)
EncodeTwoOptionallyPadOne(System.Byte*,System.UInt16*,System.Byte&)
StoreVector512ToDestination(System.UInt16*,System.UInt16*,System.Int32,System.Runtime.Intrinsics.Vector512`1<System.Byte>)
StoreVector256ToDestination(System.UInt16*,System.UInt16*,System.Int32,System.Runtime.Intrinsics.Vector256`1<System.Byte>)
StoreVector128ToDestination(System.UInt16*,System.UInt16*,System.Int32,System.Runtime.Intrinsics.Vector128`1<System.Byte>)
StoreArmVector128x4ToDestination(System.UInt16*,System.UInt16*,System.Int32,System.Runtime.Intrinsics.Vector128`1<System.Byte>,System.Runtime.Intrinsics.Vector128`1<System.Byte>,System.Runtime.Intrinsics.Vector128`1<System.Byte>,System.Runtime.Intrinsics.Vector128`1<System.Byte>)
EncodeThreeAndWrite(System.Byte*,System.UInt16*,System.Byte&)
AssertRead(System.Byte*,System.Byte*,System.Int32)
AssertWrite(System.Byte*,System.Byte*,System.Int32)
AssertRead(System.UInt16*,System.UInt16*,System.Int32)
AssertWrite(System.UInt16*,System.UInt16*,System.Int32)
ThrowUnreachableException()
IsValid(TBase64Validatable,System.ReadOnlySpan`1<T>,System.Int32&)
.cctor()
IndexOfAnyExcept(System.ReadOnlySpan`1<System.Char>)
IsWhiteSpace(System.Char)
IsEncodingPad(System.Char)
ValidateAndDecodeLength(System.Char,System.Int32,System.Int32,System.Int32&)
.cctor()
IndexOfAnyExcept(System.ReadOnlySpan`1<System.Byte>)
IsWhiteSpace(System.Byte)
IsEncodingPad(System.Byte)
ValidateAndDecodeLength(System.Byte,System.Int32,System.Int32,System.Int32&)