| | | 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 | | |
| | | 4 | | using System.Diagnostics; |
| | | 5 | | using System.Runtime.CompilerServices; |
| | | 6 | | using System.Runtime.InteropServices; |
| | | 7 | | using static System.Buffers.Text.Base64Helper; |
| | | 8 | | |
| | | 9 | | namespace System.Buffers.Text |
| | | 10 | | { |
| | | 11 | | public static partial class Base64 |
| | | 12 | | { |
| | | 13 | | private const int MaxStackallocThreshold = 256; |
| | | 14 | | |
| | | 15 | | /// <summary> |
| | | 16 | | /// Returns the maximum length (in bytes) of the result if you were to decode base 64 encoded text from a span o |
| | | 17 | | /// </summary> |
| | | 18 | | /// <param name="base64Length">The length of the base64-encoded input.</param> |
| | | 19 | | /// <returns>The maximum number of bytes that decoding could produce.</returns> |
| | | 20 | | /// <exception cref="ArgumentOutOfRangeException"> |
| | | 21 | | /// <paramref name="base64Length"/> is less than 0. |
| | | 22 | | /// </exception> |
| | | 23 | | /// <remarks> |
| | | 24 | | /// This method is equivalent to <see cref="GetMaxDecodedFromUtf8Length(int)"/>. |
| | | 25 | | /// </remarks> |
| | | 26 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 27 | | public static int GetMaxDecodedLength(int base64Length) |
| | | 28 | | { |
| | 1331200 | 29 | | ArgumentOutOfRangeException.ThrowIfNegative(base64Length); |
| | | 30 | | |
| | 1331200 | 31 | | return (base64Length >> 2) * 3; |
| | | 32 | | } |
| | | 33 | | |
| | | 34 | | /// <summary> |
| | | 35 | | /// Returns the maximum length (in bytes) of the result if you were to decode base 64 encoded text within a byte |
| | | 36 | | /// </summary> |
| | | 37 | | /// <exception cref="ArgumentOutOfRangeException"> |
| | | 38 | | /// Thrown when the specified <paramref name="length"/> is less than 0. |
| | | 39 | | /// </exception> |
| | | 40 | | /// <remarks> |
| | | 41 | | /// This method is equivalent to <see cref="GetMaxDecodedLength(int)"/>. |
| | | 42 | | /// </remarks> |
| | | 43 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | 1235856 | 44 | | public static int GetMaxDecodedFromUtf8Length(int length) => GetMaxDecodedLength(length); |
| | | 45 | | |
| | | 46 | | /// <summary> |
| | | 47 | | /// Decode the span of UTF-8 encoded text represented as base64 into binary data. |
| | | 48 | | /// If the input is not a multiple of 4, it will decode as much as it can, to the closest multiple of 4. |
| | | 49 | | /// </summary> |
| | | 50 | | /// <param name="utf8">The input span which contains UTF-8 encoded text in base64 that needs to be decoded.</par |
| | | 51 | | /// <param name="bytes">The output span which contains the result of the operation, i.e. the decoded binary data |
| | | 52 | | /// <param name="bytesConsumed">The number of input bytes consumed during the operation. This can be used to sli |
| | | 53 | | /// <param name="bytesWritten">The number of bytes written into the output span. This can be used to slice the o |
| | | 54 | | /// <param name="isFinalBlock"><see langword="true"/> (default) when the input span contains the entire data to |
| | | 55 | | /// Set to <see langword="true"/> when the source buffer contains the entirety of the data to decode. |
| | | 56 | | /// Set to <see langword="false"/> if this method is being called in a loop and if more input data may follow. |
| | | 57 | | /// At the end of the loop, call this (potentially with an empty source buffer) passing <see langword="true"/>.< |
| | | 58 | | /// <returns>It returns the OperationStatus enum values: |
| | | 59 | | /// - Done - on successful processing of the entire input span |
| | | 60 | | /// - DestinationTooSmall - if there is not enough space in the output span to fit the decoded input |
| | | 61 | | /// - NeedMoreData - only if <paramref name="isFinalBlock"/> is false and the input is not a multiple of 4, othe |
| | | 62 | | /// - InvalidData - if the input contains bytes outside of the expected base64 range, or if it contains invalid/ |
| | | 63 | | /// or if the input is incomplete (i.e. not a multiple of 4) and <paramref name="isFinalBlock"/> is <see langw |
| | | 64 | | /// </returns> |
| | | 65 | | public static OperationStatus DecodeFromUtf8(ReadOnlySpan<byte> utf8, Span<byte> bytes, out int bytesConsumed, o |
| | 71508 | 66 | | DecodeFrom(default(Base64DecoderByte), utf8, bytes, out bytesConsumed, out bytesWritten, isFinalBlock, ignor |
| | | 67 | | |
| | | 68 | | /// <summary> |
| | | 69 | | /// Decodes the span of UTF-8 encoded text represented as Base64 into binary data. |
| | | 70 | | /// </summary> |
| | | 71 | | /// <param name="source">The input span which contains UTF-8 encoded text in Base64 that needs to be decoded.</p |
| | | 72 | | /// <param name="destination">The output span which contains the result of the operation, i.e. the decoded binar |
| | | 73 | | /// <returns>The number of bytes written into <paramref name="destination"/>. This can be used to slice the outp |
| | | 74 | | /// <exception cref="ArgumentException">The buffer in <paramref name="destination"/> is too small to hold the en |
| | | 75 | | /// <exception cref="FormatException"><paramref name="source"/> contains an invalid Base64 character, |
| | | 76 | | /// more than two padding characters, or a non white space character among the padding characters.</exception> |
| | | 77 | | public static int DecodeFromUtf8(ReadOnlySpan<byte> source, Span<byte> destination) |
| | | 78 | | { |
| | 11918 | 79 | | OperationStatus status = DecodeFromUtf8(source, destination, out _, out int bytesWritten); |
| | | 80 | | |
| | 11918 | 81 | | if (status == OperationStatus.Done) |
| | | 82 | | { |
| | 11918 | 83 | | return bytesWritten; |
| | | 84 | | } |
| | | 85 | | |
| | 0 | 86 | | if (status == OperationStatus.DestinationTooSmall) |
| | | 87 | | { |
| | 0 | 88 | | throw new ArgumentException(SR.Argument_DestinationTooShort, nameof(destination)); |
| | | 89 | | } |
| | | 90 | | |
| | 0 | 91 | | Debug.Assert(status == OperationStatus.InvalidData); |
| | 0 | 92 | | throw new FormatException(SR.Format_BadBase64Char); |
| | | 93 | | } |
| | | 94 | | |
| | | 95 | | /// <summary> |
| | | 96 | | /// Decodes the span of UTF-8 encoded text represented as Base64 into binary data. |
| | | 97 | | /// </summary> |
| | | 98 | | /// <param name="source">The input span which contains UTF-8 encoded text in Base64 that needs to be decoded.</p |
| | | 99 | | /// <returns>A byte array which contains the result of the decoding operation.</returns> |
| | | 100 | | /// <exception cref="FormatException"><paramref name="source"/> contains an invalid Base64 character, |
| | | 101 | | /// more than two padding characters, or a non white space character among the padding characters.</exception> |
| | | 102 | | public static byte[] DecodeFromUtf8(ReadOnlySpan<byte> source) |
| | | 103 | | { |
| | 11918 | 104 | | int upperBound = GetMaxDecodedLength(source.Length); |
| | 11918 | 105 | | byte[]? rented = null; |
| | | 106 | | |
| | 11918 | 107 | | Span<byte> destination = (uint)upperBound <= MaxStackallocThreshold |
| | 11918 | 108 | | ? stackalloc byte[MaxStackallocThreshold] |
| | 11918 | 109 | | : (rented = ArrayPool<byte>.Shared.Rent(upperBound)); |
| | | 110 | | |
| | 11918 | 111 | | OperationStatus status = DecodeFromUtf8(source, destination, out _, out int bytesWritten); |
| | 11918 | 112 | | Debug.Assert(status is OperationStatus.Done or OperationStatus.InvalidData); |
| | 11918 | 113 | | byte[] result = destination.Slice(0, bytesWritten).ToArray(); |
| | | 114 | | |
| | 11918 | 115 | | if (rented is not null) |
| | | 116 | | { |
| | 6494 | 117 | | ArrayPool<byte>.Shared.Return(rented); |
| | | 118 | | } |
| | | 119 | | |
| | 11918 | 120 | | return status == OperationStatus.Done ? result : throw new FormatException(SR.Format_BadBase64Char); |
| | | 121 | | } |
| | | 122 | | |
| | | 123 | | /// <summary> |
| | | 124 | | /// Decodes the span of UTF-8 encoded text represented as Base64 into binary data. |
| | | 125 | | /// </summary> |
| | | 126 | | /// <param name="source">The input span which contains UTF-8 encoded text in Base64 that needs to be decoded.</p |
| | | 127 | | /// <param name="destination">The output span which contains the result of the operation, i.e. the decoded binar |
| | | 128 | | /// <param name="bytesWritten">When this method returns, contains the number of bytes written into the output sp |
| | | 129 | | /// <returns><see langword="true"/> if bytes decoded successfully, otherwise <see langword="false"/>.</returns> |
| | | 130 | | /// <exception cref="FormatException"><paramref name="source"/> contains an invalid Base64 character, |
| | | 131 | | /// more than two padding characters, or a non white space character among the padding characters.</exception> |
| | | 132 | | public static bool TryDecodeFromUtf8(ReadOnlySpan<byte> source, Span<byte> destination, out int bytesWritten) |
| | | 133 | | { |
| | 11918 | 134 | | OperationStatus status = DecodeFromUtf8(source, destination, out _, out bytesWritten); |
| | | 135 | | |
| | 11918 | 136 | | if (status == OperationStatus.InvalidData) |
| | | 137 | | { |
| | 0 | 138 | | throw new FormatException(SR.Format_BadBase64Char); |
| | | 139 | | } |
| | | 140 | | |
| | 11918 | 141 | | Debug.Assert(status is OperationStatus.Done or OperationStatus.DestinationTooSmall); |
| | 11918 | 142 | | return status == OperationStatus.Done; |
| | | 143 | | } |
| | | 144 | | |
| | | 145 | | /// <summary> |
| | | 146 | | /// Decode the span of UTF-8 encoded text in base 64 (in-place) into binary data. |
| | | 147 | | /// The decoded binary output is smaller than the text data contained in the input (the operation deflates the d |
| | | 148 | | /// If the input is not a multiple of 4, it will not decode any. |
| | | 149 | | /// </summary> |
| | | 150 | | /// <param name="buffer">The input span which contains the base 64 text data that needs to be decoded.</param> |
| | | 151 | | /// <param name="bytesWritten">The number of bytes written into the buffer.</param> |
| | | 152 | | /// <returns>It returns the OperationStatus enum values: |
| | | 153 | | /// - Done - on successful processing of the entire input span |
| | | 154 | | /// - InvalidData - if the input contains bytes outside of the expected base 64 range, or if it contains invalid |
| | | 155 | | /// or if the input is incomplete (i.e. not a multiple of 4). |
| | | 156 | | /// It does not return DestinationTooSmall since that is not possible for base 64 decoding. |
| | | 157 | | /// It does not return NeedMoreData since this method tramples the data in the buffer and |
| | | 158 | | /// hence can only be called once with all the data in the buffer. |
| | | 159 | | /// </returns> |
| | | 160 | | public static OperationStatus DecodeFromUtf8InPlace(Span<byte> buffer, out int bytesWritten) => |
| | 23836 | 161 | | Base64Helper.DecodeFromUtf8InPlace(default(Base64DecoderByte), buffer, out bytesWritten, ignoreWhiteSpace: t |
| | | 162 | | |
| | | 163 | | /// <summary> |
| | | 164 | | /// Decodes the span of unicode ASCII chars represented as Base64 into binary data. |
| | | 165 | | /// </summary> |
| | | 166 | | /// <param name="source">The input span which contains unicode ASCII chars in Base64 that needs to be decoded.</ |
| | | 167 | | /// <param name="destination">The output span which contains the result of the operation, i.e. the decoded binar |
| | | 168 | | /// <param name="charsConsumed">When this method returns, contains the number of input chars consumed during the |
| | | 169 | | /// <param name="bytesWritten">When this method returns, contains the number of bytes written into the output sp |
| | | 170 | | /// <param name="isFinalBlock"><see langword="true"/> when the input span contains the entirety of data to encod |
| | | 171 | | /// such as when calling in a loop. Calls with <see langword="false"/> should be followed up with another call w |
| | | 172 | | /// <returns>One of the enumeration values that indicates the success or failure of the operation.</returns> |
| | | 173 | | public static OperationStatus DecodeFromChars(ReadOnlySpan<char> source, Span<byte> destination, |
| | | 174 | | out int charsConsumed, out int bytesWritten, bool isFinalBlock = true) => |
| | 119170 | 175 | | DecodeFrom(default(Base64DecoderChar), MemoryMarshal.Cast<char, ushort>(source), destination, |
| | 119170 | 176 | | out charsConsumed, out bytesWritten, isFinalBlock, ignoreWhiteSpace: true); |
| | | 177 | | |
| | | 178 | | /// <summary> |
| | | 179 | | /// Decodes the span of unicode ASCII chars represented as Base64 into binary data. |
| | | 180 | | /// </summary> |
| | | 181 | | /// <param name="source">The input span which contains ASCII chars in Base64 that needs to be decoded.</param> |
| | | 182 | | /// <param name="destination">The output span which contains the result of the operation, i.e. the decoded binar |
| | | 183 | | /// <returns>The number of bytes written into the output span. This can be used to slice the output for subseque |
| | | 184 | | /// <exception cref="ArgumentException">The buffer in <paramref name="destination"/> is too small to hold the en |
| | | 185 | | /// <exception cref="FormatException"><paramref name="source"/> contains an invalid Base64 character, |
| | | 186 | | /// more than two padding characters, or a non white space character among the padding characters.</exception> |
| | | 187 | | public static int DecodeFromChars(ReadOnlySpan<char> source, Span<byte> destination) |
| | | 188 | | { |
| | 11918 | 189 | | OperationStatus status = DecodeFromChars(source, destination, out _, out int bytesWritten); |
| | | 190 | | |
| | 11918 | 191 | | if (status == OperationStatus.Done) |
| | | 192 | | { |
| | 11918 | 193 | | return bytesWritten; |
| | | 194 | | } |
| | | 195 | | |
| | 0 | 196 | | if (status == OperationStatus.DestinationTooSmall) |
| | | 197 | | { |
| | 0 | 198 | | throw new ArgumentException(SR.Argument_DestinationTooShort, nameof(destination)); |
| | | 199 | | } |
| | | 200 | | |
| | 0 | 201 | | Debug.Assert(status == OperationStatus.InvalidData); |
| | 0 | 202 | | throw new FormatException(SR.Format_BadBase64Char); |
| | | 203 | | } |
| | | 204 | | |
| | | 205 | | /// <summary> |
| | | 206 | | /// Decodes the span of unicode ASCII chars represented as Base64 into binary data. |
| | | 207 | | /// </summary> |
| | | 208 | | /// <param name="source">The input span which contains ASCII chars in Base64 that needs to be decoded.</param> |
| | | 209 | | /// <param name="destination">The output span which contains the result of the operation, i.e. the decoded binar |
| | | 210 | | /// <param name="bytesWritten">When this method returns, contains the number of bytes written into the output sp |
| | | 211 | | /// <returns><see langword="true"/> if bytes decoded successfully, otherwise <see langword="false"/>.</returns> |
| | | 212 | | /// <exception cref="FormatException"><paramref name="source"/> contains an invalid Base64 character, |
| | | 213 | | /// more than two padding characters, or a non white space character among the padding characters.</exception> |
| | | 214 | | public static bool TryDecodeFromChars(ReadOnlySpan<char> source, Span<byte> destination, out int bytesWritten) |
| | | 215 | | { |
| | 11918 | 216 | | OperationStatus status = DecodeFromChars(source, destination, out _, out bytesWritten); |
| | | 217 | | |
| | 11918 | 218 | | if (status == OperationStatus.InvalidData) |
| | | 219 | | { |
| | 0 | 220 | | throw new FormatException(SR.Format_BadBase64Char); |
| | | 221 | | } |
| | | 222 | | |
| | 11918 | 223 | | Debug.Assert(status is OperationStatus.Done or OperationStatus.DestinationTooSmall); |
| | 11918 | 224 | | return status == OperationStatus.Done; |
| | | 225 | | } |
| | | 226 | | |
| | | 227 | | /// <summary> |
| | | 228 | | /// Decodes the span of unicode ASCII chars represented as Base64 into binary data. |
| | | 229 | | /// </summary> |
| | | 230 | | /// <param name="source">The input span which contains ASCII chars in Base64 that needs to be decoded.</param> |
| | | 231 | | /// <returns>A byte array which contains the result of the decoding operation.</returns> |
| | | 232 | | /// <exception cref="FormatException"><paramref name="source"/> contains an invalid Base64 character, |
| | | 233 | | /// more than two padding characters, or a non white space character among the padding characters.</exception> |
| | | 234 | | public static byte[] DecodeFromChars(ReadOnlySpan<char> source) |
| | | 235 | | { |
| | 59590 | 236 | | int upperBound = GetMaxDecodedLength(source.Length); |
| | 59590 | 237 | | byte[]? rented = null; |
| | | 238 | | |
| | 59590 | 239 | | Span<byte> destination = (uint)upperBound <= MaxStackallocThreshold |
| | 59590 | 240 | | ? stackalloc byte[MaxStackallocThreshold] |
| | 59590 | 241 | | : (rented = ArrayPool<byte>.Shared.Rent(upperBound)); |
| | | 242 | | |
| | 59590 | 243 | | OperationStatus status = DecodeFromChars(source, destination, out _, out int bytesWritten); |
| | 59590 | 244 | | Debug.Assert(status is OperationStatus.Done or OperationStatus.InvalidData); |
| | 59590 | 245 | | byte[] result = destination.Slice(0, bytesWritten).ToArray(); |
| | | 246 | | |
| | 59590 | 247 | | if (rented is not null) |
| | | 248 | | { |
| | 32686 | 249 | | ArrayPool<byte>.Shared.Return(rented); |
| | | 250 | | } |
| | | 251 | | |
| | 59590 | 252 | | return status == OperationStatus.Done ? result : throw new FormatException(SR.Format_BadBase64Char); |
| | | 253 | | } |
| | | 254 | | } |
| | | 255 | | } |