< Summary

Line coverage
70%
Covered lines: 761
Uncovered lines: 319
Coverable lines: 1080
Total lines: 3172
Line coverage: 70.4%
Branch coverage
63%
Covered branches: 277
Total branches: 436
Branch coverage: 63.5%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Cyclomatic complexity NPath complexity Sequence coverage
File 1: DecodeFrom(...)70%808085.71%
File 1: InvalidDataFallback(TBase64Decoder,System.ReadOnlySpan`1<T>,System.Span`1<System.Byte>,System.Int32&,System.Int32&,System.Boolean)90%1010100%
File 1: DecodeFromUtf8InPlace(...)83.33%484897.43%
File 1: DecodeWithWhiteSpaceBlockwise(...)90%303095.65%
File 1: DecodeWithWhiteSpaceBlockwise(...)0%30300%
File 1: GetPaddingCount(...)83.33%66100%
File 1: GetPaddingCount(...)0%660%
File 1: DecodeWithWhiteSpaceFromUtf8InPlace(...)95.83%2424100%
File 1: Avx512Decode(...)83.33%66100%
File 1: Avx2Decode(...)83.33%66100%
File 1: SimdShuffle(...)25%8866.66%
File 1: Vector128Decode(...)36.36%222293.33%
File 1: WriteThreeLowOrderBytes(...)100%11100%
File 1: IsWhiteSpace(...)50%22100%
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%11100%
File 1: TryLoadAvxVector256(...)100%11100%
File 1: TryLoadVector128(...)100%11100%
File 1: TryLoadArmVector128x4(...)100%110%
File 1: DecodeFourElements(...)100%11100%
File 1: DecodeRemaining(...)100%66100%
File 1: IndexOfAnyExceptWhiteSpace(...)100%44100%
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(...)50%2275%
File 1: TryLoadAvxVector256(...)50%2275%
File 1: TryLoadVector128(...)50%2275%
File 1: TryLoadArmVector128x4(...)0%220%
File 1: DecodeFourElements(...)50%2294.11%
File 1: DecodeRemaining(...)62.5%8891.3%
File 1: IndexOfAnyExceptWhiteSpace(...)0%440%
File 1: DecodeWithWhiteSpaceBlockwiseWrapper(...)100%110%
File 2: EncodeTo(...)72.5%404088.67%
File 2: Avx512Encode(...)75%44100%
File 2: Avx2Encode(...)75%44100%
File 2: Vector128Encode(...)28.57%141493.93%
File 2: EncodeToUtf8InPlace(...)80%101084%
File 2: Encode(...)100%11100%
File 2: ConstructResult(...)100%11100%
File 2: EncodeOneOptionallyPadTwo(...)100%11100%
File 2: EncodeTwoOptionallyPadOne(...)100%11100%
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%11100%
File 2: StoreVector256ToDestination(...)100%11100%
File 2: StoreVector128ToDestination(...)100%11100%
File 2: StoreArmVector128x4ToDestination(...)100%110%
File 2: EncodeThreeAndWrite(...)100%11100%
File 3: AssertRead(...)50%2271.42%
File 3: AssertWrite(...)50%2271.42%
File 3: AssertRead(...)50%2271.42%
File 3: AssertWrite(...)50%2271.42%
File 3: ThrowUnreachableException()100%110%
File 4: IsValid(...)92.85%282893.93%
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            {
 4330                bytesConsumed = 0;
 4331                bytesWritten = 0;
 4332                return OperationStatus.Done;
 33            }
 34
 7468235            fixed (T* srcBytes = &MemoryMarshal.GetReference(source))
 7468236            fixed (byte* destBytes = &MemoryMarshal.GetReference(bytes))
 37            {
 7468238                int srcLength = decoder.SrcLength(isFinalBlock, source.Length);
 7468239                int destLength = bytes.Length;
 7468240                int maxSrcLength = srcLength;
 7468241                int decodedLength = decoder.GetMaxDecodedLength(srcLength);
 42
 43                // max. 2 padding chars
 7468244                if (destLength < decodedLength - 2)
 45                {
 46                    // For overflow see comment below
 047                    maxSrcLength = destLength / 3 * 4;
 48                }
 49
 7468250                T* src = srcBytes;
 7468251                byte* dest = destBytes;
 7468252                T* srcEnd = srcBytes + (uint)srcLength;
 7468253                T* srcMax = srcBytes + (uint)maxSrcLength;
 54
 55#if NET
 7468256                if (maxSrcLength >= 24)
 57                {
 3205458                    T* end = srcMax - 88;
 3205459                    if (Vector512.IsHardwareAccelerated && Avx512Vbmi.IsSupported && (end >= src))
 60                    {
 2786961                        Avx512Decode(decoder, ref src, ref dest, end, maxSrcLength, destLength, srcBytes, destBytes);
 62
 2786963                        if (src == srcEnd)
 64                        {
 65                            goto DoneExit;
 66                        }
 67                    }
 68
 3205469                    end = srcMax - 45;
 3205470                    if (Avx2.IsSupported && (end >= src))
 71                    {
 2994972                        Avx2Decode(decoder, ref src, ref dest, end, maxSrcLength, destLength, srcBytes, destBytes);
 73
 2994974                        if (src == srcEnd)
 75                        {
 76                            goto DoneExit;
 77                        }
 78                    }
 79
 3205480                    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
 3205491                    end = srcMax - 24;
 3205492                    if ((Ssse3.IsSupported || AdvSimd.Arm64.IsSupported || PackedSimd.IsSupported) && BitConverter.IsLit
 93                    {
 3131494                        Vector128Decode(decoder, ref src, ref dest, end, maxSrcLength, destLength, srcBytes, destBytes);
 95
 3131496                        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
 74682106                int skipLastChunk = isFinalBlock ? 4 : 0;
 107
 74682108                if (destLength >= decodedLength)
 109                {
 74682110                    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
 74682130                ref sbyte decodingMap = ref MemoryMarshal.GetReference(decoder.DecodingMap);
 74682131                srcMax = srcBytes + maxSrcLength;
 132
 152906133                while (src < srcMax)
 134                {
 108999135                    int result = decoder.DecodeFourElements(src, ref decodingMap);
 136
 108999137                    if (result < 0)
 138                    {
 139                        goto InvalidDataExit;
 140                    }
 141
 78224142                    WriteThreeLowOrderBytes(dest, result);
 78224143                    src += 4;
 78224144                    dest += 3;
 145                }
 146
 43907147                if (maxSrcLength != srcLength - skipLastChunk)
 148                {
 149                    goto DestinationTooSmallExit;
 150                }
 151
 43907152                if (src == srcEnd)
 153                {
 39912154                    if (isFinalBlock)
 155                    {
 156                        goto InvalidDataExit;
 157                    }
 158
 39912159                    if (src == srcBytes + source.Length)
 160                    {
 39912161                        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
 3995170                long remaining = srcEnd - src;
 3995171                Debug.Assert(typeof(TBase64Decoder) == typeof(Base64DecoderByte) ? remaining == 4 : remaining < 8);
 3995172                int i0 = decoder.DecodeRemaining(srcEnd, ref decodingMap, remaining, out uint t2, out uint t3);
 173
 3995174                if (i0 < 0)
 175                {
 176                    goto InvalidDataExit;
 177                }
 178
 3370179                byte* destMax = destBytes + (uint)destLength;
 180
 3370181                if (!decoder.IsValidPadding(t3))
 182                {
 1161183                    int i2 = Unsafe.Add(ref decodingMap, (IntPtr)t2);
 1161184                    int i3 = Unsafe.Add(ref decodingMap, (IntPtr)t3);
 185
 1161186                    i2 <<= 6;
 187
 1161188                    i0 |= i3;
 1161189                    i0 |= i2;
 190
 1161191                    if (i0 < 0)
 192                    {
 193                        goto InvalidDataExit;
 194                    }
 1114195                    if (dest + 3 > destMax)
 196                    {
 197                        goto DestinationTooSmallExit;
 198                    }
 199
 1114200                    WriteThreeLowOrderBytes(dest, i0);
 1114201                    dest += 3;
 1114202                    src += 4;
 203                }
 2209204                else if (!decoder.IsValidPadding(t2))
 205                {
 997206                    int i2 = Unsafe.Add(ref decodingMap, (IntPtr)t2);
 207
 997208                    i2 <<= 6;
 209
 997210                    i0 |= i2;
 211
 997212                    if ((i0 & 0x800000c0) != 0) // if negative or 2 unused bits are not 0.
 213                    {
 214                        goto InvalidDataExit;
 215                    }
 924216                    if (dest + 2 > destMax)
 217                    {
 218                        goto DestinationTooSmallExit;
 219                    }
 220
 924221                    dest[0] = (byte)(i0 >> 16);
 924222                    dest[1] = (byte)(i0 >> 8);
 924223                    dest += 2;
 924224                    src += remaining;
 225                }
 226                else
 227                {
 1212228                    if ((i0 & 0x8000F000) != 0) // if negative or 4 unused bits are not 0.
 229                    {
 230                        goto InvalidDataExit;
 231                    }
 1111232                    if (dest + 1 > destMax)
 233                    {
 234                        goto DestinationTooSmallExit;
 235                    }
 236
 1111237                    dest[0] = (byte)(i0 >> 16);
 1111238                    dest += 1;
 1111239                    src += remaining;
 240                }
 241
 3149242                if (srcLength != source.Length)
 243                {
 244                    goto InvalidDataExit;
 245                }
 246
 247            DoneExit:
 43061248                bytesConsumed = (int)(src - srcBytes);
 43061249                bytesWritten = (int)(dest - destBytes);
 43061250                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:
 31621274                bytesConsumed = (int)(src - srcBytes);
 31621275                bytesWritten = (int)(dest - destBytes);
 31621276                return ignoreWhiteSpace ?
 31621277                    InvalidDataFallback(decoder, source, bytes, ref bytesConsumed, ref bytesWritten, isFinalBlock) :
 31621278                    OperationStatus.InvalidData;
 279            }
 280
 281            static OperationStatus InvalidDataFallback(TBase64Decoder decoder, ReadOnlySpan<T> source, Span<byte> bytes,
 282            {
 2417283                source = source.Slice(bytesConsumed);
 2417284                bytes = bytes.Slice(bytesWritten);
 285
 286                OperationStatus status;
 287                do
 288                {
 30861289                    int localConsumed = decoder.IndexOfAnyExceptWhiteSpace(source);
 30861290                    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.
 66294                        bytesConsumed += source.Length;
 66295                        status = OperationStatus.Done;
 66296                        break;
 297                    }
 298
 30795299                    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.
 2121307                        return decoder.DecodeWithWhiteSpaceBlockwiseWrapper(decoder, source, bytes, ref bytesConsumed, r
 308                    }
 309
 310                    // Skip over the starting whitespace and continue.
 28674311                    bytesConsumed += localConsumed;
 28674312                    source = source.Slice(localConsumed);
 313
 314                    // Try again after consumed whitespace
 28674315                    status = DecodeFrom(decoder, source, bytes, out localConsumed, out int localWritten, isFinalBlock, i
 28674316                    bytesConsumed += localConsumed;
 28674317                    bytesWritten += localWritten;
 318
 28674319                    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
 28444328                    source = source.Slice(localConsumed);
 28444329                    bytes = bytes.Slice(localWritten);
 330                }
 28444331                while (!source.IsEmpty);
 332
 296333                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
 69005346            fixed (byte* bufferBytes = &MemoryMarshal.GetReference(buffer))
 347            {
 69005348                uint bufferLength = (uint)buffer.Length;
 69005349                uint sourceIndex = 0;
 69005350                uint destIndex = 0;
 351
 69005352                if (decoder.IsInvalidLength(buffer.Length))
 353                {
 354                    goto InvalidExit;
 355                }
 356
 68665357                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.
 68665364                if (bufferLength >= 24)
 365                {
 2012366                    byte* src = bufferBytes;
 2012367                    byte* dest = bufferBytes;
 2012368                    int length = (int)bufferLength;
 2012369                    byte* srcMax = bufferBytes + length;
 370
 2012371                    byte* end = srcMax - 88;
 2012372                    if (Vector512.IsHardwareAccelerated && Avx512Vbmi.IsSupported && (end >= src))
 373                    {
 1330374                        Avx512Decode(decoder, ref src, ref dest, end, length, length, bufferBytes, bufferBytes);
 375                    }
 376
 2012377                    end = srcMax - 45;
 2012378                    if (Avx2.IsSupported && (end >= src))
 379                    {
 1390380                        Avx2Decode(decoder, ref src, ref dest, end, length, length, bufferBytes, bufferBytes);
 381                    }
 382
 2012383                    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
 2012389                    end = srcMax - 24;
 2012390                    if ((Ssse3.IsSupported || AdvSimd.Arm64.IsSupported || PackedSimd.IsSupported) && BitConverter.IsLit
 391                    {
 1637392                        Vector128Decode(decoder, ref src, ref dest, end, length, length, bufferBytes, bufferBytes);
 393                    }
 394
 2012395                    sourceIndex = (uint)(src - bufferBytes);
 2012396                    destIndex = (uint)(dest - bufferBytes);
 397                }
 398#endif
 399
 68665400                if (bufferLength > 4)
 401                {
 7085402                    while (sourceIndex < bufferLength - 4)
 403                    {
 5529404                        int result = decoder.DecodeFourElements(bufferBytes + sourceIndex, ref decodingMap);
 5529405                        if (result < 0)
 406                        {
 407                            goto InvalidExit;
 408                        }
 409
 4441410                        WriteThreeLowOrderBytes(bufferBytes + destIndex, result);
 4441411                        destIndex += 3;
 4441412                        sourceIndex += 4;
 413                    }
 414                }
 415
 416                uint t0;
 417                uint t1;
 418                uint t2;
 419                uint t3;
 420
 67577421                switch (bufferLength - sourceIndex)
 422                {
 423                    case 2:
 678424                        t0 = bufferBytes[bufferLength - 2];
 678425                        t1 = bufferBytes[bufferLength - 1];
 678426                        t2 = EncodingPad;
 678427                        t3 = EncodingPad;
 678428                        break;
 429                    case 3:
 567430                        t0 = bufferBytes[bufferLength - 3];
 567431                        t1 = bufferBytes[bufferLength - 2];
 567432                        t2 = bufferBytes[bufferLength - 1];
 567433                        t3 = EncodingPad;
 567434                        break;
 435                    case 4:
 66332436                        t0 = bufferBytes[bufferLength - 4];
 66332437                        t1 = bufferBytes[bufferLength - 3];
 66332438                        t2 = bufferBytes[bufferLength - 2];
 66332439                        t3 = bufferBytes[bufferLength - 1];
 440                        break;
 441                    default:
 442                        goto InvalidExit;
 443                }
 444
 67577445                int i0 = Unsafe.Add(ref decodingMap, (int)t0);
 67577446                int i1 = Unsafe.Add(ref decodingMap, (int)t1);
 447
 67577448                i0 <<= 18;
 67577449                i1 <<= 12;
 450
 67577451                i0 |= i1;
 452
 67577453                if (!decoder.IsValidPadding(t3))
 454                {
 65620455                    int i2 = Unsafe.Add(ref decodingMap, (int)t2);
 65620456                    int i3 = Unsafe.Add(ref decodingMap, (int)t3);
 457
 65620458                    i2 <<= 6;
 459
 65620460                    i0 |= i3;
 65620461                    i0 |= i2;
 462
 65620463                    if (i0 < 0)
 464                    {
 465                        goto InvalidExit;
 466                    }
 467
 65176468                    WriteThreeLowOrderBytes(bufferBytes + destIndex, i0);
 65176469                    destIndex += 3;
 470                }
 1957471                else if (!decoder.IsValidPadding(t2))
 472                {
 848473                    int i2 = Unsafe.Add(ref decodingMap, (int)t2);
 474
 848475                    i2 <<= 6;
 476
 848477                    i0 |= i2;
 478
 848479                    if ((i0 & 0x800000c0) != 0) // if negative or 2 unused bits are not 0.
 480                    {
 481                        goto InvalidExit;
 482                    }
 483
 700484                    bufferBytes[destIndex] = (byte)(i0 >> 16);
 700485                    bufferBytes[destIndex + 1] = (byte)(i0 >> 8);
 700486                    destIndex += 2;
 487                }
 488                else
 489                {
 1109490                    if ((i0 & 0x8000F000) != 0) // if negative or 4 unused bits are not 0.
 491                    {
 492                        goto InvalidExit;
 493                    }
 494
 865495                    bufferBytes[destIndex] = (byte)(i0 >> 16);
 865496                    destIndex += 1;
 497                }
 498
 66741499                bytesWritten = (int)destIndex;
 66741500                return OperationStatus.Done;
 501
 502            InvalidExit:
 2264503                bytesWritten = (int)destIndex;
 2264504                return ignoreWhiteSpace ?
 2264505                    DecodeWithWhiteSpaceFromUtf8InPlace<TBase64Decoder>(decoder, buffer, ref bytesWritten, sourceIndex) 
 2264506                    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;
 2121514            Span<byte> buffer = stackalloc byte[BlockSize];
 2121515            OperationStatus status = OperationStatus.Done;
 516
 50591517            while (!source.IsEmpty)
 518            {
 519                // Skip over any leading whitespace
 50479520                if (IsWhiteSpace(source[0]))
 521                {
 10153522                    source = source.Slice(1);
 10153523                    bytesConsumed++;
 10153524                    continue;
 525                }
 526
 40326527                int encodedIdx = 0;
 40326528                int bufferIdx = 0;
 40326529                int skipped = 0;
 530
 401662531                for (; encodedIdx < source.Length && (uint)bufferIdx < (uint)buffer.Length; ++encodedIdx)
 532                {
 180668533                    if (IsWhiteSpace(source[encodedIdx]))
 534                    {
 21060535                        skipped++;
 536                    }
 537                    else
 538                    {
 159608539                        buffer[bufferIdx] = source[encodedIdx];
 159608540                        bufferIdx++;
 541                    }
 542                }
 543
 40326544                source = source.Slice(encodedIdx);
 40326545                Debug.Assert(bufferIdx > 0);
 546
 547                bool hasAnotherBlock;
 548
 40326549                if (typeof(TBase64Decoder) == typeof(Base64DecoderByte))
 550                {
 0551                    hasAnotherBlock = source.Length >= BlockSize;
 552                }
 553                else
 554                {
 40326555                    hasAnotherBlock = source.Length > 1;
 556                }
 557
 40326558                bool localIsFinalBlock = !hasAnotherBlock;
 559
 560                // If this block contains padding and there's another block, then only whitespace may follow for being v
 40326561                if (hasAnotherBlock)
 562                {
 38799563                    int paddingCount = GetPaddingCount(decoder, ref buffer[BlockSize - 1]);
 38799564                    if (paddingCount > 0)
 565                    {
 169566                        hasAnotherBlock = false;
 169567                        localIsFinalBlock = true;
 568                    }
 569                }
 570
 40326571                if (localIsFinalBlock && !isFinalBlock)
 572                {
 0573                    localIsFinalBlock = false;
 574                }
 575
 40326576                status = DecodeFrom<TBase64Decoder, byte>(decoder, buffer.Slice(0, bufferIdx), bytes, out int localConsu
 577
 40326578                if (status != OperationStatus.Done)
 579                {
 760580                    Debug.Assert(localConsumed == 0 && localWritten == 0, "On failure, should not have consumed or writt
 760581                    return status;
 582                }
 583
 39566584                bytesConsumed += skipped;
 39566585                bytesConsumed += localConsumed;
 39566586                bytesWritten += localWritten;
 587
 588                // The remaining data must all be whitespace in order to be valid.
 39566589                if (!hasAnotherBlock)
 590                {
 7274591                    for (int i = 0; i < source.Length; ++i)
 592                    {
 2455593                        if (!IsWhiteSpace(source[i]))
 594                        {
 595                            // Revert previous dest increment, since an invalid state followed.
 67596                            bytesConsumed -= localConsumed;
 67597                            bytesWritten -= localWritten;
 598
 67599                            return OperationStatus.InvalidData;
 600                        }
 601
 2388602                        bytesConsumed++;
 603                    }
 604
 1182605                    break;
 606                }
 607
 38317608                bytes = bytes.Slice(localWritten);
 38317609                Debug.Assert(!source.IsEmpty);
 610            }
 611
 1294612            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        {
 38799723            int padding = 0;
 724
 38799725            if (decoder.IsValidPadding(ptrToLastElement))
 726            {
 158727                padding++;
 728            }
 729
 38799730            if (decoder.IsValidPadding(Unsafe.Subtract(ref ptrToLastElement, 1)))
 731            {
 91732                padding++;
 733            }
 734
 38799735            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        {
 1622760            int BlockSize = Math.Min(source.Length - (int)sourceIndex, 4);
 1622761            Span<byte> buffer = stackalloc byte[BlockSize];
 762
 1622763            OperationStatus status = OperationStatus.Done;
 1622764            int localDestIndex = destIndex;
 1622765            bool hasPaddingBeenProcessed = false;
 1622766            int localBytesWritten = 0;
 767
 66863768            while (sourceIndex < (uint)source.Length)
 769            {
 66068770                int bufferIdx = 0;
 771
 372313772                while (bufferIdx < BlockSize && sourceIndex < (uint)source.Length)
 773                {
 306245774                    if (!IsWhiteSpace(source[(int)sourceIndex]))
 775                    {
 262147776                        buffer[bufferIdx] = source[(int)sourceIndex];
 262147777                        bufferIdx++;
 778                    }
 779
 306245780                    sourceIndex++;
 781                }
 782
 66068783                if (bufferIdx == 0)
 784                {
 785                    continue;
 786                }
 787
 65914788                if (bufferIdx != 4)
 789                {
 790                    // Base64 require 4 bytes, for Base64Url it can be less than 4 bytes but not 1 byte.
 818791                    if (decoder is Base64DecoderByte || bufferIdx == 1)
 792                    {
 164793                        status = OperationStatus.InvalidData;
 164794                        break;
 795                    }
 796                    else // For Base64Url fill empty slots in last block with padding
 797                    {
 1571798                        while (bufferIdx < BlockSize)  // Can happen only for last block
 799                        {
 917800                            Debug.Assert(source.Length == sourceIndex);
 917801                            buffer[bufferIdx++] = (byte)EncodingPad;
 802                        }
 803                    }
 804                }
 805
 65750806                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.
 21810                    localDestIndex -= localBytesWritten;
 21811                    status = OperationStatus.InvalidData;
 21812                    break;
 813                }
 814
 65729815                status = DecodeFromUtf8InPlace<TBase64Decoder>(decoder, buffer, out localBytesWritten, ignoreWhiteSpace:
 65729816                localDestIndex += localBytesWritten;
 65729817                hasPaddingBeenProcessed = localBytesWritten < 3;
 818
 65729819                if (status != OperationStatus.Done)
 820                {
 821                    break;
 822                }
 823
 824                // Write result to source span in place.
 519204825                for (int i = 0; i < localBytesWritten; i++)
 826                {
 194515827                    source[localDestIndex - localBytesWritten + i] = buffer[i];
 828                }
 829            }
 830
 1622831            destIndex = localDestIndex;
 1622832            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.
 29199849            T* src = srcBytes;
 29199850            byte* dest = destBytes;
 851
 852            // The JIT won't hoist these "constants", so help it
 29199853            Vector512<sbyte> vbmiLookup0 = Vector512.Create(decoder.VbmiLookup0).AsSByte();
 29199854            Vector512<sbyte> vbmiLookup1 = Vector512.Create(decoder.VbmiLookup1).AsSByte();
 29199855            Vector512<byte> vbmiPackedLanesControl = Vector512.Create(
 29199856                0x06000102, 0x090a0405, 0x0c0d0e08, 0x16101112,
 29199857                0x191a1415, 0x1c1d1e18, 0x26202122, 0x292a2425,
 29199858                0x2c2d2e28, 0x36303132, 0x393a3435, 0x3c3d3e38,
 29199859                0x00000000, 0x00000000, 0x00000000, 0x00000000).AsByte();
 860
 29199861            Vector512<sbyte> mergeConstant0 = Vector512.Create(0x01400140).AsSByte();
 29199862            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            {
 53725868                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]
 53725877                Vector512<sbyte> origIndex = Avx512Vbmi.PermuteVar64x8x2(vbmiLookup0, str, vbmiLookup1);
 53725878                Vector512<sbyte> errorVec = (origIndex.AsInt32() | str.AsInt32()).AsSByte();
 53725879                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]
 27045886                Vector512<short> multiAdd1 = Avx512BW.MultiplyAddAdjacent(origIndex.AsByte(), mergeConstant0);
 887                // multiAdd1: [...|00000000|aaaaaabb|bbbbcccc|ccdddddd]
 27045888                Vector512<int> multiAdd2 = Avx512BW.MultiplyAddAdjacent(multiAdd1, mergeConstant1);
 889
 890                // Step 3: Pack 48 bytes
 27045891                str = Avx512Vbmi.PermuteVar64x8(multiAdd2.AsByte(), vbmiPackedLanesControl).AsSByte();
 892
 27045893                AssertWrite<Vector512<sbyte>>(dest, destStart, destLength);
 27045894                str.Store((sbyte*)dest);
 27045895                src += 64;
 27045896                dest += 48;
 897            }
 27045898            while (src <= srcEnd);
 899
 29199900            srcBytes = src;
 29199901            destBytes = dest;
 29199902        }
 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
 31339919            Vector256<sbyte> lutHi = Vector256.Create(decoder.Avx2LutHigh);
 920
 31339921            Vector256<sbyte> lutLo = Vector256.Create(decoder.Avx2LutLow);
 922
 31339923            Vector256<sbyte> lutShift = Vector256.Create(decoder.Avx2LutShift);
 924
 31339925            Vector256<sbyte> packBytesInLaneMask = Vector256.Create(
 31339926                2, 1, 0, 6,
 31339927                5, 4, 10, 9,
 31339928                8, 14, 13, 12,
 31339929                -1, -1, -1, -1,
 31339930                2, 1, 0, 6,
 31339931                5, 4, 10, 9,
 31339932                8, 14, 13, 12,
 31339933                -1, -1, -1, -1);
 934
 31339935            Vector256<int> packLanesControl = Vector256.Create(
 31339936                 0, 0, 0, 0,
 31339937                1, 0, 0, 0,
 31339938                2, 0, 0, 0,
 31339939                4, 0, 0, 0,
 31339940                5, 0, 0, 0,
 31339941                6, 0, 0, 0,
 31339942                -1, -1, -1, -1,
 31339943                -1, -1, -1, -1).AsInt32();
 944
 31339945            Vector256<sbyte> maskSlashOrUnderscore = Vector256.Create((sbyte)decoder.MaskSlashOrUnderscore);
 31339946            Vector256<sbyte> shiftForUnderscore = Vector256.Create((sbyte)33);
 31339947            Vector256<sbyte> mergeConstant0 = Vector256.Create(0x01400140).AsSByte();
 31339948            Vector256<short> mergeConstant1 = Vector256.Create(0x00011000).AsInt16();
 949
 31339950            T* src = srcBytes;
 31339951            byte* dest = destBytes;
 952
 953            //while (remaining >= 45)
 954            do
 955            {
 33185956                if (!decoder.TryLoadAvxVector256(src, srcStart, sourceLength, out Vector256<sbyte> str))
 957                {
 958                    break;
 959                }
 960
 33185961                Vector256<sbyte> hiNibbles = ((str.AsInt32()) >>> 4).AsSByte() & maskSlashOrUnderscore;
 962
 33185963                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
 4082974                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
 4082980                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:
 4082987                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
 4082994                str = Avx2.PermuteVar8x32(output, packLanesControl).AsSByte();
 995
 4082996                AssertWrite<Vector256<sbyte>>(dest, destStart, destLength);
 4082997                Avx.Store(dest, str.AsByte());
 998
 4082999                src += 32;
 40821000                dest += 24;
 1001            }
 40821002            while (src <= srcEnd);
 1003
 313391004            srcBytes = src;
 313391005            destBytes = dest;
 313391006        }
 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
 985881016            if (Ssse3.IsSupported)
 1017            {
 985881018                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
 329511253            Vector128<byte> lutHi = Vector128.Create(decoder.Vector128LutHigh).AsByte();
 329511254            Vector128<byte> lutLo = Vector128.Create(decoder.Vector128LutLow).AsByte();
 329511255            Vector128<sbyte> lutShift = Vector128.Create(decoder.Vector128LutShift).AsSByte();
 329511256            Vector128<sbyte> packBytesMask = Vector128.Create(0x06000102, 0x090A0405, 0x0C0D0E08, 0xffffffff).AsSByte();
 329511257            Vector128<byte> mergeConstant0 = Vector128.Create(0x01400140).AsByte();
 329511258            Vector128<short> mergeConstant1 = Vector128.Create(0x00011000).AsInt16();
 329511259            Vector128<byte> one = Vector128<byte>.One;
 329511260            Vector128<byte> mask2F = Vector128.Create(decoder.MaskSlashOrUnderscore);
 329511261            Vector128<byte> mask8F = Vector128.Create((byte)0x8F);
 329511262            Vector128<byte> shiftForUnderscore = Vector128.Create((byte)33);
 329511263            T* src = srcBytes;
 329511264            byte* dest = destBytes;
 1265
 1266            //while (remaining >= 24)
 1267            do
 1268            {
 385151269                if (!decoder.TryLoadVector128(src, srcStart, sourceLength, out Vector128<byte> str))
 1270                {
 1271                    break;
 1272                }
 1273
 1274                // lookup
 385151275                Vector128<byte> hiNibbles = Vector128.ShiftRightLogical(str.AsInt32(), 4).AsByte() & mask2F;
 1276
 385151277                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;
 83221289                if (Ssse3.IsSupported)
 1290                {
 83221291                    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;
 83221319                if (Ssse3.IsSupported)
 1320                {
 83221321                    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:
 83221349                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
 83221355                AssertWrite<Vector128<sbyte>>(dest, destStart, destLength);
 83221356                str.Store(dest);
 1357
 83221358                src += 16;
 83221359                dest += 12;
 1360            }
 83221361            while (src <= srcEnd);
 1362
 329511363            srcBytes = src;
 329511364            destBytes = dest;
 329511365        }
 1366#endif
 1367
 1368        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1369        private static unsafe void WriteThreeLowOrderBytes(byte* destination, int value)
 1370        {
 1489551371            destination[0] = (byte)(value >> 16);
 1489551372            destination[1] = (byte)(value >> 8);
 1489551373            destination[2] = (byte)value;
 1489551374        }
 1375
 1376        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1377        internal static bool IsWhiteSpace(int value)
 1378        {
 6807591379            Debug.Assert(value >= 0 && value <= ushort.MaxValue);
 1380            uint charMinusLowUInt32;
 6807591381            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            {
 364091549                AssertRead<Vector512<sbyte>>(src, srcStart, sourceLength);
 364091550                str = Vector512.Load(src).AsSByte();
 364091551                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            {
 315131558                AssertRead<Vector256<sbyte>>(src, srcStart, sourceLength);
 315131559                str = Avx.LoadVector256(src).AsSByte();
 315131560                return true;
 1561            }
 1562
 1563            [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1564            public unsafe bool TryLoadVector128(byte* src, byte* srcStart, int sourceLength, out Vector128<byte> str)
 1565            {
 362931566                AssertRead<Vector128<sbyte>>(src, srcStart, sourceLength);
 362931567                str = Vector128.LoadUnsafe(ref *src);
 362931568                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
 1055781587                uint t0 = source[0];
 1055781588                uint t1 = source[1];
 1055781589                uint t2 = source[2];
 1055781590                uint t3 = source[3];
 1591
 1055781592                int i0 = Unsafe.Add(ref decodingMap, (int)t0);
 1055781593                int i1 = Unsafe.Add(ref decodingMap, (int)t1);
 1055781594                int i2 = Unsafe.Add(ref decodingMap, (int)t2);
 1055781595                int i3 = Unsafe.Add(ref decodingMap, (int)t3);
 1596
 1055781597                i0 <<= 18;
 1055781598                i1 <<= 12;
 1055781599                i2 <<= 6;
 1600
 1055781601                i0 |= i3;
 1055781602                i1 |= i2;
 1603
 1055781604                i0 |= i1;
 1055781605                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;
 23571613                t2 = EncodingPad;
 23571614                t3 = EncodingPad;
 1615                switch (remaining)
 1616                {
 1617                    case 2:
 6291618                        t0 = srcEnd[-2];
 6291619                        t1 = srcEnd[-1];
 6291620                        break;
 1621                    case 3:
 6281622                        t0 = srcEnd[-3];
 6281623                        t1 = srcEnd[-2];
 6281624                        t2 = srcEnd[-1];
 6281625                        break;
 1626                    case 4:
 9281627                        t0 = srcEnd[-4];
 9281628                        t1 = srcEnd[-3];
 9281629                        t2 = srcEnd[-2];
 9281630                        t3 = srcEnd[-1];
 9281631                        break;
 1632                    default:
 1721633                        return -1;
 1634                }
 1635
 21851636                int i0 = Unsafe.Add(ref decodingMap, (IntPtr)t0);
 21851637                int i1 = Unsafe.Add(ref decodingMap, (IntPtr)t1);
 1638
 21851639                i0 <<= 18;
 21851640                i1 <<= 12;
 1641
 21851642                i0 |= i1;
 21851643                return i0;
 1644            }
 1645
 1646            [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1647            public int IndexOfAnyExceptWhiteSpace(ReadOnlySpan<byte> span)
 1648            {
 1302481649                for (int i = 0; i < span.Length; i++)
 1650                {
 650581651                    if (!IsWhiteSpace(span[i]))
 1652                    {
 307951653                        return i;
 1654                    }
 1655                }
 1656
 661657                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            {
 173161719                AssertRead<Vector512<ushort>>(src, srcStart, sourceLength);
 173161720                Vector512<ushort> utf16VectorLower = Vector512.Load(src);
 173161721                Vector512<ushort> utf16VectorUpper = Vector512.Load(src + 32);
 173161722                if (Ascii.VectorContainsNonAsciiChar(utf16VectorLower | utf16VectorUpper))
 1723                {
 01724                    str = default;
 01725                    return false;
 1726                }
 1727
 173161728                str = Ascii.ExtractAsciiVector(utf16VectorLower, utf16VectorUpper).AsSByte();
 173161729                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            {
 16721736                AssertRead<Vector256<sbyte>>(src, srcStart, sourceLength);
 16721737                Vector256<ushort> utf16VectorLower = Avx.LoadVector256(src);
 16721738                Vector256<ushort> utf16VectorUpper = Avx.LoadVector256(src + 16);
 1739
 16721740                if (Ascii.VectorContainsNonAsciiChar(utf16VectorLower | utf16VectorUpper))
 1741                {
 01742                    str = default;
 01743                    return false;
 1744                }
 1745
 16721746                str = Ascii.ExtractAsciiVector(utf16VectorLower, utf16VectorUpper).AsSByte();
 16721747                return true;
 1748            }
 1749
 1750            [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1751            public unsafe bool TryLoadVector128(ushort* src, ushort* srcStart, int sourceLength, out Vector128<byte> str
 1752            {
 22221753                AssertRead<Vector128<sbyte>>(src, srcStart, sourceLength);
 22221754                Vector128<ushort> utf16VectorLower = Vector128.LoadUnsafe(ref *src);
 22221755                Vector128<ushort> utf16VectorUpper = Vector128.LoadUnsafe(ref *src, 8);
 22221756                if (Ascii.VectorContainsNonAsciiChar(utf16VectorLower | utf16VectorUpper))
 1757                {
 01758                    str = default;
 01759                    return false;
 1760                }
 1761
 22221762                str = Ascii.ExtractAsciiVector(utf16VectorLower, utf16VectorUpper);
 22221763                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
 89501794                uint t0 = source[0];
 89501795                uint t1 = source[1];
 89501796                uint t2 = source[2];
 89501797                uint t3 = source[3];
 1798
 89501799                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
 89501804                int i0 = Unsafe.Add(ref decodingMap, (int)t0);
 89501805                int i1 = Unsafe.Add(ref decodingMap, (int)t1);
 89501806                int i2 = Unsafe.Add(ref decodingMap, (int)t2);
 89501807                int i3 = Unsafe.Add(ref decodingMap, (int)t3);
 1808
 89501809                i0 <<= 18;
 89501810                i1 <<= 12;
 89501811                i2 <<= 6;
 1812
 89501813                i0 |= i3;
 89501814                i1 |= i2;
 1815
 89501816                i0 |= i1;
 89501817                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;
 16381825                t2 = EncodingPad;
 16381826                t3 = EncodingPad;
 1827                switch (remaining)
 1828                {
 1829                    case 2:
 6131830                        t0 = srcEnd[-2];
 6131831                        t1 = srcEnd[-1];
 6131832                        break;
 1833                    case 3:
 4431834                        t0 = srcEnd[-3];
 4431835                        t1 = srcEnd[-2];
 4431836                        t2 = srcEnd[-1];
 4431837                        break;
 1838                    case 4:
 5821839                        t0 = srcEnd[-4];
 5821840                        t1 = srcEnd[-3];
 5821841                        t2 = srcEnd[-2];
 5821842                        t3 = srcEnd[-1];
 5821843                        break;
 1844                    default:
 01845                        return -1;
 1846                }
 1847
 16381848                if (((t0 | t1 | t2 | t3) & 0xffffff00) != 0)
 1849                {
 01850                    return -1;
 1851                }
 1852
 16381853                int i0 = Unsafe.Add(ref decodingMap, (IntPtr)t0);
 16381854                int i1 = Unsafe.Add(ref decodingMap, (IntPtr)t1);
 1855
 16381856                i0 <<= 18;
 16381857                i1 <<= 12;
 1858
 16381859                i0 |= i1;
 16381860                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
 491432            fixed (byte* srcBytes = &MemoryMarshal.GetReference(source))
 491433            fixed (T* destBytes = &MemoryMarshal.GetReference(destination))
 34            {
 491435                int srcLength = source.Length;
 491436                int destLength = destination.Length;
 491437                int maxSrcLength = encoder.GetMaxSrcLength(srcLength, destLength);
 38
 491439                byte* src = srcBytes;
 491440                T* dest = destBytes;
 491441                byte* srcEnd = srcBytes + (uint)srcLength;
 491442                byte* srcMax = srcBytes + (uint)maxSrcLength;
 43
 44#if NET
 491445                if (maxSrcLength >= 16)
 46                {
 355547                    byte* end = srcMax - 64;
 355548                    if (Vector512.IsHardwareAccelerated && Avx512Vbmi.IsSupported && (end >= src))
 49                    {
 238550                        Avx512Encode(encoder, ref src, ref dest, end, maxSrcLength, destLength, srcBytes, destBytes);
 51
 238552                        if (src == srcEnd)
 53                            goto DoneExit;
 54                    }
 55
 355556                    end = srcMax - 32;
 355557                    if (Avx2.IsSupported && (end >= src))
 58                    {
 205259                        Avx2Encode(encoder, ref src, ref dest, end, maxSrcLength, destLength, srcBytes, destBytes);
 60
 205261                        if (src == srcEnd)
 62                            goto DoneExit;
 63                    }
 64
 355565                    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
 355574                    end = srcMax - 16;
 355575                    if ((Ssse3.IsSupported || AdvSimd.Arm64.IsSupported || PackedSimd.IsSupported) && BitConverter.IsLit
 76                    {
 215777                        Vector128Encode(encoder, ref src, ref dest, end, maxSrcLength, destLength, srcBytes, destBytes);
 78
 215779                        if (src == srcEnd)
 80                            goto DoneExit;
 81                    }
 82                }
 83#endif
 491484                ref byte encodingMap = ref MemoryMarshal.GetReference(encoder.EncodingMap);
 85
 491486                srcMax -= 2;
 1664487                while (src < srcMax)
 88                {
 1173089                    encoder.EncodeThreeAndWrite(src, dest, ref encodingMap);
 1173090                    src += 3;
 1173091                    dest += 4;
 92                }
 93
 491494                if (srcMax + 2 != srcEnd)
 95                    goto DestinationTooSmallExit;
 96
 491497                if (!isFinalBlock)
 98                {
 163899                    if (src == srcEnd)
 582100                        goto DoneExit;
 101
 102                    goto NeedMoreData;
 103                }
 104
 3276105                if (src + 1 == srcEnd)
 106                {
 1226107                    encoder.EncodeOneOptionallyPadTwo(src, dest, ref encodingMap);
 1226108                    src += 1;
 1226109                    dest += encoder.IncrementPadTwo;
 110                }
 2050111                else if (src + 2 == srcEnd)
 112                {
 886113                    encoder.EncodeTwoOptionallyPadOne(src, dest, ref encodingMap);
 886114                    src += 2;
 886115                    dest += encoder.IncrementPadOne;
 116                }
 117
 118            DoneExit:
 3858119                bytesConsumed = (int)(src - srcBytes);
 3858120                bytesWritten = (int)(dest - destBytes);
 3858121                return OperationStatus.Done;
 122
 123            DestinationTooSmallExit:
 0124                bytesConsumed = (int)(src - srcBytes);
 0125                bytesWritten = (int)(dest - destBytes);
 0126                return OperationStatus.DestinationTooSmall;
 127
 128            NeedMoreData:
 1056129                bytesConsumed = (int)(src - srcBytes);
 1056130                bytesWritten = (int)(dest - destBytes);
 1056131                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
 2385148            byte* src = srcBytes;
 2385149            T* dest = destBytes;
 150
 151            // The JIT won't hoist these "constants", so help it
 2385152            Vector512<sbyte> shuffleVecVbmi = Vector512.Create(
 2385153                0x01020001, 0x04050304, 0x07080607, 0x0a0b090a,
 2385154                0x0d0e0c0d, 0x10110f10, 0x13141213, 0x16171516,
 2385155                0x191a1819, 0x1c1d1b1c, 0x1f201e1f, 0x22232122,
 2385156                0x25262425, 0x28292728, 0x2b2c2a2b, 0x2e2f2d2e).AsSByte();
 2385157            Vector512<sbyte> vbmiLookup = Vector512.Create(encoder.EncodingMap).AsSByte();
 158
 2385159            Vector512<ushort> maskAC = Vector512.Create((uint)0x0fc0fc00).AsUInt16();
 2385160            Vector512<uint> maskBB = Vector512.Create((uint)0x3f003f00);
 2385161            Vector512<ushort> shiftAC = Vector512.Create((uint)0x0006000a).AsUInt16();
 2385162            Vector512<ushort> shiftBB = Vector512.Create((uint)0x00080004).AsUInt16();
 163
 2385164            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]
 2385170            Vector512<sbyte> str = Vector512.Load(src).AsSByte();
 171
 23760172            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]
 26145176                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]
 26145181                Vector512<ushort> temp1 = (str.AsUInt16() & maskAC);
 182
 183                // temp2    = [...|00000000|00cccccc|00000000|00aaaaaa]
 26145184                Vector512<ushort> temp2 = Avx512BW.ShiftRightLogicalVariable(temp1, shiftAC).AsUInt16();
 185
 186                // temp3    = [...|ccdddddd|00000000|aabbbbbb|cccc0000]
 26145187                Vector512<ushort> temp3 = Avx512BW.ShiftLeftLogicalVariable(str.AsUInt16(), shiftBB).AsUInt16();
 188
 189                // str      = [...|00dddddd|00cccccc|00bbbbbb|00aaaaaa]
 26145190                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.
 26145193                str = Avx512Vbmi.PermuteVar64x8(vbmiLookup, str);
 194
 26145195                encoder.StoreVector512ToDestination(dest, destStart, destLength, str.AsByte());
 196
 26145197                src += 48;
 26145198                dest += 64;
 199
 26145200                if (src > srcEnd)
 201                    break;
 202
 23760203                AssertRead<Vector512<sbyte>>(src, srcStart, sourceLength);
 23760204                str = Vector512.Load(src).AsSByte();
 205            }
 206
 2385207            srcBytes = src;
 2385208            destBytes = dest;
 2385209        }
 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
 2052230            Vector256<sbyte> shuffleVec = Vector256.Create(
 2052231                5, 4, 6, 5,
 2052232                8, 7, 9, 8,
 2052233                11, 10, 12, 11,
 2052234                14, 13, 15, 14,
 2052235                1, 0, 2, 1,
 2052236                4, 3, 5, 4,
 2052237                7, 6, 8, 7,
 2052238                10, 9, 11, 10);
 239
 2052240            Vector256<sbyte> lut = Vector256.Create(
 2052241                65, 71, -4, -4,
 2052242                -4, -4, -4, -4,
 2052243                -4, -4, -4, -4,
 2052244                encoder.Avx2LutChar62, encoder.Avx2LutChar63, 0, 0,
 2052245                65, 71, -4, -4,
 2052246                -4, -4, -4, -4,
 2052247                -4, -4, -4, -4,
 2052248                encoder.Avx2LutChar62, encoder.Avx2LutChar63, 0, 0);
 249
 2052250            Vector256<sbyte> maskAC = Vector256.Create(0x0fc0fc00).AsSByte();
 2052251            Vector256<sbyte> maskBB = Vector256.Create(0x003f03f0).AsSByte();
 2052252            Vector256<ushort> shiftAC = Vector256.Create(0x04000040).AsUInt16();
 2052253            Vector256<short> shiftBB = Vector256.Create(0x01000010).AsInt16();
 2052254            Vector256<byte> const51 = Vector256.Create((byte)51);
 2052255            Vector256<sbyte> const25 = Vector256.Create((sbyte)25);
 256
 2052257            byte* src = srcBytes;
 2052258            T* dest = destBytes;
 259
 260            // first load is done at c-0 not to get a segfault
 2052261            AssertRead<Vector256<sbyte>>(src, srcStart, sourceLength);
 2052262            Vector256<sbyte> str = Avx.LoadVector256(src).AsSByte();
 263
 264            // shift by 4 bytes, as required by Reshuffle
 2052265            str = Avx2.PermuteVar8x32(str.AsInt32(), Vector256.Create(
 2052266                0, 0, 0, 0,
 2052267                0, 0, 0, 0,
 2052268                1, 0, 0, 0,
 2052269                2, 0, 0, 0,
 2052270                3, 0, 0, 0,
 2052271                4, 0, 0, 0,
 2052272                5, 0, 0, 0,
 2052273                6, 0, 0, 0).AsInt32()).AsSByte();
 274
 275            // Next loads are done at src-4, as required by Reshuffle, so shift it once
 2052276            src -= 4;
 277
 873278            while (true)
 279            {
 280                // Reshuffle
 2925281                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
 2925292                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
 2925303                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
 2925313                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
 2925323                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
 2925333                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:
 2925355                Vector256<byte> indices = Avx2.SubtractSaturate(str.AsByte(), const51);
 356
 357                // mask is 0xFF (-1) for range #[1..4] and 0x00 for range #0:
 2925358                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:
 2925361                Vector256<sbyte> tmp = indices.AsSByte() - mask;
 362
 363                // Add offsets to input values:
 2925364                str += Avx2.Shuffle(lut, tmp);
 365
 2925366                encoder.StoreVector256ToDestination(dest, destStart, destLength, str.AsByte());
 367
 2925368                src += 24;
 2925369                dest += 32;
 370
 2925371                if (src > srcEnd)
 372                    break;
 373
 374                // Load at src-4, as required by Reshuffle (already shifted by -4)
 873375                AssertRead<Vector256<sbyte>>(src, srcStart, sourceLength);
 873376                str = Avx.LoadVector256(src).AsSByte();
 377            }
 378
 2052379            srcBytes = src + 4;
 2052380            destBytes = dest;
 2052381        }
 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();
 2157459            Vector128<byte> lut = Vector128.Create(0xFCFC4741, 0xFCFCFCFC, 0xFCFCFCFC, encoder.Ssse3AdvSimdLutE3).AsByte
 2157460            Vector128<byte> maskAC = Vector128.Create(0x0fc0fc00).AsByte();
 2157461            Vector128<byte> maskBB = Vector128.Create(0x003f03f0).AsByte();
 2157462            Vector128<ushort> shiftAC = Vector128.Create(0x04000040).AsUInt16();
 2157463            Vector128<short> shiftBB = Vector128.Create(0x01000010).AsInt16();
 2157464            Vector128<byte> const51 = Vector128.Create((byte)51);
 2157465            Vector128<sbyte> const25 = Vector128.Create((sbyte)25);
 2157466            Vector128<byte> mask8F = Vector128.Create((byte)0x8F);
 467
 2157468            byte* src = srcBytes;
 2157469            T* dest = destBytes;
 470
 471            //while (remaining >= 16)
 472            do
 473            {
 2457474                AssertRead<Vector128<sbyte>>(src, srcStart, sourceLength);
 2457475                Vector128<byte> str = Vector128.LoadUnsafe(ref *src);
 476
 477                // Reshuffle
 2457478                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
 2457485                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
 2457492                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;
 2457499                if (Ssse3.IsSupported)
 500                {
 2457501                    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
 2457527                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
 2457533                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;
 2457552                if (Ssse3.IsSupported)
 553                {
 2457554                    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:
 2457572                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:
 2457575                Vector128<sbyte> tmp = indices.AsSByte() - mask;
 576
 577                // Add offsets to input values:
 2457578                str += SimdShuffle(lut, tmp.AsByte(), mask8F);
 579
 2457580                encoder.StoreVector128ToDestination(dest, destStart, destLength, str);
 581
 2457582                src += 12;
 2457583                dest += 16;
 584            }
 2457585            while (src <= srcEnd);
 586
 2157587            srcBytes = src;
 2157588            destBytes = dest;
 2157589        }
 590#endif
 591
 592        internal static unsafe OperationStatus EncodeToUtf8InPlace<TBase64Encoder>(TBase64Encoder encoder, Span<byte> bu
 593            where TBase64Encoder : IBase64Encoder<byte>
 594        {
 1638595            if (buffer.IsEmpty)
 596            {
 0597                bytesWritten = 0;
 0598                return OperationStatus.Done;
 599            }
 600
 1638601            fixed (byte* bufferBytes = &MemoryMarshal.GetReference(buffer))
 602            {
 1638603                int encodedLength = encoder.GetMaxEncodedLength(dataLength);
 1638604                if (buffer.Length < encodedLength)
 605                {
 0606                    bytesWritten = 0;
 0607                    return OperationStatus.DestinationTooSmall;
 608                }
 609
 1638610                int leftover = (int)((uint)dataLength % 3); // how many bytes after packs of 3
 611
 1638612                uint destinationIndex = encoder.GetInPlaceDestinationLength(encodedLength, leftover);
 1638613                uint sourceIndex = (uint)(dataLength - leftover);
 1638614                ref byte encodingMap = ref MemoryMarshal.GetReference(encoder.EncodingMap);
 615
 616                // encode last pack to avoid conditional in the main loop
 1638617                if (leftover != 0)
 618                {
 1056619                    if (leftover == 1)
 620                    {
 613621                        encoder.EncodeOneOptionallyPadTwo(bufferBytes + sourceIndex, bufferBytes + destinationIndex, ref
 622                    }
 623                    else
 624                    {
 443625                        encoder.EncodeTwoOptionallyPadOne(bufferBytes + sourceIndex, bufferBytes + destinationIndex, ref
 626                    }
 627
 1056628                    destinationIndex -= 4;
 629                }
 630
 1638631                sourceIndex -= 3;
 156064632                while ((int)sourceIndex >= 0)
 633                {
 154426634                    uint result = Encode(bufferBytes + sourceIndex, ref encodingMap);
 154426635                    Unsafe.WriteUnaligned(bufferBytes + destinationIndex, result);
 154426636                    destinationIndex -= 4;
 154426637                    sourceIndex -= 3;
 638                }
 639
 1638640                bytesWritten = encodedLength;
 1638641                return OperationStatus.Done;
 642            }
 643        }
 644
 645        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 646        private static unsafe uint Encode(byte* threeBytes, ref byte encodingMap)
 647        {
 154426648            uint t0 = threeBytes[0];
 154426649            uint t1 = threeBytes[1];
 154426650            uint t2 = threeBytes[2];
 651
 154426652            uint i = (t0 << 16) | (t1 << 8) | t2;
 653
 154426654            uint i0 = Unsafe.Add(ref encodingMap, (IntPtr)(i >> 18));
 154426655            uint i1 = Unsafe.Add(ref encodingMap, (IntPtr)((i >> 12) & 0x3F));
 154426656            uint i2 = Unsafe.Add(ref encodingMap, (IntPtr)((i >> 6) & 0x3F));
 154426657            uint i3 = Unsafe.Add(ref encodingMap, (IntPtr)(i & 0x3F));
 658
 154426659            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            {
 154426667                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
 1226680            uint i = t0 << 8;
 681
 1226682            uint i0 = Unsafe.Add(ref encodingMap, (IntPtr)(i >> 10));
 1226683            uint i1 = Unsafe.Add(ref encodingMap, (IntPtr)((i >> 4) & 0x3F));
 684
 685            uint result;
 686
 1226687            if (BitConverter.IsLittleEndian)
 688            {
 1226689                result = (i0 | (i1 << 16));
 690            }
 691            else
 692            {
 693                result = ((i0 << 16) | i1);
 694            }
 695
 1226696            Unsafe.WriteUnaligned(dest, result);
 1226697        }
 698
 699        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 700        public static unsafe void EncodeTwoOptionallyPadOne(byte* twoBytes, ushort* dest, ref byte encodingMap)
 701        {
 886702            uint t0 = twoBytes[0];
 886703            uint t1 = twoBytes[1];
 704
 886705            uint i = (t0 << 16) | (t1 << 8);
 706
 886707            ushort i0 = Unsafe.Add(ref encodingMap, (IntPtr)(i >> 18));
 886708            ushort i1 = Unsafe.Add(ref encodingMap, (IntPtr)((i >> 12) & 0x3F));
 886709            ushort i2 = Unsafe.Add(ref encodingMap, (IntPtr)((i >> 6) & 0x3F));
 710
 886711            dest[0] = i0;
 886712            dest[1] = i1;
 886713            dest[2] = i2;
 886714        }
 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            {
 26145858                AssertWrite<Vector512<short>>(dest, destStart, destLength);
 26145859                (Vector512<ushort> utf16LowVector, Vector512<ushort> utf16HighVector) = Vector512.Widen(str);
 26145860                utf16LowVector.Store(dest);
 26145861                utf16HighVector.Store(dest + 32);
 26145862            }
 863
 864            [MethodImpl(MethodImplOptions.AggressiveInlining)]
 865            public unsafe void StoreVector256ToDestination(ushort* dest, ushort* destStart, int destLength, Vector256<by
 866            {
 2925867                AssertWrite<Vector256<short>>(dest, destStart, destLength);
 2925868                (Vector256<ushort> utf16LowVector, Vector256<ushort> utf16HighVector) = Vector256.Widen(str);
 2925869                utf16LowVector.Store(dest);
 2925870                utf16HighVector.Store(dest + 16);
 2925871            }
 872
 873            [MethodImpl(MethodImplOptions.AggressiveInlining)]
 874            public unsafe void StoreVector128ToDestination(ushort* dest, ushort* destStart, int destLength, Vector128<by
 875            {
 2457876                AssertWrite<Vector128<short>>(dest, destStart, destLength);
 2457877                (Vector128<ushort> utf16LowVector, Vector128<ushort> utf16HighVector) = Vector128.Widen(str);
 2457878                utf16LowVector.Store(dest);
 2457879                utf16HighVector.Store(dest + 8);
 2457880            }
 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];
 11730901                uint t1 = threeBytes[1];
 11730902                uint t2 = threeBytes[2];
 903
 11730904                uint i = (t0 << 16) | (t1 << 8) | t2;
 905
 11730906                ulong i0 = Unsafe.Add(ref encodingMap, (IntPtr)(i >> 18));
 11730907                ulong i1 = Unsafe.Add(ref encodingMap, (IntPtr)((i >> 12) & 0x3F));
 11730908                ulong i2 = Unsafe.Add(ref encodingMap, (IntPtr)((i >> 6) & 0x3F));
 11730909                ulong i3 = Unsafe.Add(ref encodingMap, (IntPtr)(i & 0x3F));
 910
 911                ulong result;
 11730912                if (BitConverter.IsLittleEndian)
 913                {
 11730914                    result = i0 | (i1 << 16) | (i2 << 32) | (i3 << 48);
 915                }
 916                else
 917                {
 918                    result = (i0 << 48) | (i1 << 32) | (i2 << 16) | i3;
 919                }
 920
 11730921                Unsafe.WriteUnaligned(destination, result);
 11730922            }
 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        {
 13574218            int vectorElements = sizeof(TVector);
 13574219            byte* readEnd = src + vectorElements;
 13574220            byte* srcEnd = srcStart + srcLength;
 21
 13574222            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            }
 13574227        }
 28
 29        [Conditional("DEBUG")]
 30        internal static unsafe void AssertWrite<TVector>(byte* dest, byte* destStart, int destLength)
 31        {
 3944932            int vectorElements = sizeof(TVector);
 3944933            byte* writeEnd = dest + vectorElements;
 3944934            byte* destEnd = destStart + destLength;
 35
 3944936            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            }
 3944941        }
 42
 43        [Conditional("DEBUG")]
 44        internal static unsafe void AssertRead<TVector>(ushort* src, ushort* srcStart, int srcLength)
 45        {
 2121046            int vectorElements = sizeof(TVector);
 2121047            ushort* readEnd = src + vectorElements;
 2121048            ushort* srcEnd = srcStart + srcLength;
 49
 2121050            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            }
 2121055        }
 56
 57        [Conditional("DEBUG")]
 58        internal static unsafe void AssertWrite<TVector>(ushort* dest, ushort* destStart, int destLength)
 59        {
 3152760            int vectorElements = sizeof(TVector);
 3152761            ushort* writeEnd = dest + vectorElements;
 3152762            ushort* destEnd = destStart + destLength;
 63
 3152764            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            }
 3152769        }
 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        {
 327614            int length = 0, paddingCount = 0;
 163815            T lastChar = default;
 16
 163817            if (!base64Text.IsEmpty)
 18            {
 19#if NET
 3313820                while (!base64Text.IsEmpty)
 21                {
 3299522                    int index = validatable.IndexOfAnyExcept(base64Text);
 3299523                    if ((uint)index >= (uint)base64Text.Length)
 24                    {
 76925                        length += base64Text.Length;
 76926                        lastChar = base64Text[base64Text.Length - 1];
 76927                        break;
 28                    }
 29
 3222630                    length += index;
 3222631                    if (index != 0)
 32                    {
 3101233                        lastChar = base64Text[index - 1];
 34                    }
 35
 3222636                    T charToValidate = base64Text[index];
 3222637                    base64Text = base64Text.Slice(index + 1);
 38
 3222639                    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.
 4085543                        while (!base64Text.IsEmpty && validatable.IsWhiteSpace(base64Text[0]))
 44                        {
 935545                            base64Text = base64Text.Slice(1);
 46                        }
 3135747                        continue;
 48                    }
 49
 72650                    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.
 21657                    paddingCount = 1;
 634958                    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
 300594                        if (validatable.IsEncodingPad(charToValidateInPadding))
 95                        {
 96                            // There can be at most 2 padding chars.
 8997                            if (paddingCount >= 2)
 98                            {
 99                                goto Fail;
 100                            }
 101
 81102                            paddingCount++;
 103                        }
 2916104                        else if (!validatable.IsWhiteSpace(charToValidateInPadding))
 105                        {
 106                            // Invalid char was found.
 107                            goto Fail;
 108                        }
 109                    }
 110
 123111                    length += paddingCount;
 123112                    break;
 113                }
 114
 1035115                if (!validatable.ValidateAndDecodeLength(lastChar, length, paddingCount, out decodedLength))
 116                {
 117                    goto Fail;
 118                }
 119
 811120                return true;
 121            }
 122
 0123            decodedLength = 0;
 0124            return true;
 125
 126        Fail:
 827127            decodedLength = 0;
 827128            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&)