diff --git a/src/Polyfill/Base64Url.cs b/src/Polyfill/Base64Url.cs index 179a8528..59bfcbb0 100644 --- a/src/Polyfill/Base64Url.cs +++ b/src/Polyfill/Base64Url.cs @@ -54,94 +54,61 @@ public static string EncodeToString(ReadOnlySpan source) return string.Empty; } - var base64 = Convert.ToBase64String(source.ToArray()); - return ToBase64UrlString(base64); + var length = EncodedLength(source.Length); + + if (length <= 256) + { + Span buffer = stackalloc char[256]; + buffer = buffer.Slice(0, length); + Encode(source, buffer); + return buffer.ToString(); + } + + var rented = ArrayPool.Shared.Rent(length); + Encode(source, rented); + var result = new string(rented, 0, length); + ArrayPool.Shared.Return(rented); + return result; } /// Encodes the span of binary data into UTF-16 encoded text represented as base-64-url. //Link: https://learn.microsoft.com/en-us/dotnet/api/system.buffers.text.base64url.encodetochars?view=net-11.0#system-buffers-text-base64url-encodetochars(system-readonlyspan((system-byte))-system-span((system-char))) public static int EncodeToChars(ReadOnlySpan source, Span destination) { - var encoded = EncodeToString(source); + var length = EncodedLength(source.Length); - if (encoded.Length > destination.Length) + if (length > destination.Length) { throw new ArgumentException("Destination is too small.", nameof(destination)); } - encoded.AsSpan().CopyTo(destination); - return encoded.Length; + Encode(source, destination); + return length; } /// Encodes the span of binary data into UTF-16 encoded text represented as base-64-url. //Link: https://learn.microsoft.com/en-us/dotnet/api/system.buffers.text.base64url.encodetochars?view=net-11.0#system-buffers-text-base64url-encodetochars(system-readonlyspan((system-byte))-system-span((system-char))-system-int32@-system-int32@-system-boolean) public static OperationStatus EncodeToChars(ReadOnlySpan source, Span destination, out int bytesConsumed, out int charsWritten, bool isFinalBlock = true) { - if (source.IsEmpty) - { - charsWritten = 0; - bytesConsumed = 0; - return OperationStatus.Done; - } - - var completeGroups = source.Length / 3; - var remainingBytes = source.Length % 3; - - if (!isFinalBlock) - { - var groupsWeCanFit = Math.Min(completeGroups, destination.Length / 4); - bytesConsumed = groupsWeCanFit * 3; - charsWritten = groupsWeCanFit * 4; - - if (bytesConsumed > 0) - { - EncodeToString(source.Slice(0, bytesConsumed)).AsSpan().CopyTo(destination); - } - - if (groupsWeCanFit < completeGroups) - { - return OperationStatus.DestinationTooSmall; - } - - return remainingBytes > 0 ? OperationStatus.NeedMoreData : OperationStatus.Done; - } - - var totalChars = GetEncodedLength(source.Length); - - if (totalChars <= destination.Length) - { - EncodeToString(source).AsSpan().CopyTo(destination); - charsWritten = totalChars; - bytesConsumed = source.Length; - return OperationStatus.Done; - } - - var fitting = destination.Length / 4; - bytesConsumed = fitting * 3; - charsWritten = fitting * 4; - - if (bytesConsumed > 0) - { - EncodeToString(source.Slice(0, bytesConsumed)).AsSpan().CopyTo(destination); - } - - return OperationStatus.DestinationTooSmall; + var status = PlanEncode(source.Length, destination.Length, isFinalBlock, out bytesConsumed, out charsWritten); + Encode(source.Slice(0, bytesConsumed), destination); + return status; } /// Tries to encode the span of binary data into UTF-16 encoded text represented as base-64-url. //Link: https://learn.microsoft.com/en-us/dotnet/api/system.buffers.text.base64url.tryencodetochars?view=net-11.0 public static bool TryEncodeToChars(ReadOnlySpan source, Span destination, out int charsWritten) { - var encoded = EncodeToString(source); + var length = EncodedLength(source.Length); - if (encoded.Length > destination.Length) + if (length > destination.Length) { charsWritten = 0; return false; } - encoded.AsSpan().CopyTo(destination); - charsWritten = encoded.Length; + Encode(source, destination); + charsWritten = length; return true; } @@ -149,14 +116,8 @@ public static bool TryEncodeToChars(ReadOnlySpan source, Span destin //Link: https://learn.microsoft.com/en-us/dotnet/api/system.buffers.text.base64url.encodetoutf8?view=net-11.0#system-buffers-text-base64url-encodetoutf8(system-readonlyspan((system-byte))) public static byte[] EncodeToUtf8(ReadOnlySpan source) { - var chars = EncodeToString(source); - var result = new byte[chars.Length]; - - for (var i = 0; i < chars.Length; i++) - { - result[i] = (byte)chars[i]; - } - + var result = new byte[EncodedLength(source.Length)]; + Encode(source, result); return result; } @@ -164,86 +125,40 @@ public static byte[] EncodeToUtf8(ReadOnlySpan source) //Link: https://learn.microsoft.com/en-us/dotnet/api/system.buffers.text.base64url.encodetoutf8?view=net-11.0#system-buffers-text-base64url-encodetoutf8(system-readonlyspan((system-byte))-system-span((system-byte))) public static int EncodeToUtf8(ReadOnlySpan source, Span destination) { - var encoded = EncodeToString(source); + var length = EncodedLength(source.Length); - if (encoded.Length > destination.Length) + if (length > destination.Length) { throw new ArgumentException("Destination is too small.", nameof(destination)); } - WriteStringToBytes(encoded, destination); - return encoded.Length; + Encode(source, destination); + return length; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. //Link: https://learn.microsoft.com/en-us/dotnet/api/system.buffers.text.base64url.encodetoutf8?view=net-11.0#system-buffers-text-base64url-encodetoutf8(system-readonlyspan((system-byte))-system-span((system-byte))-system-int32@-system-int32@-system-boolean) public static OperationStatus EncodeToUtf8(ReadOnlySpan source, Span destination, out int bytesConsumed, out int bytesWritten, bool isFinalBlock = true) { - if (source.IsEmpty) - { - bytesWritten = 0; - bytesConsumed = 0; - return OperationStatus.Done; - } - - var completeGroups = source.Length / 3; - var remainingBytes = source.Length % 3; - - if (!isFinalBlock) - { - var groupsWeCanFit = Math.Min(completeGroups, destination.Length / 4); - bytesConsumed = groupsWeCanFit * 3; - bytesWritten = groupsWeCanFit * 4; - - if (bytesConsumed > 0) - { - WriteStringToBytes(EncodeToString(source.Slice(0, bytesConsumed)), destination); - } - - if (groupsWeCanFit < completeGroups) - { - return OperationStatus.DestinationTooSmall; - } - - return remainingBytes > 0 ? OperationStatus.NeedMoreData : OperationStatus.Done; - } - - var totalBytes = GetEncodedLength(source.Length); - - if (totalBytes <= destination.Length) - { - WriteStringToBytes(EncodeToString(source), destination); - bytesWritten = totalBytes; - bytesConsumed = source.Length; - return OperationStatus.Done; - } - - var fitting = destination.Length / 4; - bytesConsumed = fitting * 3; - bytesWritten = fitting * 4; - - if (bytesConsumed > 0) - { - WriteStringToBytes(EncodeToString(source.Slice(0, bytesConsumed)), destination); - } - - return OperationStatus.DestinationTooSmall; + var status = PlanEncode(source.Length, destination.Length, isFinalBlock, out bytesConsumed, out bytesWritten); + Encode(source.Slice(0, bytesConsumed), destination); + return status; } /// Tries to encode the span of binary data into UTF-8 encoded text represented as base-64-url. //Link: https://learn.microsoft.com/en-us/dotnet/api/system.buffers.text.base64url.tryencodetoutf8?view=net-11.0 public static bool TryEncodeToUtf8(ReadOnlySpan source, Span destination, out int bytesWritten) { - var encoded = EncodeToString(source); + var length = EncodedLength(source.Length); - if (encoded.Length > destination.Length) + if (length > destination.Length) { bytesWritten = 0; return false; } - WriteStringToBytes(encoded, destination); - bytesWritten = encoded.Length; + Encode(source, destination); + bytesWritten = length; return true; } @@ -256,7 +171,7 @@ public static bool TryEncodeToUtf8InPlace(Span buffer, int dataLength, out throw new ArgumentOutOfRangeException(nameof(dataLength)); } - var encodedLength = GetEncodedLength(dataLength); + var encodedLength = EncodedLength(dataLength); if (encodedLength > buffer.Length) { @@ -264,10 +179,40 @@ public static bool TryEncodeToUtf8InPlace(Span buffer, int dataLength, out return false; } - var source = buffer.Slice(0, dataLength).ToArray(); - var encoded = EncodeToString(source); - WriteStringToBytes(encoded, buffer); - bytesWritten = encoded.Length; + // The output of a group never starts before its input, so encoding from the last group to + // the first reads every byte before it is overwritten. + var map = encodeMap; + var groups = dataLength / 3; + var sourceIndex = groups * 3; + var destinationIndex = groups * 4; + var remaining = dataLength - sourceIndex; + + if (remaining == 1) + { + var value = buffer[sourceIndex] << 16; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = buffer[sourceIndex] << 16 | buffer[sourceIndex + 1] << 8; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + buffer[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + } + + while (sourceIndex > 0) + { + sourceIndex -= 3; + destinationIndex -= 4; + var value = buffer[sourceIndex] << 16 | buffer[sourceIndex + 1] << 8 | buffer[sourceIndex + 2]; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + buffer[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + buffer[destinationIndex + 3] = (byte) map[value & 0x3F]; + } + + bytesWritten = encodedLength; return true; } @@ -423,28 +368,115 @@ public static bool IsValid(ReadOnlySpan utf8Base64UrlText, out int decoded return IsValid(chars, out decodedLength); } - static string ToBase64UrlString(string base64) + const string encodeMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + + static int EncodedLength(int bytesLength) => + checked((int) (((long) bytesLength * 4 + 2) / 3)); + + // Works out how much of the source an encode with the given destination size consumes. + static OperationStatus PlanEncode(int sourceLength, int destinationLength, bool isFinalBlock, out int bytesConsumed, out int written) { - var len = base64.Length; + if (isFinalBlock) + { + var total = EncodedLength(sourceLength); + + if (total <= destinationLength) + { + bytesConsumed = sourceLength; + written = total; + return OperationStatus.Done; + } + } - while (len > 0 && base64[len - 1] == '=') + // only complete groups are written when the whole of the source cannot be + var completeGroups = sourceLength / 3; + var groups = Math.Min(completeGroups, destinationLength / 4); + bytesConsumed = groups * 3; + written = groups * 4; + + if (isFinalBlock || groups < completeGroups) { - len--; + return OperationStatus.DestinationTooSmall; } - var chars = new char[len]; + if (sourceLength % 3 > 0) + { + return OperationStatus.NeedMoreData; + } - for (var i = 0; i < len; i++) + return OperationStatus.Done; + } + + // Encodes all of source. The destination must hold EncodedLength(source.Length) chars. + static void Encode(ReadOnlySpan source, Span destination) + { + var map = encodeMap; + var sourceIndex = 0; + var destinationIndex = 0; + var end = source.Length - 2; + + while (sourceIndex < end) { - chars[i] = base64[i] switch - { - '+' => '-', - '/' => '_', - _ => base64[i] - }; + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8 | source[sourceIndex + 2]; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = map[value >> 6 & 0x3F]; + destination[destinationIndex + 3] = map[value & 0x3F]; + sourceIndex += 3; + destinationIndex += 4; + } + + var remaining = source.Length - sourceIndex; + + if (remaining == 1) + { + var value = source[sourceIndex] << 16; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = map[value >> 6 & 0x3F]; + } + } + + // Encodes all of source. The destination must hold EncodedLength(source.Length) bytes. + static void Encode(ReadOnlySpan source, Span destination) + { + var map = encodeMap; + var sourceIndex = 0; + var destinationIndex = 0; + var end = source.Length - 2; + + while (sourceIndex < end) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8 | source[sourceIndex + 2]; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + destination[destinationIndex + 3] = (byte) map[value & 0x3F]; + sourceIndex += 3; + destinationIndex += 4; } - return new string(chars); + var remaining = source.Length - sourceIndex; + + if (remaining == 1) + { + var value = source[sourceIndex] << 16; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + } } // Decodes block by block. Whitespace (space, tab, CR, LF) is skipped anywhere, and the final @@ -622,14 +654,6 @@ static int DecodeValue(char c) return -1; } - static void WriteStringToBytes(string source, Span destination) - { - for (var i = 0; i < source.Length; i++) - { - destination[i] = (byte)source[i]; - } - } - static char[] BytesToChars(ReadOnlySpan source) { var chars = new char[source.Length]; diff --git a/src/Split/net461/Base64Url.cs b/src/Split/net461/Base64Url.cs index 817dcd19..88920e01 100644 --- a/src/Split/net461/Base64Url.cs +++ b/src/Split/net461/Base64Url.cs @@ -42,152 +42,87 @@ public static string EncodeToString(ReadOnlySpan source) { return string.Empty; } - var base64 = Convert.ToBase64String(source.ToArray()); - return ToBase64UrlString(base64); + var length = EncodedLength(source.Length); + if (length <= 256) + { + Span buffer = stackalloc char[256]; + buffer = buffer.Slice(0, length); + Encode(source, buffer); + return buffer.ToString(); + } + var rented = ArrayPool.Shared.Rent(length); + Encode(source, rented); + var result = new string(rented, 0, length); + ArrayPool.Shared.Return(rented); + return result; } /// Encodes the span of binary data into UTF-16 encoded text represented as base-64-url. public static int EncodeToChars(ReadOnlySpan source, Span destination) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { throw new ArgumentException("Destination is too small.", nameof(destination)); } - encoded.AsSpan().CopyTo(destination); - return encoded.Length; + Encode(source, destination); + return length; } /// Encodes the span of binary data into UTF-16 encoded text represented as base-64-url. public static OperationStatus EncodeToChars(ReadOnlySpan source, Span destination, out int bytesConsumed, out int charsWritten, bool isFinalBlock = true) { - if (source.IsEmpty) - { - charsWritten = 0; - bytesConsumed = 0; - return OperationStatus.Done; - } - var completeGroups = source.Length / 3; - var remainingBytes = source.Length % 3; - if (!isFinalBlock) - { - var groupsWeCanFit = Math.Min(completeGroups, destination.Length / 4); - bytesConsumed = groupsWeCanFit * 3; - charsWritten = groupsWeCanFit * 4; - if (bytesConsumed > 0) - { - EncodeToString(source.Slice(0, bytesConsumed)).AsSpan().CopyTo(destination); - } - if (groupsWeCanFit < completeGroups) - { - return OperationStatus.DestinationTooSmall; - } - return remainingBytes > 0 ? OperationStatus.NeedMoreData : OperationStatus.Done; - } - var totalChars = GetEncodedLength(source.Length); - if (totalChars <= destination.Length) - { - EncodeToString(source).AsSpan().CopyTo(destination); - charsWritten = totalChars; - bytesConsumed = source.Length; - return OperationStatus.Done; - } - var fitting = destination.Length / 4; - bytesConsumed = fitting * 3; - charsWritten = fitting * 4; - if (bytesConsumed > 0) - { - EncodeToString(source.Slice(0, bytesConsumed)).AsSpan().CopyTo(destination); - } - return OperationStatus.DestinationTooSmall; + var status = PlanEncode(source.Length, destination.Length, isFinalBlock, out bytesConsumed, out charsWritten); + Encode(source.Slice(0, bytesConsumed), destination); + return status; } /// Tries to encode the span of binary data into UTF-16 encoded text represented as base-64-url. public static bool TryEncodeToChars(ReadOnlySpan source, Span destination, out int charsWritten) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { charsWritten = 0; return false; } - encoded.AsSpan().CopyTo(destination); - charsWritten = encoded.Length; + Encode(source, destination); + charsWritten = length; return true; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static byte[] EncodeToUtf8(ReadOnlySpan source) { - var chars = EncodeToString(source); - var result = new byte[chars.Length]; - for (var i = 0; i < chars.Length; i++) - { - result[i] = (byte)chars[i]; - } + var result = new byte[EncodedLength(source.Length)]; + Encode(source, result); return result; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static int EncodeToUtf8(ReadOnlySpan source, Span destination) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { throw new ArgumentException("Destination is too small.", nameof(destination)); } - WriteStringToBytes(encoded, destination); - return encoded.Length; + Encode(source, destination); + return length; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static OperationStatus EncodeToUtf8(ReadOnlySpan source, Span destination, out int bytesConsumed, out int bytesWritten, bool isFinalBlock = true) { - if (source.IsEmpty) - { - bytesWritten = 0; - bytesConsumed = 0; - return OperationStatus.Done; - } - var completeGroups = source.Length / 3; - var remainingBytes = source.Length % 3; - if (!isFinalBlock) - { - var groupsWeCanFit = Math.Min(completeGroups, destination.Length / 4); - bytesConsumed = groupsWeCanFit * 3; - bytesWritten = groupsWeCanFit * 4; - if (bytesConsumed > 0) - { - WriteStringToBytes(EncodeToString(source.Slice(0, bytesConsumed)), destination); - } - if (groupsWeCanFit < completeGroups) - { - return OperationStatus.DestinationTooSmall; - } - return remainingBytes > 0 ? OperationStatus.NeedMoreData : OperationStatus.Done; - } - var totalBytes = GetEncodedLength(source.Length); - if (totalBytes <= destination.Length) - { - WriteStringToBytes(EncodeToString(source), destination); - bytesWritten = totalBytes; - bytesConsumed = source.Length; - return OperationStatus.Done; - } - var fitting = destination.Length / 4; - bytesConsumed = fitting * 3; - bytesWritten = fitting * 4; - if (bytesConsumed > 0) - { - WriteStringToBytes(EncodeToString(source.Slice(0, bytesConsumed)), destination); - } - return OperationStatus.DestinationTooSmall; + var status = PlanEncode(source.Length, destination.Length, isFinalBlock, out bytesConsumed, out bytesWritten); + Encode(source.Slice(0, bytesConsumed), destination); + return status; } /// Tries to encode the span of binary data into UTF-8 encoded text represented as base-64-url. public static bool TryEncodeToUtf8(ReadOnlySpan source, Span destination, out int bytesWritten) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { bytesWritten = 0; return false; } - WriteStringToBytes(encoded, destination); - bytesWritten = encoded.Length; + Encode(source, destination); + bytesWritten = length; return true; } /// Encodes the span of binary data (in-place) into UTF-8 encoded text represented as base-64-url. @@ -197,16 +132,41 @@ public static bool TryEncodeToUtf8InPlace(Span buffer, int dataLength, out { throw new ArgumentOutOfRangeException(nameof(dataLength)); } - var encodedLength = GetEncodedLength(dataLength); + var encodedLength = EncodedLength(dataLength); if (encodedLength > buffer.Length) { bytesWritten = 0; return false; } - var source = buffer.Slice(0, dataLength).ToArray(); - var encoded = EncodeToString(source); - WriteStringToBytes(encoded, buffer); - bytesWritten = encoded.Length; + var map = encodeMap; + var groups = dataLength / 3; + var sourceIndex = groups * 3; + var destinationIndex = groups * 4; + var remaining = dataLength - sourceIndex; + if (remaining == 1) + { + var value = buffer[sourceIndex] << 16; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = buffer[sourceIndex] << 16 | buffer[sourceIndex + 1] << 8; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + buffer[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + } + while (sourceIndex > 0) + { + sourceIndex -= 3; + destinationIndex -= 4; + var value = buffer[sourceIndex] << 16 | buffer[sourceIndex + 1] << 8 | buffer[sourceIndex + 2]; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + buffer[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + buffer[destinationIndex + 3] = (byte) map[value & 0x3F]; + } + bytesWritten = encodedLength; return true; } /// Decodes the span of UTF-16 encoded text represented as base-64-url into binary data. @@ -322,24 +282,96 @@ public static bool IsValid(ReadOnlySpan utf8Base64UrlText, out int decoded var chars = BytesToChars(utf8Base64UrlText); return IsValid(chars, out decodedLength); } - static string ToBase64UrlString(string base64) + const string encodeMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + static int EncodedLength(int bytesLength) => + checked((int) (((long) bytesLength * 4 + 2) / 3)); + static OperationStatus PlanEncode(int sourceLength, int destinationLength, bool isFinalBlock, out int bytesConsumed, out int written) { - var len = base64.Length; - while (len > 0 && base64[len - 1] == '=') + if (isFinalBlock) { - len--; + var total = EncodedLength(sourceLength); + if (total <= destinationLength) + { + bytesConsumed = sourceLength; + written = total; + return OperationStatus.Done; + } } - var chars = new char[len]; - for (var i = 0; i < len; i++) + var completeGroups = sourceLength / 3; + var groups = Math.Min(completeGroups, destinationLength / 4); + bytesConsumed = groups * 3; + written = groups * 4; + if (isFinalBlock || groups < completeGroups) { - chars[i] = base64[i] switch - { - '+' => '-', - '/' => '_', - _ => base64[i] - }; + return OperationStatus.DestinationTooSmall; + } + if (sourceLength % 3 > 0) + { + return OperationStatus.NeedMoreData; + } + return OperationStatus.Done; + } + static void Encode(ReadOnlySpan source, Span destination) + { + var map = encodeMap; + var sourceIndex = 0; + var destinationIndex = 0; + var end = source.Length - 2; + while (sourceIndex < end) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8 | source[sourceIndex + 2]; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = map[value >> 6 & 0x3F]; + destination[destinationIndex + 3] = map[value & 0x3F]; + sourceIndex += 3; + destinationIndex += 4; + } + var remaining = source.Length - sourceIndex; + if (remaining == 1) + { + var value = source[sourceIndex] << 16; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = map[value >> 6 & 0x3F]; + } + } + static void Encode(ReadOnlySpan source, Span destination) + { + var map = encodeMap; + var sourceIndex = 0; + var destinationIndex = 0; + var end = source.Length - 2; + while (sourceIndex < end) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8 | source[sourceIndex + 2]; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + destination[destinationIndex + 3] = (byte) map[value & 0x3F]; + sourceIndex += 3; + destinationIndex += 4; + } + var remaining = source.Length - sourceIndex; + if (remaining == 1) + { + var value = source[sourceIndex] << 16; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; } - return new string(chars); } static OperationStatus Decode(ReadOnlySpan source, Span destination, bool write, out int charsConsumed, out int bytesWritten, bool isFinalBlock) { @@ -478,13 +510,6 @@ static int DecodeValue(char c) } return -1; } - static void WriteStringToBytes(string source, Span destination) - { - for (var i = 0; i < source.Length; i++) - { - destination[i] = (byte)source[i]; - } - } static char[] BytesToChars(ReadOnlySpan source) { var chars = new char[source.Length]; diff --git a/src/Split/net462/Base64Url.cs b/src/Split/net462/Base64Url.cs index 817dcd19..88920e01 100644 --- a/src/Split/net462/Base64Url.cs +++ b/src/Split/net462/Base64Url.cs @@ -42,152 +42,87 @@ public static string EncodeToString(ReadOnlySpan source) { return string.Empty; } - var base64 = Convert.ToBase64String(source.ToArray()); - return ToBase64UrlString(base64); + var length = EncodedLength(source.Length); + if (length <= 256) + { + Span buffer = stackalloc char[256]; + buffer = buffer.Slice(0, length); + Encode(source, buffer); + return buffer.ToString(); + } + var rented = ArrayPool.Shared.Rent(length); + Encode(source, rented); + var result = new string(rented, 0, length); + ArrayPool.Shared.Return(rented); + return result; } /// Encodes the span of binary data into UTF-16 encoded text represented as base-64-url. public static int EncodeToChars(ReadOnlySpan source, Span destination) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { throw new ArgumentException("Destination is too small.", nameof(destination)); } - encoded.AsSpan().CopyTo(destination); - return encoded.Length; + Encode(source, destination); + return length; } /// Encodes the span of binary data into UTF-16 encoded text represented as base-64-url. public static OperationStatus EncodeToChars(ReadOnlySpan source, Span destination, out int bytesConsumed, out int charsWritten, bool isFinalBlock = true) { - if (source.IsEmpty) - { - charsWritten = 0; - bytesConsumed = 0; - return OperationStatus.Done; - } - var completeGroups = source.Length / 3; - var remainingBytes = source.Length % 3; - if (!isFinalBlock) - { - var groupsWeCanFit = Math.Min(completeGroups, destination.Length / 4); - bytesConsumed = groupsWeCanFit * 3; - charsWritten = groupsWeCanFit * 4; - if (bytesConsumed > 0) - { - EncodeToString(source.Slice(0, bytesConsumed)).AsSpan().CopyTo(destination); - } - if (groupsWeCanFit < completeGroups) - { - return OperationStatus.DestinationTooSmall; - } - return remainingBytes > 0 ? OperationStatus.NeedMoreData : OperationStatus.Done; - } - var totalChars = GetEncodedLength(source.Length); - if (totalChars <= destination.Length) - { - EncodeToString(source).AsSpan().CopyTo(destination); - charsWritten = totalChars; - bytesConsumed = source.Length; - return OperationStatus.Done; - } - var fitting = destination.Length / 4; - bytesConsumed = fitting * 3; - charsWritten = fitting * 4; - if (bytesConsumed > 0) - { - EncodeToString(source.Slice(0, bytesConsumed)).AsSpan().CopyTo(destination); - } - return OperationStatus.DestinationTooSmall; + var status = PlanEncode(source.Length, destination.Length, isFinalBlock, out bytesConsumed, out charsWritten); + Encode(source.Slice(0, bytesConsumed), destination); + return status; } /// Tries to encode the span of binary data into UTF-16 encoded text represented as base-64-url. public static bool TryEncodeToChars(ReadOnlySpan source, Span destination, out int charsWritten) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { charsWritten = 0; return false; } - encoded.AsSpan().CopyTo(destination); - charsWritten = encoded.Length; + Encode(source, destination); + charsWritten = length; return true; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static byte[] EncodeToUtf8(ReadOnlySpan source) { - var chars = EncodeToString(source); - var result = new byte[chars.Length]; - for (var i = 0; i < chars.Length; i++) - { - result[i] = (byte)chars[i]; - } + var result = new byte[EncodedLength(source.Length)]; + Encode(source, result); return result; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static int EncodeToUtf8(ReadOnlySpan source, Span destination) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { throw new ArgumentException("Destination is too small.", nameof(destination)); } - WriteStringToBytes(encoded, destination); - return encoded.Length; + Encode(source, destination); + return length; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static OperationStatus EncodeToUtf8(ReadOnlySpan source, Span destination, out int bytesConsumed, out int bytesWritten, bool isFinalBlock = true) { - if (source.IsEmpty) - { - bytesWritten = 0; - bytesConsumed = 0; - return OperationStatus.Done; - } - var completeGroups = source.Length / 3; - var remainingBytes = source.Length % 3; - if (!isFinalBlock) - { - var groupsWeCanFit = Math.Min(completeGroups, destination.Length / 4); - bytesConsumed = groupsWeCanFit * 3; - bytesWritten = groupsWeCanFit * 4; - if (bytesConsumed > 0) - { - WriteStringToBytes(EncodeToString(source.Slice(0, bytesConsumed)), destination); - } - if (groupsWeCanFit < completeGroups) - { - return OperationStatus.DestinationTooSmall; - } - return remainingBytes > 0 ? OperationStatus.NeedMoreData : OperationStatus.Done; - } - var totalBytes = GetEncodedLength(source.Length); - if (totalBytes <= destination.Length) - { - WriteStringToBytes(EncodeToString(source), destination); - bytesWritten = totalBytes; - bytesConsumed = source.Length; - return OperationStatus.Done; - } - var fitting = destination.Length / 4; - bytesConsumed = fitting * 3; - bytesWritten = fitting * 4; - if (bytesConsumed > 0) - { - WriteStringToBytes(EncodeToString(source.Slice(0, bytesConsumed)), destination); - } - return OperationStatus.DestinationTooSmall; + var status = PlanEncode(source.Length, destination.Length, isFinalBlock, out bytesConsumed, out bytesWritten); + Encode(source.Slice(0, bytesConsumed), destination); + return status; } /// Tries to encode the span of binary data into UTF-8 encoded text represented as base-64-url. public static bool TryEncodeToUtf8(ReadOnlySpan source, Span destination, out int bytesWritten) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { bytesWritten = 0; return false; } - WriteStringToBytes(encoded, destination); - bytesWritten = encoded.Length; + Encode(source, destination); + bytesWritten = length; return true; } /// Encodes the span of binary data (in-place) into UTF-8 encoded text represented as base-64-url. @@ -197,16 +132,41 @@ public static bool TryEncodeToUtf8InPlace(Span buffer, int dataLength, out { throw new ArgumentOutOfRangeException(nameof(dataLength)); } - var encodedLength = GetEncodedLength(dataLength); + var encodedLength = EncodedLength(dataLength); if (encodedLength > buffer.Length) { bytesWritten = 0; return false; } - var source = buffer.Slice(0, dataLength).ToArray(); - var encoded = EncodeToString(source); - WriteStringToBytes(encoded, buffer); - bytesWritten = encoded.Length; + var map = encodeMap; + var groups = dataLength / 3; + var sourceIndex = groups * 3; + var destinationIndex = groups * 4; + var remaining = dataLength - sourceIndex; + if (remaining == 1) + { + var value = buffer[sourceIndex] << 16; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = buffer[sourceIndex] << 16 | buffer[sourceIndex + 1] << 8; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + buffer[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + } + while (sourceIndex > 0) + { + sourceIndex -= 3; + destinationIndex -= 4; + var value = buffer[sourceIndex] << 16 | buffer[sourceIndex + 1] << 8 | buffer[sourceIndex + 2]; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + buffer[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + buffer[destinationIndex + 3] = (byte) map[value & 0x3F]; + } + bytesWritten = encodedLength; return true; } /// Decodes the span of UTF-16 encoded text represented as base-64-url into binary data. @@ -322,24 +282,96 @@ public static bool IsValid(ReadOnlySpan utf8Base64UrlText, out int decoded var chars = BytesToChars(utf8Base64UrlText); return IsValid(chars, out decodedLength); } - static string ToBase64UrlString(string base64) + const string encodeMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + static int EncodedLength(int bytesLength) => + checked((int) (((long) bytesLength * 4 + 2) / 3)); + static OperationStatus PlanEncode(int sourceLength, int destinationLength, bool isFinalBlock, out int bytesConsumed, out int written) { - var len = base64.Length; - while (len > 0 && base64[len - 1] == '=') + if (isFinalBlock) { - len--; + var total = EncodedLength(sourceLength); + if (total <= destinationLength) + { + bytesConsumed = sourceLength; + written = total; + return OperationStatus.Done; + } } - var chars = new char[len]; - for (var i = 0; i < len; i++) + var completeGroups = sourceLength / 3; + var groups = Math.Min(completeGroups, destinationLength / 4); + bytesConsumed = groups * 3; + written = groups * 4; + if (isFinalBlock || groups < completeGroups) { - chars[i] = base64[i] switch - { - '+' => '-', - '/' => '_', - _ => base64[i] - }; + return OperationStatus.DestinationTooSmall; + } + if (sourceLength % 3 > 0) + { + return OperationStatus.NeedMoreData; + } + return OperationStatus.Done; + } + static void Encode(ReadOnlySpan source, Span destination) + { + var map = encodeMap; + var sourceIndex = 0; + var destinationIndex = 0; + var end = source.Length - 2; + while (sourceIndex < end) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8 | source[sourceIndex + 2]; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = map[value >> 6 & 0x3F]; + destination[destinationIndex + 3] = map[value & 0x3F]; + sourceIndex += 3; + destinationIndex += 4; + } + var remaining = source.Length - sourceIndex; + if (remaining == 1) + { + var value = source[sourceIndex] << 16; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = map[value >> 6 & 0x3F]; + } + } + static void Encode(ReadOnlySpan source, Span destination) + { + var map = encodeMap; + var sourceIndex = 0; + var destinationIndex = 0; + var end = source.Length - 2; + while (sourceIndex < end) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8 | source[sourceIndex + 2]; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + destination[destinationIndex + 3] = (byte) map[value & 0x3F]; + sourceIndex += 3; + destinationIndex += 4; + } + var remaining = source.Length - sourceIndex; + if (remaining == 1) + { + var value = source[sourceIndex] << 16; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; } - return new string(chars); } static OperationStatus Decode(ReadOnlySpan source, Span destination, bool write, out int charsConsumed, out int bytesWritten, bool isFinalBlock) { @@ -478,13 +510,6 @@ static int DecodeValue(char c) } return -1; } - static void WriteStringToBytes(string source, Span destination) - { - for (var i = 0; i < source.Length; i++) - { - destination[i] = (byte)source[i]; - } - } static char[] BytesToChars(ReadOnlySpan source) { var chars = new char[source.Length]; diff --git a/src/Split/net47/Base64Url.cs b/src/Split/net47/Base64Url.cs index 817dcd19..88920e01 100644 --- a/src/Split/net47/Base64Url.cs +++ b/src/Split/net47/Base64Url.cs @@ -42,152 +42,87 @@ public static string EncodeToString(ReadOnlySpan source) { return string.Empty; } - var base64 = Convert.ToBase64String(source.ToArray()); - return ToBase64UrlString(base64); + var length = EncodedLength(source.Length); + if (length <= 256) + { + Span buffer = stackalloc char[256]; + buffer = buffer.Slice(0, length); + Encode(source, buffer); + return buffer.ToString(); + } + var rented = ArrayPool.Shared.Rent(length); + Encode(source, rented); + var result = new string(rented, 0, length); + ArrayPool.Shared.Return(rented); + return result; } /// Encodes the span of binary data into UTF-16 encoded text represented as base-64-url. public static int EncodeToChars(ReadOnlySpan source, Span destination) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { throw new ArgumentException("Destination is too small.", nameof(destination)); } - encoded.AsSpan().CopyTo(destination); - return encoded.Length; + Encode(source, destination); + return length; } /// Encodes the span of binary data into UTF-16 encoded text represented as base-64-url. public static OperationStatus EncodeToChars(ReadOnlySpan source, Span destination, out int bytesConsumed, out int charsWritten, bool isFinalBlock = true) { - if (source.IsEmpty) - { - charsWritten = 0; - bytesConsumed = 0; - return OperationStatus.Done; - } - var completeGroups = source.Length / 3; - var remainingBytes = source.Length % 3; - if (!isFinalBlock) - { - var groupsWeCanFit = Math.Min(completeGroups, destination.Length / 4); - bytesConsumed = groupsWeCanFit * 3; - charsWritten = groupsWeCanFit * 4; - if (bytesConsumed > 0) - { - EncodeToString(source.Slice(0, bytesConsumed)).AsSpan().CopyTo(destination); - } - if (groupsWeCanFit < completeGroups) - { - return OperationStatus.DestinationTooSmall; - } - return remainingBytes > 0 ? OperationStatus.NeedMoreData : OperationStatus.Done; - } - var totalChars = GetEncodedLength(source.Length); - if (totalChars <= destination.Length) - { - EncodeToString(source).AsSpan().CopyTo(destination); - charsWritten = totalChars; - bytesConsumed = source.Length; - return OperationStatus.Done; - } - var fitting = destination.Length / 4; - bytesConsumed = fitting * 3; - charsWritten = fitting * 4; - if (bytesConsumed > 0) - { - EncodeToString(source.Slice(0, bytesConsumed)).AsSpan().CopyTo(destination); - } - return OperationStatus.DestinationTooSmall; + var status = PlanEncode(source.Length, destination.Length, isFinalBlock, out bytesConsumed, out charsWritten); + Encode(source.Slice(0, bytesConsumed), destination); + return status; } /// Tries to encode the span of binary data into UTF-16 encoded text represented as base-64-url. public static bool TryEncodeToChars(ReadOnlySpan source, Span destination, out int charsWritten) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { charsWritten = 0; return false; } - encoded.AsSpan().CopyTo(destination); - charsWritten = encoded.Length; + Encode(source, destination); + charsWritten = length; return true; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static byte[] EncodeToUtf8(ReadOnlySpan source) { - var chars = EncodeToString(source); - var result = new byte[chars.Length]; - for (var i = 0; i < chars.Length; i++) - { - result[i] = (byte)chars[i]; - } + var result = new byte[EncodedLength(source.Length)]; + Encode(source, result); return result; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static int EncodeToUtf8(ReadOnlySpan source, Span destination) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { throw new ArgumentException("Destination is too small.", nameof(destination)); } - WriteStringToBytes(encoded, destination); - return encoded.Length; + Encode(source, destination); + return length; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static OperationStatus EncodeToUtf8(ReadOnlySpan source, Span destination, out int bytesConsumed, out int bytesWritten, bool isFinalBlock = true) { - if (source.IsEmpty) - { - bytesWritten = 0; - bytesConsumed = 0; - return OperationStatus.Done; - } - var completeGroups = source.Length / 3; - var remainingBytes = source.Length % 3; - if (!isFinalBlock) - { - var groupsWeCanFit = Math.Min(completeGroups, destination.Length / 4); - bytesConsumed = groupsWeCanFit * 3; - bytesWritten = groupsWeCanFit * 4; - if (bytesConsumed > 0) - { - WriteStringToBytes(EncodeToString(source.Slice(0, bytesConsumed)), destination); - } - if (groupsWeCanFit < completeGroups) - { - return OperationStatus.DestinationTooSmall; - } - return remainingBytes > 0 ? OperationStatus.NeedMoreData : OperationStatus.Done; - } - var totalBytes = GetEncodedLength(source.Length); - if (totalBytes <= destination.Length) - { - WriteStringToBytes(EncodeToString(source), destination); - bytesWritten = totalBytes; - bytesConsumed = source.Length; - return OperationStatus.Done; - } - var fitting = destination.Length / 4; - bytesConsumed = fitting * 3; - bytesWritten = fitting * 4; - if (bytesConsumed > 0) - { - WriteStringToBytes(EncodeToString(source.Slice(0, bytesConsumed)), destination); - } - return OperationStatus.DestinationTooSmall; + var status = PlanEncode(source.Length, destination.Length, isFinalBlock, out bytesConsumed, out bytesWritten); + Encode(source.Slice(0, bytesConsumed), destination); + return status; } /// Tries to encode the span of binary data into UTF-8 encoded text represented as base-64-url. public static bool TryEncodeToUtf8(ReadOnlySpan source, Span destination, out int bytesWritten) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { bytesWritten = 0; return false; } - WriteStringToBytes(encoded, destination); - bytesWritten = encoded.Length; + Encode(source, destination); + bytesWritten = length; return true; } /// Encodes the span of binary data (in-place) into UTF-8 encoded text represented as base-64-url. @@ -197,16 +132,41 @@ public static bool TryEncodeToUtf8InPlace(Span buffer, int dataLength, out { throw new ArgumentOutOfRangeException(nameof(dataLength)); } - var encodedLength = GetEncodedLength(dataLength); + var encodedLength = EncodedLength(dataLength); if (encodedLength > buffer.Length) { bytesWritten = 0; return false; } - var source = buffer.Slice(0, dataLength).ToArray(); - var encoded = EncodeToString(source); - WriteStringToBytes(encoded, buffer); - bytesWritten = encoded.Length; + var map = encodeMap; + var groups = dataLength / 3; + var sourceIndex = groups * 3; + var destinationIndex = groups * 4; + var remaining = dataLength - sourceIndex; + if (remaining == 1) + { + var value = buffer[sourceIndex] << 16; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = buffer[sourceIndex] << 16 | buffer[sourceIndex + 1] << 8; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + buffer[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + } + while (sourceIndex > 0) + { + sourceIndex -= 3; + destinationIndex -= 4; + var value = buffer[sourceIndex] << 16 | buffer[sourceIndex + 1] << 8 | buffer[sourceIndex + 2]; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + buffer[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + buffer[destinationIndex + 3] = (byte) map[value & 0x3F]; + } + bytesWritten = encodedLength; return true; } /// Decodes the span of UTF-16 encoded text represented as base-64-url into binary data. @@ -322,24 +282,96 @@ public static bool IsValid(ReadOnlySpan utf8Base64UrlText, out int decoded var chars = BytesToChars(utf8Base64UrlText); return IsValid(chars, out decodedLength); } - static string ToBase64UrlString(string base64) + const string encodeMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + static int EncodedLength(int bytesLength) => + checked((int) (((long) bytesLength * 4 + 2) / 3)); + static OperationStatus PlanEncode(int sourceLength, int destinationLength, bool isFinalBlock, out int bytesConsumed, out int written) { - var len = base64.Length; - while (len > 0 && base64[len - 1] == '=') + if (isFinalBlock) { - len--; + var total = EncodedLength(sourceLength); + if (total <= destinationLength) + { + bytesConsumed = sourceLength; + written = total; + return OperationStatus.Done; + } } - var chars = new char[len]; - for (var i = 0; i < len; i++) + var completeGroups = sourceLength / 3; + var groups = Math.Min(completeGroups, destinationLength / 4); + bytesConsumed = groups * 3; + written = groups * 4; + if (isFinalBlock || groups < completeGroups) { - chars[i] = base64[i] switch - { - '+' => '-', - '/' => '_', - _ => base64[i] - }; + return OperationStatus.DestinationTooSmall; + } + if (sourceLength % 3 > 0) + { + return OperationStatus.NeedMoreData; + } + return OperationStatus.Done; + } + static void Encode(ReadOnlySpan source, Span destination) + { + var map = encodeMap; + var sourceIndex = 0; + var destinationIndex = 0; + var end = source.Length - 2; + while (sourceIndex < end) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8 | source[sourceIndex + 2]; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = map[value >> 6 & 0x3F]; + destination[destinationIndex + 3] = map[value & 0x3F]; + sourceIndex += 3; + destinationIndex += 4; + } + var remaining = source.Length - sourceIndex; + if (remaining == 1) + { + var value = source[sourceIndex] << 16; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = map[value >> 6 & 0x3F]; + } + } + static void Encode(ReadOnlySpan source, Span destination) + { + var map = encodeMap; + var sourceIndex = 0; + var destinationIndex = 0; + var end = source.Length - 2; + while (sourceIndex < end) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8 | source[sourceIndex + 2]; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + destination[destinationIndex + 3] = (byte) map[value & 0x3F]; + sourceIndex += 3; + destinationIndex += 4; + } + var remaining = source.Length - sourceIndex; + if (remaining == 1) + { + var value = source[sourceIndex] << 16; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; } - return new string(chars); } static OperationStatus Decode(ReadOnlySpan source, Span destination, bool write, out int charsConsumed, out int bytesWritten, bool isFinalBlock) { @@ -478,13 +510,6 @@ static int DecodeValue(char c) } return -1; } - static void WriteStringToBytes(string source, Span destination) - { - for (var i = 0; i < source.Length; i++) - { - destination[i] = (byte)source[i]; - } - } static char[] BytesToChars(ReadOnlySpan source) { var chars = new char[source.Length]; diff --git a/src/Split/net471/Base64Url.cs b/src/Split/net471/Base64Url.cs index 817dcd19..88920e01 100644 --- a/src/Split/net471/Base64Url.cs +++ b/src/Split/net471/Base64Url.cs @@ -42,152 +42,87 @@ public static string EncodeToString(ReadOnlySpan source) { return string.Empty; } - var base64 = Convert.ToBase64String(source.ToArray()); - return ToBase64UrlString(base64); + var length = EncodedLength(source.Length); + if (length <= 256) + { + Span buffer = stackalloc char[256]; + buffer = buffer.Slice(0, length); + Encode(source, buffer); + return buffer.ToString(); + } + var rented = ArrayPool.Shared.Rent(length); + Encode(source, rented); + var result = new string(rented, 0, length); + ArrayPool.Shared.Return(rented); + return result; } /// Encodes the span of binary data into UTF-16 encoded text represented as base-64-url. public static int EncodeToChars(ReadOnlySpan source, Span destination) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { throw new ArgumentException("Destination is too small.", nameof(destination)); } - encoded.AsSpan().CopyTo(destination); - return encoded.Length; + Encode(source, destination); + return length; } /// Encodes the span of binary data into UTF-16 encoded text represented as base-64-url. public static OperationStatus EncodeToChars(ReadOnlySpan source, Span destination, out int bytesConsumed, out int charsWritten, bool isFinalBlock = true) { - if (source.IsEmpty) - { - charsWritten = 0; - bytesConsumed = 0; - return OperationStatus.Done; - } - var completeGroups = source.Length / 3; - var remainingBytes = source.Length % 3; - if (!isFinalBlock) - { - var groupsWeCanFit = Math.Min(completeGroups, destination.Length / 4); - bytesConsumed = groupsWeCanFit * 3; - charsWritten = groupsWeCanFit * 4; - if (bytesConsumed > 0) - { - EncodeToString(source.Slice(0, bytesConsumed)).AsSpan().CopyTo(destination); - } - if (groupsWeCanFit < completeGroups) - { - return OperationStatus.DestinationTooSmall; - } - return remainingBytes > 0 ? OperationStatus.NeedMoreData : OperationStatus.Done; - } - var totalChars = GetEncodedLength(source.Length); - if (totalChars <= destination.Length) - { - EncodeToString(source).AsSpan().CopyTo(destination); - charsWritten = totalChars; - bytesConsumed = source.Length; - return OperationStatus.Done; - } - var fitting = destination.Length / 4; - bytesConsumed = fitting * 3; - charsWritten = fitting * 4; - if (bytesConsumed > 0) - { - EncodeToString(source.Slice(0, bytesConsumed)).AsSpan().CopyTo(destination); - } - return OperationStatus.DestinationTooSmall; + var status = PlanEncode(source.Length, destination.Length, isFinalBlock, out bytesConsumed, out charsWritten); + Encode(source.Slice(0, bytesConsumed), destination); + return status; } /// Tries to encode the span of binary data into UTF-16 encoded text represented as base-64-url. public static bool TryEncodeToChars(ReadOnlySpan source, Span destination, out int charsWritten) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { charsWritten = 0; return false; } - encoded.AsSpan().CopyTo(destination); - charsWritten = encoded.Length; + Encode(source, destination); + charsWritten = length; return true; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static byte[] EncodeToUtf8(ReadOnlySpan source) { - var chars = EncodeToString(source); - var result = new byte[chars.Length]; - for (var i = 0; i < chars.Length; i++) - { - result[i] = (byte)chars[i]; - } + var result = new byte[EncodedLength(source.Length)]; + Encode(source, result); return result; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static int EncodeToUtf8(ReadOnlySpan source, Span destination) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { throw new ArgumentException("Destination is too small.", nameof(destination)); } - WriteStringToBytes(encoded, destination); - return encoded.Length; + Encode(source, destination); + return length; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static OperationStatus EncodeToUtf8(ReadOnlySpan source, Span destination, out int bytesConsumed, out int bytesWritten, bool isFinalBlock = true) { - if (source.IsEmpty) - { - bytesWritten = 0; - bytesConsumed = 0; - return OperationStatus.Done; - } - var completeGroups = source.Length / 3; - var remainingBytes = source.Length % 3; - if (!isFinalBlock) - { - var groupsWeCanFit = Math.Min(completeGroups, destination.Length / 4); - bytesConsumed = groupsWeCanFit * 3; - bytesWritten = groupsWeCanFit * 4; - if (bytesConsumed > 0) - { - WriteStringToBytes(EncodeToString(source.Slice(0, bytesConsumed)), destination); - } - if (groupsWeCanFit < completeGroups) - { - return OperationStatus.DestinationTooSmall; - } - return remainingBytes > 0 ? OperationStatus.NeedMoreData : OperationStatus.Done; - } - var totalBytes = GetEncodedLength(source.Length); - if (totalBytes <= destination.Length) - { - WriteStringToBytes(EncodeToString(source), destination); - bytesWritten = totalBytes; - bytesConsumed = source.Length; - return OperationStatus.Done; - } - var fitting = destination.Length / 4; - bytesConsumed = fitting * 3; - bytesWritten = fitting * 4; - if (bytesConsumed > 0) - { - WriteStringToBytes(EncodeToString(source.Slice(0, bytesConsumed)), destination); - } - return OperationStatus.DestinationTooSmall; + var status = PlanEncode(source.Length, destination.Length, isFinalBlock, out bytesConsumed, out bytesWritten); + Encode(source.Slice(0, bytesConsumed), destination); + return status; } /// Tries to encode the span of binary data into UTF-8 encoded text represented as base-64-url. public static bool TryEncodeToUtf8(ReadOnlySpan source, Span destination, out int bytesWritten) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { bytesWritten = 0; return false; } - WriteStringToBytes(encoded, destination); - bytesWritten = encoded.Length; + Encode(source, destination); + bytesWritten = length; return true; } /// Encodes the span of binary data (in-place) into UTF-8 encoded text represented as base-64-url. @@ -197,16 +132,41 @@ public static bool TryEncodeToUtf8InPlace(Span buffer, int dataLength, out { throw new ArgumentOutOfRangeException(nameof(dataLength)); } - var encodedLength = GetEncodedLength(dataLength); + var encodedLength = EncodedLength(dataLength); if (encodedLength > buffer.Length) { bytesWritten = 0; return false; } - var source = buffer.Slice(0, dataLength).ToArray(); - var encoded = EncodeToString(source); - WriteStringToBytes(encoded, buffer); - bytesWritten = encoded.Length; + var map = encodeMap; + var groups = dataLength / 3; + var sourceIndex = groups * 3; + var destinationIndex = groups * 4; + var remaining = dataLength - sourceIndex; + if (remaining == 1) + { + var value = buffer[sourceIndex] << 16; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = buffer[sourceIndex] << 16 | buffer[sourceIndex + 1] << 8; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + buffer[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + } + while (sourceIndex > 0) + { + sourceIndex -= 3; + destinationIndex -= 4; + var value = buffer[sourceIndex] << 16 | buffer[sourceIndex + 1] << 8 | buffer[sourceIndex + 2]; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + buffer[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + buffer[destinationIndex + 3] = (byte) map[value & 0x3F]; + } + bytesWritten = encodedLength; return true; } /// Decodes the span of UTF-16 encoded text represented as base-64-url into binary data. @@ -322,24 +282,96 @@ public static bool IsValid(ReadOnlySpan utf8Base64UrlText, out int decoded var chars = BytesToChars(utf8Base64UrlText); return IsValid(chars, out decodedLength); } - static string ToBase64UrlString(string base64) + const string encodeMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + static int EncodedLength(int bytesLength) => + checked((int) (((long) bytesLength * 4 + 2) / 3)); + static OperationStatus PlanEncode(int sourceLength, int destinationLength, bool isFinalBlock, out int bytesConsumed, out int written) { - var len = base64.Length; - while (len > 0 && base64[len - 1] == '=') + if (isFinalBlock) { - len--; + var total = EncodedLength(sourceLength); + if (total <= destinationLength) + { + bytesConsumed = sourceLength; + written = total; + return OperationStatus.Done; + } } - var chars = new char[len]; - for (var i = 0; i < len; i++) + var completeGroups = sourceLength / 3; + var groups = Math.Min(completeGroups, destinationLength / 4); + bytesConsumed = groups * 3; + written = groups * 4; + if (isFinalBlock || groups < completeGroups) { - chars[i] = base64[i] switch - { - '+' => '-', - '/' => '_', - _ => base64[i] - }; + return OperationStatus.DestinationTooSmall; + } + if (sourceLength % 3 > 0) + { + return OperationStatus.NeedMoreData; + } + return OperationStatus.Done; + } + static void Encode(ReadOnlySpan source, Span destination) + { + var map = encodeMap; + var sourceIndex = 0; + var destinationIndex = 0; + var end = source.Length - 2; + while (sourceIndex < end) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8 | source[sourceIndex + 2]; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = map[value >> 6 & 0x3F]; + destination[destinationIndex + 3] = map[value & 0x3F]; + sourceIndex += 3; + destinationIndex += 4; + } + var remaining = source.Length - sourceIndex; + if (remaining == 1) + { + var value = source[sourceIndex] << 16; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = map[value >> 6 & 0x3F]; + } + } + static void Encode(ReadOnlySpan source, Span destination) + { + var map = encodeMap; + var sourceIndex = 0; + var destinationIndex = 0; + var end = source.Length - 2; + while (sourceIndex < end) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8 | source[sourceIndex + 2]; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + destination[destinationIndex + 3] = (byte) map[value & 0x3F]; + sourceIndex += 3; + destinationIndex += 4; + } + var remaining = source.Length - sourceIndex; + if (remaining == 1) + { + var value = source[sourceIndex] << 16; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; } - return new string(chars); } static OperationStatus Decode(ReadOnlySpan source, Span destination, bool write, out int charsConsumed, out int bytesWritten, bool isFinalBlock) { @@ -478,13 +510,6 @@ static int DecodeValue(char c) } return -1; } - static void WriteStringToBytes(string source, Span destination) - { - for (var i = 0; i < source.Length; i++) - { - destination[i] = (byte)source[i]; - } - } static char[] BytesToChars(ReadOnlySpan source) { var chars = new char[source.Length]; diff --git a/src/Split/net472/Base64Url.cs b/src/Split/net472/Base64Url.cs index 817dcd19..88920e01 100644 --- a/src/Split/net472/Base64Url.cs +++ b/src/Split/net472/Base64Url.cs @@ -42,152 +42,87 @@ public static string EncodeToString(ReadOnlySpan source) { return string.Empty; } - var base64 = Convert.ToBase64String(source.ToArray()); - return ToBase64UrlString(base64); + var length = EncodedLength(source.Length); + if (length <= 256) + { + Span buffer = stackalloc char[256]; + buffer = buffer.Slice(0, length); + Encode(source, buffer); + return buffer.ToString(); + } + var rented = ArrayPool.Shared.Rent(length); + Encode(source, rented); + var result = new string(rented, 0, length); + ArrayPool.Shared.Return(rented); + return result; } /// Encodes the span of binary data into UTF-16 encoded text represented as base-64-url. public static int EncodeToChars(ReadOnlySpan source, Span destination) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { throw new ArgumentException("Destination is too small.", nameof(destination)); } - encoded.AsSpan().CopyTo(destination); - return encoded.Length; + Encode(source, destination); + return length; } /// Encodes the span of binary data into UTF-16 encoded text represented as base-64-url. public static OperationStatus EncodeToChars(ReadOnlySpan source, Span destination, out int bytesConsumed, out int charsWritten, bool isFinalBlock = true) { - if (source.IsEmpty) - { - charsWritten = 0; - bytesConsumed = 0; - return OperationStatus.Done; - } - var completeGroups = source.Length / 3; - var remainingBytes = source.Length % 3; - if (!isFinalBlock) - { - var groupsWeCanFit = Math.Min(completeGroups, destination.Length / 4); - bytesConsumed = groupsWeCanFit * 3; - charsWritten = groupsWeCanFit * 4; - if (bytesConsumed > 0) - { - EncodeToString(source.Slice(0, bytesConsumed)).AsSpan().CopyTo(destination); - } - if (groupsWeCanFit < completeGroups) - { - return OperationStatus.DestinationTooSmall; - } - return remainingBytes > 0 ? OperationStatus.NeedMoreData : OperationStatus.Done; - } - var totalChars = GetEncodedLength(source.Length); - if (totalChars <= destination.Length) - { - EncodeToString(source).AsSpan().CopyTo(destination); - charsWritten = totalChars; - bytesConsumed = source.Length; - return OperationStatus.Done; - } - var fitting = destination.Length / 4; - bytesConsumed = fitting * 3; - charsWritten = fitting * 4; - if (bytesConsumed > 0) - { - EncodeToString(source.Slice(0, bytesConsumed)).AsSpan().CopyTo(destination); - } - return OperationStatus.DestinationTooSmall; + var status = PlanEncode(source.Length, destination.Length, isFinalBlock, out bytesConsumed, out charsWritten); + Encode(source.Slice(0, bytesConsumed), destination); + return status; } /// Tries to encode the span of binary data into UTF-16 encoded text represented as base-64-url. public static bool TryEncodeToChars(ReadOnlySpan source, Span destination, out int charsWritten) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { charsWritten = 0; return false; } - encoded.AsSpan().CopyTo(destination); - charsWritten = encoded.Length; + Encode(source, destination); + charsWritten = length; return true; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static byte[] EncodeToUtf8(ReadOnlySpan source) { - var chars = EncodeToString(source); - var result = new byte[chars.Length]; - for (var i = 0; i < chars.Length; i++) - { - result[i] = (byte)chars[i]; - } + var result = new byte[EncodedLength(source.Length)]; + Encode(source, result); return result; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static int EncodeToUtf8(ReadOnlySpan source, Span destination) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { throw new ArgumentException("Destination is too small.", nameof(destination)); } - WriteStringToBytes(encoded, destination); - return encoded.Length; + Encode(source, destination); + return length; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static OperationStatus EncodeToUtf8(ReadOnlySpan source, Span destination, out int bytesConsumed, out int bytesWritten, bool isFinalBlock = true) { - if (source.IsEmpty) - { - bytesWritten = 0; - bytesConsumed = 0; - return OperationStatus.Done; - } - var completeGroups = source.Length / 3; - var remainingBytes = source.Length % 3; - if (!isFinalBlock) - { - var groupsWeCanFit = Math.Min(completeGroups, destination.Length / 4); - bytesConsumed = groupsWeCanFit * 3; - bytesWritten = groupsWeCanFit * 4; - if (bytesConsumed > 0) - { - WriteStringToBytes(EncodeToString(source.Slice(0, bytesConsumed)), destination); - } - if (groupsWeCanFit < completeGroups) - { - return OperationStatus.DestinationTooSmall; - } - return remainingBytes > 0 ? OperationStatus.NeedMoreData : OperationStatus.Done; - } - var totalBytes = GetEncodedLength(source.Length); - if (totalBytes <= destination.Length) - { - WriteStringToBytes(EncodeToString(source), destination); - bytesWritten = totalBytes; - bytesConsumed = source.Length; - return OperationStatus.Done; - } - var fitting = destination.Length / 4; - bytesConsumed = fitting * 3; - bytesWritten = fitting * 4; - if (bytesConsumed > 0) - { - WriteStringToBytes(EncodeToString(source.Slice(0, bytesConsumed)), destination); - } - return OperationStatus.DestinationTooSmall; + var status = PlanEncode(source.Length, destination.Length, isFinalBlock, out bytesConsumed, out bytesWritten); + Encode(source.Slice(0, bytesConsumed), destination); + return status; } /// Tries to encode the span of binary data into UTF-8 encoded text represented as base-64-url. public static bool TryEncodeToUtf8(ReadOnlySpan source, Span destination, out int bytesWritten) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { bytesWritten = 0; return false; } - WriteStringToBytes(encoded, destination); - bytesWritten = encoded.Length; + Encode(source, destination); + bytesWritten = length; return true; } /// Encodes the span of binary data (in-place) into UTF-8 encoded text represented as base-64-url. @@ -197,16 +132,41 @@ public static bool TryEncodeToUtf8InPlace(Span buffer, int dataLength, out { throw new ArgumentOutOfRangeException(nameof(dataLength)); } - var encodedLength = GetEncodedLength(dataLength); + var encodedLength = EncodedLength(dataLength); if (encodedLength > buffer.Length) { bytesWritten = 0; return false; } - var source = buffer.Slice(0, dataLength).ToArray(); - var encoded = EncodeToString(source); - WriteStringToBytes(encoded, buffer); - bytesWritten = encoded.Length; + var map = encodeMap; + var groups = dataLength / 3; + var sourceIndex = groups * 3; + var destinationIndex = groups * 4; + var remaining = dataLength - sourceIndex; + if (remaining == 1) + { + var value = buffer[sourceIndex] << 16; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = buffer[sourceIndex] << 16 | buffer[sourceIndex + 1] << 8; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + buffer[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + } + while (sourceIndex > 0) + { + sourceIndex -= 3; + destinationIndex -= 4; + var value = buffer[sourceIndex] << 16 | buffer[sourceIndex + 1] << 8 | buffer[sourceIndex + 2]; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + buffer[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + buffer[destinationIndex + 3] = (byte) map[value & 0x3F]; + } + bytesWritten = encodedLength; return true; } /// Decodes the span of UTF-16 encoded text represented as base-64-url into binary data. @@ -322,24 +282,96 @@ public static bool IsValid(ReadOnlySpan utf8Base64UrlText, out int decoded var chars = BytesToChars(utf8Base64UrlText); return IsValid(chars, out decodedLength); } - static string ToBase64UrlString(string base64) + const string encodeMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + static int EncodedLength(int bytesLength) => + checked((int) (((long) bytesLength * 4 + 2) / 3)); + static OperationStatus PlanEncode(int sourceLength, int destinationLength, bool isFinalBlock, out int bytesConsumed, out int written) { - var len = base64.Length; - while (len > 0 && base64[len - 1] == '=') + if (isFinalBlock) { - len--; + var total = EncodedLength(sourceLength); + if (total <= destinationLength) + { + bytesConsumed = sourceLength; + written = total; + return OperationStatus.Done; + } } - var chars = new char[len]; - for (var i = 0; i < len; i++) + var completeGroups = sourceLength / 3; + var groups = Math.Min(completeGroups, destinationLength / 4); + bytesConsumed = groups * 3; + written = groups * 4; + if (isFinalBlock || groups < completeGroups) { - chars[i] = base64[i] switch - { - '+' => '-', - '/' => '_', - _ => base64[i] - }; + return OperationStatus.DestinationTooSmall; + } + if (sourceLength % 3 > 0) + { + return OperationStatus.NeedMoreData; + } + return OperationStatus.Done; + } + static void Encode(ReadOnlySpan source, Span destination) + { + var map = encodeMap; + var sourceIndex = 0; + var destinationIndex = 0; + var end = source.Length - 2; + while (sourceIndex < end) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8 | source[sourceIndex + 2]; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = map[value >> 6 & 0x3F]; + destination[destinationIndex + 3] = map[value & 0x3F]; + sourceIndex += 3; + destinationIndex += 4; + } + var remaining = source.Length - sourceIndex; + if (remaining == 1) + { + var value = source[sourceIndex] << 16; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = map[value >> 6 & 0x3F]; + } + } + static void Encode(ReadOnlySpan source, Span destination) + { + var map = encodeMap; + var sourceIndex = 0; + var destinationIndex = 0; + var end = source.Length - 2; + while (sourceIndex < end) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8 | source[sourceIndex + 2]; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + destination[destinationIndex + 3] = (byte) map[value & 0x3F]; + sourceIndex += 3; + destinationIndex += 4; + } + var remaining = source.Length - sourceIndex; + if (remaining == 1) + { + var value = source[sourceIndex] << 16; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; } - return new string(chars); } static OperationStatus Decode(ReadOnlySpan source, Span destination, bool write, out int charsConsumed, out int bytesWritten, bool isFinalBlock) { @@ -478,13 +510,6 @@ static int DecodeValue(char c) } return -1; } - static void WriteStringToBytes(string source, Span destination) - { - for (var i = 0; i < source.Length; i++) - { - destination[i] = (byte)source[i]; - } - } static char[] BytesToChars(ReadOnlySpan source) { var chars = new char[source.Length]; diff --git a/src/Split/net48/Base64Url.cs b/src/Split/net48/Base64Url.cs index 817dcd19..88920e01 100644 --- a/src/Split/net48/Base64Url.cs +++ b/src/Split/net48/Base64Url.cs @@ -42,152 +42,87 @@ public static string EncodeToString(ReadOnlySpan source) { return string.Empty; } - var base64 = Convert.ToBase64String(source.ToArray()); - return ToBase64UrlString(base64); + var length = EncodedLength(source.Length); + if (length <= 256) + { + Span buffer = stackalloc char[256]; + buffer = buffer.Slice(0, length); + Encode(source, buffer); + return buffer.ToString(); + } + var rented = ArrayPool.Shared.Rent(length); + Encode(source, rented); + var result = new string(rented, 0, length); + ArrayPool.Shared.Return(rented); + return result; } /// Encodes the span of binary data into UTF-16 encoded text represented as base-64-url. public static int EncodeToChars(ReadOnlySpan source, Span destination) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { throw new ArgumentException("Destination is too small.", nameof(destination)); } - encoded.AsSpan().CopyTo(destination); - return encoded.Length; + Encode(source, destination); + return length; } /// Encodes the span of binary data into UTF-16 encoded text represented as base-64-url. public static OperationStatus EncodeToChars(ReadOnlySpan source, Span destination, out int bytesConsumed, out int charsWritten, bool isFinalBlock = true) { - if (source.IsEmpty) - { - charsWritten = 0; - bytesConsumed = 0; - return OperationStatus.Done; - } - var completeGroups = source.Length / 3; - var remainingBytes = source.Length % 3; - if (!isFinalBlock) - { - var groupsWeCanFit = Math.Min(completeGroups, destination.Length / 4); - bytesConsumed = groupsWeCanFit * 3; - charsWritten = groupsWeCanFit * 4; - if (bytesConsumed > 0) - { - EncodeToString(source.Slice(0, bytesConsumed)).AsSpan().CopyTo(destination); - } - if (groupsWeCanFit < completeGroups) - { - return OperationStatus.DestinationTooSmall; - } - return remainingBytes > 0 ? OperationStatus.NeedMoreData : OperationStatus.Done; - } - var totalChars = GetEncodedLength(source.Length); - if (totalChars <= destination.Length) - { - EncodeToString(source).AsSpan().CopyTo(destination); - charsWritten = totalChars; - bytesConsumed = source.Length; - return OperationStatus.Done; - } - var fitting = destination.Length / 4; - bytesConsumed = fitting * 3; - charsWritten = fitting * 4; - if (bytesConsumed > 0) - { - EncodeToString(source.Slice(0, bytesConsumed)).AsSpan().CopyTo(destination); - } - return OperationStatus.DestinationTooSmall; + var status = PlanEncode(source.Length, destination.Length, isFinalBlock, out bytesConsumed, out charsWritten); + Encode(source.Slice(0, bytesConsumed), destination); + return status; } /// Tries to encode the span of binary data into UTF-16 encoded text represented as base-64-url. public static bool TryEncodeToChars(ReadOnlySpan source, Span destination, out int charsWritten) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { charsWritten = 0; return false; } - encoded.AsSpan().CopyTo(destination); - charsWritten = encoded.Length; + Encode(source, destination); + charsWritten = length; return true; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static byte[] EncodeToUtf8(ReadOnlySpan source) { - var chars = EncodeToString(source); - var result = new byte[chars.Length]; - for (var i = 0; i < chars.Length; i++) - { - result[i] = (byte)chars[i]; - } + var result = new byte[EncodedLength(source.Length)]; + Encode(source, result); return result; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static int EncodeToUtf8(ReadOnlySpan source, Span destination) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { throw new ArgumentException("Destination is too small.", nameof(destination)); } - WriteStringToBytes(encoded, destination); - return encoded.Length; + Encode(source, destination); + return length; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static OperationStatus EncodeToUtf8(ReadOnlySpan source, Span destination, out int bytesConsumed, out int bytesWritten, bool isFinalBlock = true) { - if (source.IsEmpty) - { - bytesWritten = 0; - bytesConsumed = 0; - return OperationStatus.Done; - } - var completeGroups = source.Length / 3; - var remainingBytes = source.Length % 3; - if (!isFinalBlock) - { - var groupsWeCanFit = Math.Min(completeGroups, destination.Length / 4); - bytesConsumed = groupsWeCanFit * 3; - bytesWritten = groupsWeCanFit * 4; - if (bytesConsumed > 0) - { - WriteStringToBytes(EncodeToString(source.Slice(0, bytesConsumed)), destination); - } - if (groupsWeCanFit < completeGroups) - { - return OperationStatus.DestinationTooSmall; - } - return remainingBytes > 0 ? OperationStatus.NeedMoreData : OperationStatus.Done; - } - var totalBytes = GetEncodedLength(source.Length); - if (totalBytes <= destination.Length) - { - WriteStringToBytes(EncodeToString(source), destination); - bytesWritten = totalBytes; - bytesConsumed = source.Length; - return OperationStatus.Done; - } - var fitting = destination.Length / 4; - bytesConsumed = fitting * 3; - bytesWritten = fitting * 4; - if (bytesConsumed > 0) - { - WriteStringToBytes(EncodeToString(source.Slice(0, bytesConsumed)), destination); - } - return OperationStatus.DestinationTooSmall; + var status = PlanEncode(source.Length, destination.Length, isFinalBlock, out bytesConsumed, out bytesWritten); + Encode(source.Slice(0, bytesConsumed), destination); + return status; } /// Tries to encode the span of binary data into UTF-8 encoded text represented as base-64-url. public static bool TryEncodeToUtf8(ReadOnlySpan source, Span destination, out int bytesWritten) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { bytesWritten = 0; return false; } - WriteStringToBytes(encoded, destination); - bytesWritten = encoded.Length; + Encode(source, destination); + bytesWritten = length; return true; } /// Encodes the span of binary data (in-place) into UTF-8 encoded text represented as base-64-url. @@ -197,16 +132,41 @@ public static bool TryEncodeToUtf8InPlace(Span buffer, int dataLength, out { throw new ArgumentOutOfRangeException(nameof(dataLength)); } - var encodedLength = GetEncodedLength(dataLength); + var encodedLength = EncodedLength(dataLength); if (encodedLength > buffer.Length) { bytesWritten = 0; return false; } - var source = buffer.Slice(0, dataLength).ToArray(); - var encoded = EncodeToString(source); - WriteStringToBytes(encoded, buffer); - bytesWritten = encoded.Length; + var map = encodeMap; + var groups = dataLength / 3; + var sourceIndex = groups * 3; + var destinationIndex = groups * 4; + var remaining = dataLength - sourceIndex; + if (remaining == 1) + { + var value = buffer[sourceIndex] << 16; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = buffer[sourceIndex] << 16 | buffer[sourceIndex + 1] << 8; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + buffer[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + } + while (sourceIndex > 0) + { + sourceIndex -= 3; + destinationIndex -= 4; + var value = buffer[sourceIndex] << 16 | buffer[sourceIndex + 1] << 8 | buffer[sourceIndex + 2]; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + buffer[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + buffer[destinationIndex + 3] = (byte) map[value & 0x3F]; + } + bytesWritten = encodedLength; return true; } /// Decodes the span of UTF-16 encoded text represented as base-64-url into binary data. @@ -322,24 +282,96 @@ public static bool IsValid(ReadOnlySpan utf8Base64UrlText, out int decoded var chars = BytesToChars(utf8Base64UrlText); return IsValid(chars, out decodedLength); } - static string ToBase64UrlString(string base64) + const string encodeMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + static int EncodedLength(int bytesLength) => + checked((int) (((long) bytesLength * 4 + 2) / 3)); + static OperationStatus PlanEncode(int sourceLength, int destinationLength, bool isFinalBlock, out int bytesConsumed, out int written) { - var len = base64.Length; - while (len > 0 && base64[len - 1] == '=') + if (isFinalBlock) { - len--; + var total = EncodedLength(sourceLength); + if (total <= destinationLength) + { + bytesConsumed = sourceLength; + written = total; + return OperationStatus.Done; + } } - var chars = new char[len]; - for (var i = 0; i < len; i++) + var completeGroups = sourceLength / 3; + var groups = Math.Min(completeGroups, destinationLength / 4); + bytesConsumed = groups * 3; + written = groups * 4; + if (isFinalBlock || groups < completeGroups) { - chars[i] = base64[i] switch - { - '+' => '-', - '/' => '_', - _ => base64[i] - }; + return OperationStatus.DestinationTooSmall; + } + if (sourceLength % 3 > 0) + { + return OperationStatus.NeedMoreData; + } + return OperationStatus.Done; + } + static void Encode(ReadOnlySpan source, Span destination) + { + var map = encodeMap; + var sourceIndex = 0; + var destinationIndex = 0; + var end = source.Length - 2; + while (sourceIndex < end) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8 | source[sourceIndex + 2]; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = map[value >> 6 & 0x3F]; + destination[destinationIndex + 3] = map[value & 0x3F]; + sourceIndex += 3; + destinationIndex += 4; + } + var remaining = source.Length - sourceIndex; + if (remaining == 1) + { + var value = source[sourceIndex] << 16; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = map[value >> 6 & 0x3F]; + } + } + static void Encode(ReadOnlySpan source, Span destination) + { + var map = encodeMap; + var sourceIndex = 0; + var destinationIndex = 0; + var end = source.Length - 2; + while (sourceIndex < end) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8 | source[sourceIndex + 2]; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + destination[destinationIndex + 3] = (byte) map[value & 0x3F]; + sourceIndex += 3; + destinationIndex += 4; + } + var remaining = source.Length - sourceIndex; + if (remaining == 1) + { + var value = source[sourceIndex] << 16; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; } - return new string(chars); } static OperationStatus Decode(ReadOnlySpan source, Span destination, bool write, out int charsConsumed, out int bytesWritten, bool isFinalBlock) { @@ -478,13 +510,6 @@ static int DecodeValue(char c) } return -1; } - static void WriteStringToBytes(string source, Span destination) - { - for (var i = 0; i < source.Length; i++) - { - destination[i] = (byte)source[i]; - } - } static char[] BytesToChars(ReadOnlySpan source) { var chars = new char[source.Length]; diff --git a/src/Split/net481/Base64Url.cs b/src/Split/net481/Base64Url.cs index 817dcd19..88920e01 100644 --- a/src/Split/net481/Base64Url.cs +++ b/src/Split/net481/Base64Url.cs @@ -42,152 +42,87 @@ public static string EncodeToString(ReadOnlySpan source) { return string.Empty; } - var base64 = Convert.ToBase64String(source.ToArray()); - return ToBase64UrlString(base64); + var length = EncodedLength(source.Length); + if (length <= 256) + { + Span buffer = stackalloc char[256]; + buffer = buffer.Slice(0, length); + Encode(source, buffer); + return buffer.ToString(); + } + var rented = ArrayPool.Shared.Rent(length); + Encode(source, rented); + var result = new string(rented, 0, length); + ArrayPool.Shared.Return(rented); + return result; } /// Encodes the span of binary data into UTF-16 encoded text represented as base-64-url. public static int EncodeToChars(ReadOnlySpan source, Span destination) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { throw new ArgumentException("Destination is too small.", nameof(destination)); } - encoded.AsSpan().CopyTo(destination); - return encoded.Length; + Encode(source, destination); + return length; } /// Encodes the span of binary data into UTF-16 encoded text represented as base-64-url. public static OperationStatus EncodeToChars(ReadOnlySpan source, Span destination, out int bytesConsumed, out int charsWritten, bool isFinalBlock = true) { - if (source.IsEmpty) - { - charsWritten = 0; - bytesConsumed = 0; - return OperationStatus.Done; - } - var completeGroups = source.Length / 3; - var remainingBytes = source.Length % 3; - if (!isFinalBlock) - { - var groupsWeCanFit = Math.Min(completeGroups, destination.Length / 4); - bytesConsumed = groupsWeCanFit * 3; - charsWritten = groupsWeCanFit * 4; - if (bytesConsumed > 0) - { - EncodeToString(source.Slice(0, bytesConsumed)).AsSpan().CopyTo(destination); - } - if (groupsWeCanFit < completeGroups) - { - return OperationStatus.DestinationTooSmall; - } - return remainingBytes > 0 ? OperationStatus.NeedMoreData : OperationStatus.Done; - } - var totalChars = GetEncodedLength(source.Length); - if (totalChars <= destination.Length) - { - EncodeToString(source).AsSpan().CopyTo(destination); - charsWritten = totalChars; - bytesConsumed = source.Length; - return OperationStatus.Done; - } - var fitting = destination.Length / 4; - bytesConsumed = fitting * 3; - charsWritten = fitting * 4; - if (bytesConsumed > 0) - { - EncodeToString(source.Slice(0, bytesConsumed)).AsSpan().CopyTo(destination); - } - return OperationStatus.DestinationTooSmall; + var status = PlanEncode(source.Length, destination.Length, isFinalBlock, out bytesConsumed, out charsWritten); + Encode(source.Slice(0, bytesConsumed), destination); + return status; } /// Tries to encode the span of binary data into UTF-16 encoded text represented as base-64-url. public static bool TryEncodeToChars(ReadOnlySpan source, Span destination, out int charsWritten) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { charsWritten = 0; return false; } - encoded.AsSpan().CopyTo(destination); - charsWritten = encoded.Length; + Encode(source, destination); + charsWritten = length; return true; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static byte[] EncodeToUtf8(ReadOnlySpan source) { - var chars = EncodeToString(source); - var result = new byte[chars.Length]; - for (var i = 0; i < chars.Length; i++) - { - result[i] = (byte)chars[i]; - } + var result = new byte[EncodedLength(source.Length)]; + Encode(source, result); return result; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static int EncodeToUtf8(ReadOnlySpan source, Span destination) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { throw new ArgumentException("Destination is too small.", nameof(destination)); } - WriteStringToBytes(encoded, destination); - return encoded.Length; + Encode(source, destination); + return length; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static OperationStatus EncodeToUtf8(ReadOnlySpan source, Span destination, out int bytesConsumed, out int bytesWritten, bool isFinalBlock = true) { - if (source.IsEmpty) - { - bytesWritten = 0; - bytesConsumed = 0; - return OperationStatus.Done; - } - var completeGroups = source.Length / 3; - var remainingBytes = source.Length % 3; - if (!isFinalBlock) - { - var groupsWeCanFit = Math.Min(completeGroups, destination.Length / 4); - bytesConsumed = groupsWeCanFit * 3; - bytesWritten = groupsWeCanFit * 4; - if (bytesConsumed > 0) - { - WriteStringToBytes(EncodeToString(source.Slice(0, bytesConsumed)), destination); - } - if (groupsWeCanFit < completeGroups) - { - return OperationStatus.DestinationTooSmall; - } - return remainingBytes > 0 ? OperationStatus.NeedMoreData : OperationStatus.Done; - } - var totalBytes = GetEncodedLength(source.Length); - if (totalBytes <= destination.Length) - { - WriteStringToBytes(EncodeToString(source), destination); - bytesWritten = totalBytes; - bytesConsumed = source.Length; - return OperationStatus.Done; - } - var fitting = destination.Length / 4; - bytesConsumed = fitting * 3; - bytesWritten = fitting * 4; - if (bytesConsumed > 0) - { - WriteStringToBytes(EncodeToString(source.Slice(0, bytesConsumed)), destination); - } - return OperationStatus.DestinationTooSmall; + var status = PlanEncode(source.Length, destination.Length, isFinalBlock, out bytesConsumed, out bytesWritten); + Encode(source.Slice(0, bytesConsumed), destination); + return status; } /// Tries to encode the span of binary data into UTF-8 encoded text represented as base-64-url. public static bool TryEncodeToUtf8(ReadOnlySpan source, Span destination, out int bytesWritten) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { bytesWritten = 0; return false; } - WriteStringToBytes(encoded, destination); - bytesWritten = encoded.Length; + Encode(source, destination); + bytesWritten = length; return true; } /// Encodes the span of binary data (in-place) into UTF-8 encoded text represented as base-64-url. @@ -197,16 +132,41 @@ public static bool TryEncodeToUtf8InPlace(Span buffer, int dataLength, out { throw new ArgumentOutOfRangeException(nameof(dataLength)); } - var encodedLength = GetEncodedLength(dataLength); + var encodedLength = EncodedLength(dataLength); if (encodedLength > buffer.Length) { bytesWritten = 0; return false; } - var source = buffer.Slice(0, dataLength).ToArray(); - var encoded = EncodeToString(source); - WriteStringToBytes(encoded, buffer); - bytesWritten = encoded.Length; + var map = encodeMap; + var groups = dataLength / 3; + var sourceIndex = groups * 3; + var destinationIndex = groups * 4; + var remaining = dataLength - sourceIndex; + if (remaining == 1) + { + var value = buffer[sourceIndex] << 16; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = buffer[sourceIndex] << 16 | buffer[sourceIndex + 1] << 8; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + buffer[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + } + while (sourceIndex > 0) + { + sourceIndex -= 3; + destinationIndex -= 4; + var value = buffer[sourceIndex] << 16 | buffer[sourceIndex + 1] << 8 | buffer[sourceIndex + 2]; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + buffer[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + buffer[destinationIndex + 3] = (byte) map[value & 0x3F]; + } + bytesWritten = encodedLength; return true; } /// Decodes the span of UTF-16 encoded text represented as base-64-url into binary data. @@ -322,24 +282,96 @@ public static bool IsValid(ReadOnlySpan utf8Base64UrlText, out int decoded var chars = BytesToChars(utf8Base64UrlText); return IsValid(chars, out decodedLength); } - static string ToBase64UrlString(string base64) + const string encodeMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + static int EncodedLength(int bytesLength) => + checked((int) (((long) bytesLength * 4 + 2) / 3)); + static OperationStatus PlanEncode(int sourceLength, int destinationLength, bool isFinalBlock, out int bytesConsumed, out int written) { - var len = base64.Length; - while (len > 0 && base64[len - 1] == '=') + if (isFinalBlock) { - len--; + var total = EncodedLength(sourceLength); + if (total <= destinationLength) + { + bytesConsumed = sourceLength; + written = total; + return OperationStatus.Done; + } } - var chars = new char[len]; - for (var i = 0; i < len; i++) + var completeGroups = sourceLength / 3; + var groups = Math.Min(completeGroups, destinationLength / 4); + bytesConsumed = groups * 3; + written = groups * 4; + if (isFinalBlock || groups < completeGroups) { - chars[i] = base64[i] switch - { - '+' => '-', - '/' => '_', - _ => base64[i] - }; + return OperationStatus.DestinationTooSmall; + } + if (sourceLength % 3 > 0) + { + return OperationStatus.NeedMoreData; + } + return OperationStatus.Done; + } + static void Encode(ReadOnlySpan source, Span destination) + { + var map = encodeMap; + var sourceIndex = 0; + var destinationIndex = 0; + var end = source.Length - 2; + while (sourceIndex < end) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8 | source[sourceIndex + 2]; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = map[value >> 6 & 0x3F]; + destination[destinationIndex + 3] = map[value & 0x3F]; + sourceIndex += 3; + destinationIndex += 4; + } + var remaining = source.Length - sourceIndex; + if (remaining == 1) + { + var value = source[sourceIndex] << 16; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = map[value >> 6 & 0x3F]; + } + } + static void Encode(ReadOnlySpan source, Span destination) + { + var map = encodeMap; + var sourceIndex = 0; + var destinationIndex = 0; + var end = source.Length - 2; + while (sourceIndex < end) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8 | source[sourceIndex + 2]; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + destination[destinationIndex + 3] = (byte) map[value & 0x3F]; + sourceIndex += 3; + destinationIndex += 4; + } + var remaining = source.Length - sourceIndex; + if (remaining == 1) + { + var value = source[sourceIndex] << 16; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; } - return new string(chars); } static OperationStatus Decode(ReadOnlySpan source, Span destination, bool write, out int charsConsumed, out int bytesWritten, bool isFinalBlock) { @@ -478,13 +510,6 @@ static int DecodeValue(char c) } return -1; } - static void WriteStringToBytes(string source, Span destination) - { - for (var i = 0; i < source.Length; i++) - { - destination[i] = (byte)source[i]; - } - } static char[] BytesToChars(ReadOnlySpan source) { var chars = new char[source.Length]; diff --git a/src/Split/net5.0/Base64Url.cs b/src/Split/net5.0/Base64Url.cs index 817dcd19..88920e01 100644 --- a/src/Split/net5.0/Base64Url.cs +++ b/src/Split/net5.0/Base64Url.cs @@ -42,152 +42,87 @@ public static string EncodeToString(ReadOnlySpan source) { return string.Empty; } - var base64 = Convert.ToBase64String(source.ToArray()); - return ToBase64UrlString(base64); + var length = EncodedLength(source.Length); + if (length <= 256) + { + Span buffer = stackalloc char[256]; + buffer = buffer.Slice(0, length); + Encode(source, buffer); + return buffer.ToString(); + } + var rented = ArrayPool.Shared.Rent(length); + Encode(source, rented); + var result = new string(rented, 0, length); + ArrayPool.Shared.Return(rented); + return result; } /// Encodes the span of binary data into UTF-16 encoded text represented as base-64-url. public static int EncodeToChars(ReadOnlySpan source, Span destination) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { throw new ArgumentException("Destination is too small.", nameof(destination)); } - encoded.AsSpan().CopyTo(destination); - return encoded.Length; + Encode(source, destination); + return length; } /// Encodes the span of binary data into UTF-16 encoded text represented as base-64-url. public static OperationStatus EncodeToChars(ReadOnlySpan source, Span destination, out int bytesConsumed, out int charsWritten, bool isFinalBlock = true) { - if (source.IsEmpty) - { - charsWritten = 0; - bytesConsumed = 0; - return OperationStatus.Done; - } - var completeGroups = source.Length / 3; - var remainingBytes = source.Length % 3; - if (!isFinalBlock) - { - var groupsWeCanFit = Math.Min(completeGroups, destination.Length / 4); - bytesConsumed = groupsWeCanFit * 3; - charsWritten = groupsWeCanFit * 4; - if (bytesConsumed > 0) - { - EncodeToString(source.Slice(0, bytesConsumed)).AsSpan().CopyTo(destination); - } - if (groupsWeCanFit < completeGroups) - { - return OperationStatus.DestinationTooSmall; - } - return remainingBytes > 0 ? OperationStatus.NeedMoreData : OperationStatus.Done; - } - var totalChars = GetEncodedLength(source.Length); - if (totalChars <= destination.Length) - { - EncodeToString(source).AsSpan().CopyTo(destination); - charsWritten = totalChars; - bytesConsumed = source.Length; - return OperationStatus.Done; - } - var fitting = destination.Length / 4; - bytesConsumed = fitting * 3; - charsWritten = fitting * 4; - if (bytesConsumed > 0) - { - EncodeToString(source.Slice(0, bytesConsumed)).AsSpan().CopyTo(destination); - } - return OperationStatus.DestinationTooSmall; + var status = PlanEncode(source.Length, destination.Length, isFinalBlock, out bytesConsumed, out charsWritten); + Encode(source.Slice(0, bytesConsumed), destination); + return status; } /// Tries to encode the span of binary data into UTF-16 encoded text represented as base-64-url. public static bool TryEncodeToChars(ReadOnlySpan source, Span destination, out int charsWritten) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { charsWritten = 0; return false; } - encoded.AsSpan().CopyTo(destination); - charsWritten = encoded.Length; + Encode(source, destination); + charsWritten = length; return true; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static byte[] EncodeToUtf8(ReadOnlySpan source) { - var chars = EncodeToString(source); - var result = new byte[chars.Length]; - for (var i = 0; i < chars.Length; i++) - { - result[i] = (byte)chars[i]; - } + var result = new byte[EncodedLength(source.Length)]; + Encode(source, result); return result; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static int EncodeToUtf8(ReadOnlySpan source, Span destination) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { throw new ArgumentException("Destination is too small.", nameof(destination)); } - WriteStringToBytes(encoded, destination); - return encoded.Length; + Encode(source, destination); + return length; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static OperationStatus EncodeToUtf8(ReadOnlySpan source, Span destination, out int bytesConsumed, out int bytesWritten, bool isFinalBlock = true) { - if (source.IsEmpty) - { - bytesWritten = 0; - bytesConsumed = 0; - return OperationStatus.Done; - } - var completeGroups = source.Length / 3; - var remainingBytes = source.Length % 3; - if (!isFinalBlock) - { - var groupsWeCanFit = Math.Min(completeGroups, destination.Length / 4); - bytesConsumed = groupsWeCanFit * 3; - bytesWritten = groupsWeCanFit * 4; - if (bytesConsumed > 0) - { - WriteStringToBytes(EncodeToString(source.Slice(0, bytesConsumed)), destination); - } - if (groupsWeCanFit < completeGroups) - { - return OperationStatus.DestinationTooSmall; - } - return remainingBytes > 0 ? OperationStatus.NeedMoreData : OperationStatus.Done; - } - var totalBytes = GetEncodedLength(source.Length); - if (totalBytes <= destination.Length) - { - WriteStringToBytes(EncodeToString(source), destination); - bytesWritten = totalBytes; - bytesConsumed = source.Length; - return OperationStatus.Done; - } - var fitting = destination.Length / 4; - bytesConsumed = fitting * 3; - bytesWritten = fitting * 4; - if (bytesConsumed > 0) - { - WriteStringToBytes(EncodeToString(source.Slice(0, bytesConsumed)), destination); - } - return OperationStatus.DestinationTooSmall; + var status = PlanEncode(source.Length, destination.Length, isFinalBlock, out bytesConsumed, out bytesWritten); + Encode(source.Slice(0, bytesConsumed), destination); + return status; } /// Tries to encode the span of binary data into UTF-8 encoded text represented as base-64-url. public static bool TryEncodeToUtf8(ReadOnlySpan source, Span destination, out int bytesWritten) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { bytesWritten = 0; return false; } - WriteStringToBytes(encoded, destination); - bytesWritten = encoded.Length; + Encode(source, destination); + bytesWritten = length; return true; } /// Encodes the span of binary data (in-place) into UTF-8 encoded text represented as base-64-url. @@ -197,16 +132,41 @@ public static bool TryEncodeToUtf8InPlace(Span buffer, int dataLength, out { throw new ArgumentOutOfRangeException(nameof(dataLength)); } - var encodedLength = GetEncodedLength(dataLength); + var encodedLength = EncodedLength(dataLength); if (encodedLength > buffer.Length) { bytesWritten = 0; return false; } - var source = buffer.Slice(0, dataLength).ToArray(); - var encoded = EncodeToString(source); - WriteStringToBytes(encoded, buffer); - bytesWritten = encoded.Length; + var map = encodeMap; + var groups = dataLength / 3; + var sourceIndex = groups * 3; + var destinationIndex = groups * 4; + var remaining = dataLength - sourceIndex; + if (remaining == 1) + { + var value = buffer[sourceIndex] << 16; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = buffer[sourceIndex] << 16 | buffer[sourceIndex + 1] << 8; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + buffer[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + } + while (sourceIndex > 0) + { + sourceIndex -= 3; + destinationIndex -= 4; + var value = buffer[sourceIndex] << 16 | buffer[sourceIndex + 1] << 8 | buffer[sourceIndex + 2]; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + buffer[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + buffer[destinationIndex + 3] = (byte) map[value & 0x3F]; + } + bytesWritten = encodedLength; return true; } /// Decodes the span of UTF-16 encoded text represented as base-64-url into binary data. @@ -322,24 +282,96 @@ public static bool IsValid(ReadOnlySpan utf8Base64UrlText, out int decoded var chars = BytesToChars(utf8Base64UrlText); return IsValid(chars, out decodedLength); } - static string ToBase64UrlString(string base64) + const string encodeMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + static int EncodedLength(int bytesLength) => + checked((int) (((long) bytesLength * 4 + 2) / 3)); + static OperationStatus PlanEncode(int sourceLength, int destinationLength, bool isFinalBlock, out int bytesConsumed, out int written) { - var len = base64.Length; - while (len > 0 && base64[len - 1] == '=') + if (isFinalBlock) { - len--; + var total = EncodedLength(sourceLength); + if (total <= destinationLength) + { + bytesConsumed = sourceLength; + written = total; + return OperationStatus.Done; + } } - var chars = new char[len]; - for (var i = 0; i < len; i++) + var completeGroups = sourceLength / 3; + var groups = Math.Min(completeGroups, destinationLength / 4); + bytesConsumed = groups * 3; + written = groups * 4; + if (isFinalBlock || groups < completeGroups) { - chars[i] = base64[i] switch - { - '+' => '-', - '/' => '_', - _ => base64[i] - }; + return OperationStatus.DestinationTooSmall; + } + if (sourceLength % 3 > 0) + { + return OperationStatus.NeedMoreData; + } + return OperationStatus.Done; + } + static void Encode(ReadOnlySpan source, Span destination) + { + var map = encodeMap; + var sourceIndex = 0; + var destinationIndex = 0; + var end = source.Length - 2; + while (sourceIndex < end) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8 | source[sourceIndex + 2]; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = map[value >> 6 & 0x3F]; + destination[destinationIndex + 3] = map[value & 0x3F]; + sourceIndex += 3; + destinationIndex += 4; + } + var remaining = source.Length - sourceIndex; + if (remaining == 1) + { + var value = source[sourceIndex] << 16; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = map[value >> 6 & 0x3F]; + } + } + static void Encode(ReadOnlySpan source, Span destination) + { + var map = encodeMap; + var sourceIndex = 0; + var destinationIndex = 0; + var end = source.Length - 2; + while (sourceIndex < end) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8 | source[sourceIndex + 2]; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + destination[destinationIndex + 3] = (byte) map[value & 0x3F]; + sourceIndex += 3; + destinationIndex += 4; + } + var remaining = source.Length - sourceIndex; + if (remaining == 1) + { + var value = source[sourceIndex] << 16; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; } - return new string(chars); } static OperationStatus Decode(ReadOnlySpan source, Span destination, bool write, out int charsConsumed, out int bytesWritten, bool isFinalBlock) { @@ -478,13 +510,6 @@ static int DecodeValue(char c) } return -1; } - static void WriteStringToBytes(string source, Span destination) - { - for (var i = 0; i < source.Length; i++) - { - destination[i] = (byte)source[i]; - } - } static char[] BytesToChars(ReadOnlySpan source) { var chars = new char[source.Length]; diff --git a/src/Split/net6.0/Base64Url.cs b/src/Split/net6.0/Base64Url.cs index 817dcd19..88920e01 100644 --- a/src/Split/net6.0/Base64Url.cs +++ b/src/Split/net6.0/Base64Url.cs @@ -42,152 +42,87 @@ public static string EncodeToString(ReadOnlySpan source) { return string.Empty; } - var base64 = Convert.ToBase64String(source.ToArray()); - return ToBase64UrlString(base64); + var length = EncodedLength(source.Length); + if (length <= 256) + { + Span buffer = stackalloc char[256]; + buffer = buffer.Slice(0, length); + Encode(source, buffer); + return buffer.ToString(); + } + var rented = ArrayPool.Shared.Rent(length); + Encode(source, rented); + var result = new string(rented, 0, length); + ArrayPool.Shared.Return(rented); + return result; } /// Encodes the span of binary data into UTF-16 encoded text represented as base-64-url. public static int EncodeToChars(ReadOnlySpan source, Span destination) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { throw new ArgumentException("Destination is too small.", nameof(destination)); } - encoded.AsSpan().CopyTo(destination); - return encoded.Length; + Encode(source, destination); + return length; } /// Encodes the span of binary data into UTF-16 encoded text represented as base-64-url. public static OperationStatus EncodeToChars(ReadOnlySpan source, Span destination, out int bytesConsumed, out int charsWritten, bool isFinalBlock = true) { - if (source.IsEmpty) - { - charsWritten = 0; - bytesConsumed = 0; - return OperationStatus.Done; - } - var completeGroups = source.Length / 3; - var remainingBytes = source.Length % 3; - if (!isFinalBlock) - { - var groupsWeCanFit = Math.Min(completeGroups, destination.Length / 4); - bytesConsumed = groupsWeCanFit * 3; - charsWritten = groupsWeCanFit * 4; - if (bytesConsumed > 0) - { - EncodeToString(source.Slice(0, bytesConsumed)).AsSpan().CopyTo(destination); - } - if (groupsWeCanFit < completeGroups) - { - return OperationStatus.DestinationTooSmall; - } - return remainingBytes > 0 ? OperationStatus.NeedMoreData : OperationStatus.Done; - } - var totalChars = GetEncodedLength(source.Length); - if (totalChars <= destination.Length) - { - EncodeToString(source).AsSpan().CopyTo(destination); - charsWritten = totalChars; - bytesConsumed = source.Length; - return OperationStatus.Done; - } - var fitting = destination.Length / 4; - bytesConsumed = fitting * 3; - charsWritten = fitting * 4; - if (bytesConsumed > 0) - { - EncodeToString(source.Slice(0, bytesConsumed)).AsSpan().CopyTo(destination); - } - return OperationStatus.DestinationTooSmall; + var status = PlanEncode(source.Length, destination.Length, isFinalBlock, out bytesConsumed, out charsWritten); + Encode(source.Slice(0, bytesConsumed), destination); + return status; } /// Tries to encode the span of binary data into UTF-16 encoded text represented as base-64-url. public static bool TryEncodeToChars(ReadOnlySpan source, Span destination, out int charsWritten) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { charsWritten = 0; return false; } - encoded.AsSpan().CopyTo(destination); - charsWritten = encoded.Length; + Encode(source, destination); + charsWritten = length; return true; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static byte[] EncodeToUtf8(ReadOnlySpan source) { - var chars = EncodeToString(source); - var result = new byte[chars.Length]; - for (var i = 0; i < chars.Length; i++) - { - result[i] = (byte)chars[i]; - } + var result = new byte[EncodedLength(source.Length)]; + Encode(source, result); return result; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static int EncodeToUtf8(ReadOnlySpan source, Span destination) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { throw new ArgumentException("Destination is too small.", nameof(destination)); } - WriteStringToBytes(encoded, destination); - return encoded.Length; + Encode(source, destination); + return length; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static OperationStatus EncodeToUtf8(ReadOnlySpan source, Span destination, out int bytesConsumed, out int bytesWritten, bool isFinalBlock = true) { - if (source.IsEmpty) - { - bytesWritten = 0; - bytesConsumed = 0; - return OperationStatus.Done; - } - var completeGroups = source.Length / 3; - var remainingBytes = source.Length % 3; - if (!isFinalBlock) - { - var groupsWeCanFit = Math.Min(completeGroups, destination.Length / 4); - bytesConsumed = groupsWeCanFit * 3; - bytesWritten = groupsWeCanFit * 4; - if (bytesConsumed > 0) - { - WriteStringToBytes(EncodeToString(source.Slice(0, bytesConsumed)), destination); - } - if (groupsWeCanFit < completeGroups) - { - return OperationStatus.DestinationTooSmall; - } - return remainingBytes > 0 ? OperationStatus.NeedMoreData : OperationStatus.Done; - } - var totalBytes = GetEncodedLength(source.Length); - if (totalBytes <= destination.Length) - { - WriteStringToBytes(EncodeToString(source), destination); - bytesWritten = totalBytes; - bytesConsumed = source.Length; - return OperationStatus.Done; - } - var fitting = destination.Length / 4; - bytesConsumed = fitting * 3; - bytesWritten = fitting * 4; - if (bytesConsumed > 0) - { - WriteStringToBytes(EncodeToString(source.Slice(0, bytesConsumed)), destination); - } - return OperationStatus.DestinationTooSmall; + var status = PlanEncode(source.Length, destination.Length, isFinalBlock, out bytesConsumed, out bytesWritten); + Encode(source.Slice(0, bytesConsumed), destination); + return status; } /// Tries to encode the span of binary data into UTF-8 encoded text represented as base-64-url. public static bool TryEncodeToUtf8(ReadOnlySpan source, Span destination, out int bytesWritten) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { bytesWritten = 0; return false; } - WriteStringToBytes(encoded, destination); - bytesWritten = encoded.Length; + Encode(source, destination); + bytesWritten = length; return true; } /// Encodes the span of binary data (in-place) into UTF-8 encoded text represented as base-64-url. @@ -197,16 +132,41 @@ public static bool TryEncodeToUtf8InPlace(Span buffer, int dataLength, out { throw new ArgumentOutOfRangeException(nameof(dataLength)); } - var encodedLength = GetEncodedLength(dataLength); + var encodedLength = EncodedLength(dataLength); if (encodedLength > buffer.Length) { bytesWritten = 0; return false; } - var source = buffer.Slice(0, dataLength).ToArray(); - var encoded = EncodeToString(source); - WriteStringToBytes(encoded, buffer); - bytesWritten = encoded.Length; + var map = encodeMap; + var groups = dataLength / 3; + var sourceIndex = groups * 3; + var destinationIndex = groups * 4; + var remaining = dataLength - sourceIndex; + if (remaining == 1) + { + var value = buffer[sourceIndex] << 16; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = buffer[sourceIndex] << 16 | buffer[sourceIndex + 1] << 8; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + buffer[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + } + while (sourceIndex > 0) + { + sourceIndex -= 3; + destinationIndex -= 4; + var value = buffer[sourceIndex] << 16 | buffer[sourceIndex + 1] << 8 | buffer[sourceIndex + 2]; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + buffer[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + buffer[destinationIndex + 3] = (byte) map[value & 0x3F]; + } + bytesWritten = encodedLength; return true; } /// Decodes the span of UTF-16 encoded text represented as base-64-url into binary data. @@ -322,24 +282,96 @@ public static bool IsValid(ReadOnlySpan utf8Base64UrlText, out int decoded var chars = BytesToChars(utf8Base64UrlText); return IsValid(chars, out decodedLength); } - static string ToBase64UrlString(string base64) + const string encodeMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + static int EncodedLength(int bytesLength) => + checked((int) (((long) bytesLength * 4 + 2) / 3)); + static OperationStatus PlanEncode(int sourceLength, int destinationLength, bool isFinalBlock, out int bytesConsumed, out int written) { - var len = base64.Length; - while (len > 0 && base64[len - 1] == '=') + if (isFinalBlock) { - len--; + var total = EncodedLength(sourceLength); + if (total <= destinationLength) + { + bytesConsumed = sourceLength; + written = total; + return OperationStatus.Done; + } } - var chars = new char[len]; - for (var i = 0; i < len; i++) + var completeGroups = sourceLength / 3; + var groups = Math.Min(completeGroups, destinationLength / 4); + bytesConsumed = groups * 3; + written = groups * 4; + if (isFinalBlock || groups < completeGroups) { - chars[i] = base64[i] switch - { - '+' => '-', - '/' => '_', - _ => base64[i] - }; + return OperationStatus.DestinationTooSmall; + } + if (sourceLength % 3 > 0) + { + return OperationStatus.NeedMoreData; + } + return OperationStatus.Done; + } + static void Encode(ReadOnlySpan source, Span destination) + { + var map = encodeMap; + var sourceIndex = 0; + var destinationIndex = 0; + var end = source.Length - 2; + while (sourceIndex < end) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8 | source[sourceIndex + 2]; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = map[value >> 6 & 0x3F]; + destination[destinationIndex + 3] = map[value & 0x3F]; + sourceIndex += 3; + destinationIndex += 4; + } + var remaining = source.Length - sourceIndex; + if (remaining == 1) + { + var value = source[sourceIndex] << 16; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = map[value >> 6 & 0x3F]; + } + } + static void Encode(ReadOnlySpan source, Span destination) + { + var map = encodeMap; + var sourceIndex = 0; + var destinationIndex = 0; + var end = source.Length - 2; + while (sourceIndex < end) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8 | source[sourceIndex + 2]; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + destination[destinationIndex + 3] = (byte) map[value & 0x3F]; + sourceIndex += 3; + destinationIndex += 4; + } + var remaining = source.Length - sourceIndex; + if (remaining == 1) + { + var value = source[sourceIndex] << 16; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; } - return new string(chars); } static OperationStatus Decode(ReadOnlySpan source, Span destination, bool write, out int charsConsumed, out int bytesWritten, bool isFinalBlock) { @@ -478,13 +510,6 @@ static int DecodeValue(char c) } return -1; } - static void WriteStringToBytes(string source, Span destination) - { - for (var i = 0; i < source.Length; i++) - { - destination[i] = (byte)source[i]; - } - } static char[] BytesToChars(ReadOnlySpan source) { var chars = new char[source.Length]; diff --git a/src/Split/net7.0/Base64Url.cs b/src/Split/net7.0/Base64Url.cs index 817dcd19..88920e01 100644 --- a/src/Split/net7.0/Base64Url.cs +++ b/src/Split/net7.0/Base64Url.cs @@ -42,152 +42,87 @@ public static string EncodeToString(ReadOnlySpan source) { return string.Empty; } - var base64 = Convert.ToBase64String(source.ToArray()); - return ToBase64UrlString(base64); + var length = EncodedLength(source.Length); + if (length <= 256) + { + Span buffer = stackalloc char[256]; + buffer = buffer.Slice(0, length); + Encode(source, buffer); + return buffer.ToString(); + } + var rented = ArrayPool.Shared.Rent(length); + Encode(source, rented); + var result = new string(rented, 0, length); + ArrayPool.Shared.Return(rented); + return result; } /// Encodes the span of binary data into UTF-16 encoded text represented as base-64-url. public static int EncodeToChars(ReadOnlySpan source, Span destination) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { throw new ArgumentException("Destination is too small.", nameof(destination)); } - encoded.AsSpan().CopyTo(destination); - return encoded.Length; + Encode(source, destination); + return length; } /// Encodes the span of binary data into UTF-16 encoded text represented as base-64-url. public static OperationStatus EncodeToChars(ReadOnlySpan source, Span destination, out int bytesConsumed, out int charsWritten, bool isFinalBlock = true) { - if (source.IsEmpty) - { - charsWritten = 0; - bytesConsumed = 0; - return OperationStatus.Done; - } - var completeGroups = source.Length / 3; - var remainingBytes = source.Length % 3; - if (!isFinalBlock) - { - var groupsWeCanFit = Math.Min(completeGroups, destination.Length / 4); - bytesConsumed = groupsWeCanFit * 3; - charsWritten = groupsWeCanFit * 4; - if (bytesConsumed > 0) - { - EncodeToString(source.Slice(0, bytesConsumed)).AsSpan().CopyTo(destination); - } - if (groupsWeCanFit < completeGroups) - { - return OperationStatus.DestinationTooSmall; - } - return remainingBytes > 0 ? OperationStatus.NeedMoreData : OperationStatus.Done; - } - var totalChars = GetEncodedLength(source.Length); - if (totalChars <= destination.Length) - { - EncodeToString(source).AsSpan().CopyTo(destination); - charsWritten = totalChars; - bytesConsumed = source.Length; - return OperationStatus.Done; - } - var fitting = destination.Length / 4; - bytesConsumed = fitting * 3; - charsWritten = fitting * 4; - if (bytesConsumed > 0) - { - EncodeToString(source.Slice(0, bytesConsumed)).AsSpan().CopyTo(destination); - } - return OperationStatus.DestinationTooSmall; + var status = PlanEncode(source.Length, destination.Length, isFinalBlock, out bytesConsumed, out charsWritten); + Encode(source.Slice(0, bytesConsumed), destination); + return status; } /// Tries to encode the span of binary data into UTF-16 encoded text represented as base-64-url. public static bool TryEncodeToChars(ReadOnlySpan source, Span destination, out int charsWritten) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { charsWritten = 0; return false; } - encoded.AsSpan().CopyTo(destination); - charsWritten = encoded.Length; + Encode(source, destination); + charsWritten = length; return true; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static byte[] EncodeToUtf8(ReadOnlySpan source) { - var chars = EncodeToString(source); - var result = new byte[chars.Length]; - for (var i = 0; i < chars.Length; i++) - { - result[i] = (byte)chars[i]; - } + var result = new byte[EncodedLength(source.Length)]; + Encode(source, result); return result; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static int EncodeToUtf8(ReadOnlySpan source, Span destination) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { throw new ArgumentException("Destination is too small.", nameof(destination)); } - WriteStringToBytes(encoded, destination); - return encoded.Length; + Encode(source, destination); + return length; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static OperationStatus EncodeToUtf8(ReadOnlySpan source, Span destination, out int bytesConsumed, out int bytesWritten, bool isFinalBlock = true) { - if (source.IsEmpty) - { - bytesWritten = 0; - bytesConsumed = 0; - return OperationStatus.Done; - } - var completeGroups = source.Length / 3; - var remainingBytes = source.Length % 3; - if (!isFinalBlock) - { - var groupsWeCanFit = Math.Min(completeGroups, destination.Length / 4); - bytesConsumed = groupsWeCanFit * 3; - bytesWritten = groupsWeCanFit * 4; - if (bytesConsumed > 0) - { - WriteStringToBytes(EncodeToString(source.Slice(0, bytesConsumed)), destination); - } - if (groupsWeCanFit < completeGroups) - { - return OperationStatus.DestinationTooSmall; - } - return remainingBytes > 0 ? OperationStatus.NeedMoreData : OperationStatus.Done; - } - var totalBytes = GetEncodedLength(source.Length); - if (totalBytes <= destination.Length) - { - WriteStringToBytes(EncodeToString(source), destination); - bytesWritten = totalBytes; - bytesConsumed = source.Length; - return OperationStatus.Done; - } - var fitting = destination.Length / 4; - bytesConsumed = fitting * 3; - bytesWritten = fitting * 4; - if (bytesConsumed > 0) - { - WriteStringToBytes(EncodeToString(source.Slice(0, bytesConsumed)), destination); - } - return OperationStatus.DestinationTooSmall; + var status = PlanEncode(source.Length, destination.Length, isFinalBlock, out bytesConsumed, out bytesWritten); + Encode(source.Slice(0, bytesConsumed), destination); + return status; } /// Tries to encode the span of binary data into UTF-8 encoded text represented as base-64-url. public static bool TryEncodeToUtf8(ReadOnlySpan source, Span destination, out int bytesWritten) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { bytesWritten = 0; return false; } - WriteStringToBytes(encoded, destination); - bytesWritten = encoded.Length; + Encode(source, destination); + bytesWritten = length; return true; } /// Encodes the span of binary data (in-place) into UTF-8 encoded text represented as base-64-url. @@ -197,16 +132,41 @@ public static bool TryEncodeToUtf8InPlace(Span buffer, int dataLength, out { throw new ArgumentOutOfRangeException(nameof(dataLength)); } - var encodedLength = GetEncodedLength(dataLength); + var encodedLength = EncodedLength(dataLength); if (encodedLength > buffer.Length) { bytesWritten = 0; return false; } - var source = buffer.Slice(0, dataLength).ToArray(); - var encoded = EncodeToString(source); - WriteStringToBytes(encoded, buffer); - bytesWritten = encoded.Length; + var map = encodeMap; + var groups = dataLength / 3; + var sourceIndex = groups * 3; + var destinationIndex = groups * 4; + var remaining = dataLength - sourceIndex; + if (remaining == 1) + { + var value = buffer[sourceIndex] << 16; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = buffer[sourceIndex] << 16 | buffer[sourceIndex + 1] << 8; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + buffer[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + } + while (sourceIndex > 0) + { + sourceIndex -= 3; + destinationIndex -= 4; + var value = buffer[sourceIndex] << 16 | buffer[sourceIndex + 1] << 8 | buffer[sourceIndex + 2]; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + buffer[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + buffer[destinationIndex + 3] = (byte) map[value & 0x3F]; + } + bytesWritten = encodedLength; return true; } /// Decodes the span of UTF-16 encoded text represented as base-64-url into binary data. @@ -322,24 +282,96 @@ public static bool IsValid(ReadOnlySpan utf8Base64UrlText, out int decoded var chars = BytesToChars(utf8Base64UrlText); return IsValid(chars, out decodedLength); } - static string ToBase64UrlString(string base64) + const string encodeMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + static int EncodedLength(int bytesLength) => + checked((int) (((long) bytesLength * 4 + 2) / 3)); + static OperationStatus PlanEncode(int sourceLength, int destinationLength, bool isFinalBlock, out int bytesConsumed, out int written) { - var len = base64.Length; - while (len > 0 && base64[len - 1] == '=') + if (isFinalBlock) { - len--; + var total = EncodedLength(sourceLength); + if (total <= destinationLength) + { + bytesConsumed = sourceLength; + written = total; + return OperationStatus.Done; + } } - var chars = new char[len]; - for (var i = 0; i < len; i++) + var completeGroups = sourceLength / 3; + var groups = Math.Min(completeGroups, destinationLength / 4); + bytesConsumed = groups * 3; + written = groups * 4; + if (isFinalBlock || groups < completeGroups) { - chars[i] = base64[i] switch - { - '+' => '-', - '/' => '_', - _ => base64[i] - }; + return OperationStatus.DestinationTooSmall; + } + if (sourceLength % 3 > 0) + { + return OperationStatus.NeedMoreData; + } + return OperationStatus.Done; + } + static void Encode(ReadOnlySpan source, Span destination) + { + var map = encodeMap; + var sourceIndex = 0; + var destinationIndex = 0; + var end = source.Length - 2; + while (sourceIndex < end) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8 | source[sourceIndex + 2]; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = map[value >> 6 & 0x3F]; + destination[destinationIndex + 3] = map[value & 0x3F]; + sourceIndex += 3; + destinationIndex += 4; + } + var remaining = source.Length - sourceIndex; + if (remaining == 1) + { + var value = source[sourceIndex] << 16; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = map[value >> 6 & 0x3F]; + } + } + static void Encode(ReadOnlySpan source, Span destination) + { + var map = encodeMap; + var sourceIndex = 0; + var destinationIndex = 0; + var end = source.Length - 2; + while (sourceIndex < end) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8 | source[sourceIndex + 2]; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + destination[destinationIndex + 3] = (byte) map[value & 0x3F]; + sourceIndex += 3; + destinationIndex += 4; + } + var remaining = source.Length - sourceIndex; + if (remaining == 1) + { + var value = source[sourceIndex] << 16; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; } - return new string(chars); } static OperationStatus Decode(ReadOnlySpan source, Span destination, bool write, out int charsConsumed, out int bytesWritten, bool isFinalBlock) { @@ -478,13 +510,6 @@ static int DecodeValue(char c) } return -1; } - static void WriteStringToBytes(string source, Span destination) - { - for (var i = 0; i < source.Length; i++) - { - destination[i] = (byte)source[i]; - } - } static char[] BytesToChars(ReadOnlySpan source) { var chars = new char[source.Length]; diff --git a/src/Split/net8.0/Base64Url.cs b/src/Split/net8.0/Base64Url.cs index 817dcd19..88920e01 100644 --- a/src/Split/net8.0/Base64Url.cs +++ b/src/Split/net8.0/Base64Url.cs @@ -42,152 +42,87 @@ public static string EncodeToString(ReadOnlySpan source) { return string.Empty; } - var base64 = Convert.ToBase64String(source.ToArray()); - return ToBase64UrlString(base64); + var length = EncodedLength(source.Length); + if (length <= 256) + { + Span buffer = stackalloc char[256]; + buffer = buffer.Slice(0, length); + Encode(source, buffer); + return buffer.ToString(); + } + var rented = ArrayPool.Shared.Rent(length); + Encode(source, rented); + var result = new string(rented, 0, length); + ArrayPool.Shared.Return(rented); + return result; } /// Encodes the span of binary data into UTF-16 encoded text represented as base-64-url. public static int EncodeToChars(ReadOnlySpan source, Span destination) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { throw new ArgumentException("Destination is too small.", nameof(destination)); } - encoded.AsSpan().CopyTo(destination); - return encoded.Length; + Encode(source, destination); + return length; } /// Encodes the span of binary data into UTF-16 encoded text represented as base-64-url. public static OperationStatus EncodeToChars(ReadOnlySpan source, Span destination, out int bytesConsumed, out int charsWritten, bool isFinalBlock = true) { - if (source.IsEmpty) - { - charsWritten = 0; - bytesConsumed = 0; - return OperationStatus.Done; - } - var completeGroups = source.Length / 3; - var remainingBytes = source.Length % 3; - if (!isFinalBlock) - { - var groupsWeCanFit = Math.Min(completeGroups, destination.Length / 4); - bytesConsumed = groupsWeCanFit * 3; - charsWritten = groupsWeCanFit * 4; - if (bytesConsumed > 0) - { - EncodeToString(source.Slice(0, bytesConsumed)).AsSpan().CopyTo(destination); - } - if (groupsWeCanFit < completeGroups) - { - return OperationStatus.DestinationTooSmall; - } - return remainingBytes > 0 ? OperationStatus.NeedMoreData : OperationStatus.Done; - } - var totalChars = GetEncodedLength(source.Length); - if (totalChars <= destination.Length) - { - EncodeToString(source).AsSpan().CopyTo(destination); - charsWritten = totalChars; - bytesConsumed = source.Length; - return OperationStatus.Done; - } - var fitting = destination.Length / 4; - bytesConsumed = fitting * 3; - charsWritten = fitting * 4; - if (bytesConsumed > 0) - { - EncodeToString(source.Slice(0, bytesConsumed)).AsSpan().CopyTo(destination); - } - return OperationStatus.DestinationTooSmall; + var status = PlanEncode(source.Length, destination.Length, isFinalBlock, out bytesConsumed, out charsWritten); + Encode(source.Slice(0, bytesConsumed), destination); + return status; } /// Tries to encode the span of binary data into UTF-16 encoded text represented as base-64-url. public static bool TryEncodeToChars(ReadOnlySpan source, Span destination, out int charsWritten) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { charsWritten = 0; return false; } - encoded.AsSpan().CopyTo(destination); - charsWritten = encoded.Length; + Encode(source, destination); + charsWritten = length; return true; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static byte[] EncodeToUtf8(ReadOnlySpan source) { - var chars = EncodeToString(source); - var result = new byte[chars.Length]; - for (var i = 0; i < chars.Length; i++) - { - result[i] = (byte)chars[i]; - } + var result = new byte[EncodedLength(source.Length)]; + Encode(source, result); return result; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static int EncodeToUtf8(ReadOnlySpan source, Span destination) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { throw new ArgumentException("Destination is too small.", nameof(destination)); } - WriteStringToBytes(encoded, destination); - return encoded.Length; + Encode(source, destination); + return length; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static OperationStatus EncodeToUtf8(ReadOnlySpan source, Span destination, out int bytesConsumed, out int bytesWritten, bool isFinalBlock = true) { - if (source.IsEmpty) - { - bytesWritten = 0; - bytesConsumed = 0; - return OperationStatus.Done; - } - var completeGroups = source.Length / 3; - var remainingBytes = source.Length % 3; - if (!isFinalBlock) - { - var groupsWeCanFit = Math.Min(completeGroups, destination.Length / 4); - bytesConsumed = groupsWeCanFit * 3; - bytesWritten = groupsWeCanFit * 4; - if (bytesConsumed > 0) - { - WriteStringToBytes(EncodeToString(source.Slice(0, bytesConsumed)), destination); - } - if (groupsWeCanFit < completeGroups) - { - return OperationStatus.DestinationTooSmall; - } - return remainingBytes > 0 ? OperationStatus.NeedMoreData : OperationStatus.Done; - } - var totalBytes = GetEncodedLength(source.Length); - if (totalBytes <= destination.Length) - { - WriteStringToBytes(EncodeToString(source), destination); - bytesWritten = totalBytes; - bytesConsumed = source.Length; - return OperationStatus.Done; - } - var fitting = destination.Length / 4; - bytesConsumed = fitting * 3; - bytesWritten = fitting * 4; - if (bytesConsumed > 0) - { - WriteStringToBytes(EncodeToString(source.Slice(0, bytesConsumed)), destination); - } - return OperationStatus.DestinationTooSmall; + var status = PlanEncode(source.Length, destination.Length, isFinalBlock, out bytesConsumed, out bytesWritten); + Encode(source.Slice(0, bytesConsumed), destination); + return status; } /// Tries to encode the span of binary data into UTF-8 encoded text represented as base-64-url. public static bool TryEncodeToUtf8(ReadOnlySpan source, Span destination, out int bytesWritten) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { bytesWritten = 0; return false; } - WriteStringToBytes(encoded, destination); - bytesWritten = encoded.Length; + Encode(source, destination); + bytesWritten = length; return true; } /// Encodes the span of binary data (in-place) into UTF-8 encoded text represented as base-64-url. @@ -197,16 +132,41 @@ public static bool TryEncodeToUtf8InPlace(Span buffer, int dataLength, out { throw new ArgumentOutOfRangeException(nameof(dataLength)); } - var encodedLength = GetEncodedLength(dataLength); + var encodedLength = EncodedLength(dataLength); if (encodedLength > buffer.Length) { bytesWritten = 0; return false; } - var source = buffer.Slice(0, dataLength).ToArray(); - var encoded = EncodeToString(source); - WriteStringToBytes(encoded, buffer); - bytesWritten = encoded.Length; + var map = encodeMap; + var groups = dataLength / 3; + var sourceIndex = groups * 3; + var destinationIndex = groups * 4; + var remaining = dataLength - sourceIndex; + if (remaining == 1) + { + var value = buffer[sourceIndex] << 16; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = buffer[sourceIndex] << 16 | buffer[sourceIndex + 1] << 8; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + buffer[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + } + while (sourceIndex > 0) + { + sourceIndex -= 3; + destinationIndex -= 4; + var value = buffer[sourceIndex] << 16 | buffer[sourceIndex + 1] << 8 | buffer[sourceIndex + 2]; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + buffer[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + buffer[destinationIndex + 3] = (byte) map[value & 0x3F]; + } + bytesWritten = encodedLength; return true; } /// Decodes the span of UTF-16 encoded text represented as base-64-url into binary data. @@ -322,24 +282,96 @@ public static bool IsValid(ReadOnlySpan utf8Base64UrlText, out int decoded var chars = BytesToChars(utf8Base64UrlText); return IsValid(chars, out decodedLength); } - static string ToBase64UrlString(string base64) + const string encodeMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + static int EncodedLength(int bytesLength) => + checked((int) (((long) bytesLength * 4 + 2) / 3)); + static OperationStatus PlanEncode(int sourceLength, int destinationLength, bool isFinalBlock, out int bytesConsumed, out int written) { - var len = base64.Length; - while (len > 0 && base64[len - 1] == '=') + if (isFinalBlock) { - len--; + var total = EncodedLength(sourceLength); + if (total <= destinationLength) + { + bytesConsumed = sourceLength; + written = total; + return OperationStatus.Done; + } } - var chars = new char[len]; - for (var i = 0; i < len; i++) + var completeGroups = sourceLength / 3; + var groups = Math.Min(completeGroups, destinationLength / 4); + bytesConsumed = groups * 3; + written = groups * 4; + if (isFinalBlock || groups < completeGroups) { - chars[i] = base64[i] switch - { - '+' => '-', - '/' => '_', - _ => base64[i] - }; + return OperationStatus.DestinationTooSmall; + } + if (sourceLength % 3 > 0) + { + return OperationStatus.NeedMoreData; + } + return OperationStatus.Done; + } + static void Encode(ReadOnlySpan source, Span destination) + { + var map = encodeMap; + var sourceIndex = 0; + var destinationIndex = 0; + var end = source.Length - 2; + while (sourceIndex < end) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8 | source[sourceIndex + 2]; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = map[value >> 6 & 0x3F]; + destination[destinationIndex + 3] = map[value & 0x3F]; + sourceIndex += 3; + destinationIndex += 4; + } + var remaining = source.Length - sourceIndex; + if (remaining == 1) + { + var value = source[sourceIndex] << 16; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = map[value >> 6 & 0x3F]; + } + } + static void Encode(ReadOnlySpan source, Span destination) + { + var map = encodeMap; + var sourceIndex = 0; + var destinationIndex = 0; + var end = source.Length - 2; + while (sourceIndex < end) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8 | source[sourceIndex + 2]; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + destination[destinationIndex + 3] = (byte) map[value & 0x3F]; + sourceIndex += 3; + destinationIndex += 4; + } + var remaining = source.Length - sourceIndex; + if (remaining == 1) + { + var value = source[sourceIndex] << 16; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; } - return new string(chars); } static OperationStatus Decode(ReadOnlySpan source, Span destination, bool write, out int charsConsumed, out int bytesWritten, bool isFinalBlock) { @@ -478,13 +510,6 @@ static int DecodeValue(char c) } return -1; } - static void WriteStringToBytes(string source, Span destination) - { - for (var i = 0; i < source.Length; i++) - { - destination[i] = (byte)source[i]; - } - } static char[] BytesToChars(ReadOnlySpan source) { var chars = new char[source.Length]; diff --git a/src/Split/netcoreapp2.0/Base64Url.cs b/src/Split/netcoreapp2.0/Base64Url.cs index 817dcd19..88920e01 100644 --- a/src/Split/netcoreapp2.0/Base64Url.cs +++ b/src/Split/netcoreapp2.0/Base64Url.cs @@ -42,152 +42,87 @@ public static string EncodeToString(ReadOnlySpan source) { return string.Empty; } - var base64 = Convert.ToBase64String(source.ToArray()); - return ToBase64UrlString(base64); + var length = EncodedLength(source.Length); + if (length <= 256) + { + Span buffer = stackalloc char[256]; + buffer = buffer.Slice(0, length); + Encode(source, buffer); + return buffer.ToString(); + } + var rented = ArrayPool.Shared.Rent(length); + Encode(source, rented); + var result = new string(rented, 0, length); + ArrayPool.Shared.Return(rented); + return result; } /// Encodes the span of binary data into UTF-16 encoded text represented as base-64-url. public static int EncodeToChars(ReadOnlySpan source, Span destination) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { throw new ArgumentException("Destination is too small.", nameof(destination)); } - encoded.AsSpan().CopyTo(destination); - return encoded.Length; + Encode(source, destination); + return length; } /// Encodes the span of binary data into UTF-16 encoded text represented as base-64-url. public static OperationStatus EncodeToChars(ReadOnlySpan source, Span destination, out int bytesConsumed, out int charsWritten, bool isFinalBlock = true) { - if (source.IsEmpty) - { - charsWritten = 0; - bytesConsumed = 0; - return OperationStatus.Done; - } - var completeGroups = source.Length / 3; - var remainingBytes = source.Length % 3; - if (!isFinalBlock) - { - var groupsWeCanFit = Math.Min(completeGroups, destination.Length / 4); - bytesConsumed = groupsWeCanFit * 3; - charsWritten = groupsWeCanFit * 4; - if (bytesConsumed > 0) - { - EncodeToString(source.Slice(0, bytesConsumed)).AsSpan().CopyTo(destination); - } - if (groupsWeCanFit < completeGroups) - { - return OperationStatus.DestinationTooSmall; - } - return remainingBytes > 0 ? OperationStatus.NeedMoreData : OperationStatus.Done; - } - var totalChars = GetEncodedLength(source.Length); - if (totalChars <= destination.Length) - { - EncodeToString(source).AsSpan().CopyTo(destination); - charsWritten = totalChars; - bytesConsumed = source.Length; - return OperationStatus.Done; - } - var fitting = destination.Length / 4; - bytesConsumed = fitting * 3; - charsWritten = fitting * 4; - if (bytesConsumed > 0) - { - EncodeToString(source.Slice(0, bytesConsumed)).AsSpan().CopyTo(destination); - } - return OperationStatus.DestinationTooSmall; + var status = PlanEncode(source.Length, destination.Length, isFinalBlock, out bytesConsumed, out charsWritten); + Encode(source.Slice(0, bytesConsumed), destination); + return status; } /// Tries to encode the span of binary data into UTF-16 encoded text represented as base-64-url. public static bool TryEncodeToChars(ReadOnlySpan source, Span destination, out int charsWritten) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { charsWritten = 0; return false; } - encoded.AsSpan().CopyTo(destination); - charsWritten = encoded.Length; + Encode(source, destination); + charsWritten = length; return true; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static byte[] EncodeToUtf8(ReadOnlySpan source) { - var chars = EncodeToString(source); - var result = new byte[chars.Length]; - for (var i = 0; i < chars.Length; i++) - { - result[i] = (byte)chars[i]; - } + var result = new byte[EncodedLength(source.Length)]; + Encode(source, result); return result; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static int EncodeToUtf8(ReadOnlySpan source, Span destination) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { throw new ArgumentException("Destination is too small.", nameof(destination)); } - WriteStringToBytes(encoded, destination); - return encoded.Length; + Encode(source, destination); + return length; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static OperationStatus EncodeToUtf8(ReadOnlySpan source, Span destination, out int bytesConsumed, out int bytesWritten, bool isFinalBlock = true) { - if (source.IsEmpty) - { - bytesWritten = 0; - bytesConsumed = 0; - return OperationStatus.Done; - } - var completeGroups = source.Length / 3; - var remainingBytes = source.Length % 3; - if (!isFinalBlock) - { - var groupsWeCanFit = Math.Min(completeGroups, destination.Length / 4); - bytesConsumed = groupsWeCanFit * 3; - bytesWritten = groupsWeCanFit * 4; - if (bytesConsumed > 0) - { - WriteStringToBytes(EncodeToString(source.Slice(0, bytesConsumed)), destination); - } - if (groupsWeCanFit < completeGroups) - { - return OperationStatus.DestinationTooSmall; - } - return remainingBytes > 0 ? OperationStatus.NeedMoreData : OperationStatus.Done; - } - var totalBytes = GetEncodedLength(source.Length); - if (totalBytes <= destination.Length) - { - WriteStringToBytes(EncodeToString(source), destination); - bytesWritten = totalBytes; - bytesConsumed = source.Length; - return OperationStatus.Done; - } - var fitting = destination.Length / 4; - bytesConsumed = fitting * 3; - bytesWritten = fitting * 4; - if (bytesConsumed > 0) - { - WriteStringToBytes(EncodeToString(source.Slice(0, bytesConsumed)), destination); - } - return OperationStatus.DestinationTooSmall; + var status = PlanEncode(source.Length, destination.Length, isFinalBlock, out bytesConsumed, out bytesWritten); + Encode(source.Slice(0, bytesConsumed), destination); + return status; } /// Tries to encode the span of binary data into UTF-8 encoded text represented as base-64-url. public static bool TryEncodeToUtf8(ReadOnlySpan source, Span destination, out int bytesWritten) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { bytesWritten = 0; return false; } - WriteStringToBytes(encoded, destination); - bytesWritten = encoded.Length; + Encode(source, destination); + bytesWritten = length; return true; } /// Encodes the span of binary data (in-place) into UTF-8 encoded text represented as base-64-url. @@ -197,16 +132,41 @@ public static bool TryEncodeToUtf8InPlace(Span buffer, int dataLength, out { throw new ArgumentOutOfRangeException(nameof(dataLength)); } - var encodedLength = GetEncodedLength(dataLength); + var encodedLength = EncodedLength(dataLength); if (encodedLength > buffer.Length) { bytesWritten = 0; return false; } - var source = buffer.Slice(0, dataLength).ToArray(); - var encoded = EncodeToString(source); - WriteStringToBytes(encoded, buffer); - bytesWritten = encoded.Length; + var map = encodeMap; + var groups = dataLength / 3; + var sourceIndex = groups * 3; + var destinationIndex = groups * 4; + var remaining = dataLength - sourceIndex; + if (remaining == 1) + { + var value = buffer[sourceIndex] << 16; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = buffer[sourceIndex] << 16 | buffer[sourceIndex + 1] << 8; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + buffer[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + } + while (sourceIndex > 0) + { + sourceIndex -= 3; + destinationIndex -= 4; + var value = buffer[sourceIndex] << 16 | buffer[sourceIndex + 1] << 8 | buffer[sourceIndex + 2]; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + buffer[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + buffer[destinationIndex + 3] = (byte) map[value & 0x3F]; + } + bytesWritten = encodedLength; return true; } /// Decodes the span of UTF-16 encoded text represented as base-64-url into binary data. @@ -322,24 +282,96 @@ public static bool IsValid(ReadOnlySpan utf8Base64UrlText, out int decoded var chars = BytesToChars(utf8Base64UrlText); return IsValid(chars, out decodedLength); } - static string ToBase64UrlString(string base64) + const string encodeMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + static int EncodedLength(int bytesLength) => + checked((int) (((long) bytesLength * 4 + 2) / 3)); + static OperationStatus PlanEncode(int sourceLength, int destinationLength, bool isFinalBlock, out int bytesConsumed, out int written) { - var len = base64.Length; - while (len > 0 && base64[len - 1] == '=') + if (isFinalBlock) { - len--; + var total = EncodedLength(sourceLength); + if (total <= destinationLength) + { + bytesConsumed = sourceLength; + written = total; + return OperationStatus.Done; + } } - var chars = new char[len]; - for (var i = 0; i < len; i++) + var completeGroups = sourceLength / 3; + var groups = Math.Min(completeGroups, destinationLength / 4); + bytesConsumed = groups * 3; + written = groups * 4; + if (isFinalBlock || groups < completeGroups) { - chars[i] = base64[i] switch - { - '+' => '-', - '/' => '_', - _ => base64[i] - }; + return OperationStatus.DestinationTooSmall; + } + if (sourceLength % 3 > 0) + { + return OperationStatus.NeedMoreData; + } + return OperationStatus.Done; + } + static void Encode(ReadOnlySpan source, Span destination) + { + var map = encodeMap; + var sourceIndex = 0; + var destinationIndex = 0; + var end = source.Length - 2; + while (sourceIndex < end) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8 | source[sourceIndex + 2]; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = map[value >> 6 & 0x3F]; + destination[destinationIndex + 3] = map[value & 0x3F]; + sourceIndex += 3; + destinationIndex += 4; + } + var remaining = source.Length - sourceIndex; + if (remaining == 1) + { + var value = source[sourceIndex] << 16; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = map[value >> 6 & 0x3F]; + } + } + static void Encode(ReadOnlySpan source, Span destination) + { + var map = encodeMap; + var sourceIndex = 0; + var destinationIndex = 0; + var end = source.Length - 2; + while (sourceIndex < end) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8 | source[sourceIndex + 2]; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + destination[destinationIndex + 3] = (byte) map[value & 0x3F]; + sourceIndex += 3; + destinationIndex += 4; + } + var remaining = source.Length - sourceIndex; + if (remaining == 1) + { + var value = source[sourceIndex] << 16; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; } - return new string(chars); } static OperationStatus Decode(ReadOnlySpan source, Span destination, bool write, out int charsConsumed, out int bytesWritten, bool isFinalBlock) { @@ -478,13 +510,6 @@ static int DecodeValue(char c) } return -1; } - static void WriteStringToBytes(string source, Span destination) - { - for (var i = 0; i < source.Length; i++) - { - destination[i] = (byte)source[i]; - } - } static char[] BytesToChars(ReadOnlySpan source) { var chars = new char[source.Length]; diff --git a/src/Split/netcoreapp2.1/Base64Url.cs b/src/Split/netcoreapp2.1/Base64Url.cs index 817dcd19..88920e01 100644 --- a/src/Split/netcoreapp2.1/Base64Url.cs +++ b/src/Split/netcoreapp2.1/Base64Url.cs @@ -42,152 +42,87 @@ public static string EncodeToString(ReadOnlySpan source) { return string.Empty; } - var base64 = Convert.ToBase64String(source.ToArray()); - return ToBase64UrlString(base64); + var length = EncodedLength(source.Length); + if (length <= 256) + { + Span buffer = stackalloc char[256]; + buffer = buffer.Slice(0, length); + Encode(source, buffer); + return buffer.ToString(); + } + var rented = ArrayPool.Shared.Rent(length); + Encode(source, rented); + var result = new string(rented, 0, length); + ArrayPool.Shared.Return(rented); + return result; } /// Encodes the span of binary data into UTF-16 encoded text represented as base-64-url. public static int EncodeToChars(ReadOnlySpan source, Span destination) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { throw new ArgumentException("Destination is too small.", nameof(destination)); } - encoded.AsSpan().CopyTo(destination); - return encoded.Length; + Encode(source, destination); + return length; } /// Encodes the span of binary data into UTF-16 encoded text represented as base-64-url. public static OperationStatus EncodeToChars(ReadOnlySpan source, Span destination, out int bytesConsumed, out int charsWritten, bool isFinalBlock = true) { - if (source.IsEmpty) - { - charsWritten = 0; - bytesConsumed = 0; - return OperationStatus.Done; - } - var completeGroups = source.Length / 3; - var remainingBytes = source.Length % 3; - if (!isFinalBlock) - { - var groupsWeCanFit = Math.Min(completeGroups, destination.Length / 4); - bytesConsumed = groupsWeCanFit * 3; - charsWritten = groupsWeCanFit * 4; - if (bytesConsumed > 0) - { - EncodeToString(source.Slice(0, bytesConsumed)).AsSpan().CopyTo(destination); - } - if (groupsWeCanFit < completeGroups) - { - return OperationStatus.DestinationTooSmall; - } - return remainingBytes > 0 ? OperationStatus.NeedMoreData : OperationStatus.Done; - } - var totalChars = GetEncodedLength(source.Length); - if (totalChars <= destination.Length) - { - EncodeToString(source).AsSpan().CopyTo(destination); - charsWritten = totalChars; - bytesConsumed = source.Length; - return OperationStatus.Done; - } - var fitting = destination.Length / 4; - bytesConsumed = fitting * 3; - charsWritten = fitting * 4; - if (bytesConsumed > 0) - { - EncodeToString(source.Slice(0, bytesConsumed)).AsSpan().CopyTo(destination); - } - return OperationStatus.DestinationTooSmall; + var status = PlanEncode(source.Length, destination.Length, isFinalBlock, out bytesConsumed, out charsWritten); + Encode(source.Slice(0, bytesConsumed), destination); + return status; } /// Tries to encode the span of binary data into UTF-16 encoded text represented as base-64-url. public static bool TryEncodeToChars(ReadOnlySpan source, Span destination, out int charsWritten) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { charsWritten = 0; return false; } - encoded.AsSpan().CopyTo(destination); - charsWritten = encoded.Length; + Encode(source, destination); + charsWritten = length; return true; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static byte[] EncodeToUtf8(ReadOnlySpan source) { - var chars = EncodeToString(source); - var result = new byte[chars.Length]; - for (var i = 0; i < chars.Length; i++) - { - result[i] = (byte)chars[i]; - } + var result = new byte[EncodedLength(source.Length)]; + Encode(source, result); return result; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static int EncodeToUtf8(ReadOnlySpan source, Span destination) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { throw new ArgumentException("Destination is too small.", nameof(destination)); } - WriteStringToBytes(encoded, destination); - return encoded.Length; + Encode(source, destination); + return length; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static OperationStatus EncodeToUtf8(ReadOnlySpan source, Span destination, out int bytesConsumed, out int bytesWritten, bool isFinalBlock = true) { - if (source.IsEmpty) - { - bytesWritten = 0; - bytesConsumed = 0; - return OperationStatus.Done; - } - var completeGroups = source.Length / 3; - var remainingBytes = source.Length % 3; - if (!isFinalBlock) - { - var groupsWeCanFit = Math.Min(completeGroups, destination.Length / 4); - bytesConsumed = groupsWeCanFit * 3; - bytesWritten = groupsWeCanFit * 4; - if (bytesConsumed > 0) - { - WriteStringToBytes(EncodeToString(source.Slice(0, bytesConsumed)), destination); - } - if (groupsWeCanFit < completeGroups) - { - return OperationStatus.DestinationTooSmall; - } - return remainingBytes > 0 ? OperationStatus.NeedMoreData : OperationStatus.Done; - } - var totalBytes = GetEncodedLength(source.Length); - if (totalBytes <= destination.Length) - { - WriteStringToBytes(EncodeToString(source), destination); - bytesWritten = totalBytes; - bytesConsumed = source.Length; - return OperationStatus.Done; - } - var fitting = destination.Length / 4; - bytesConsumed = fitting * 3; - bytesWritten = fitting * 4; - if (bytesConsumed > 0) - { - WriteStringToBytes(EncodeToString(source.Slice(0, bytesConsumed)), destination); - } - return OperationStatus.DestinationTooSmall; + var status = PlanEncode(source.Length, destination.Length, isFinalBlock, out bytesConsumed, out bytesWritten); + Encode(source.Slice(0, bytesConsumed), destination); + return status; } /// Tries to encode the span of binary data into UTF-8 encoded text represented as base-64-url. public static bool TryEncodeToUtf8(ReadOnlySpan source, Span destination, out int bytesWritten) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { bytesWritten = 0; return false; } - WriteStringToBytes(encoded, destination); - bytesWritten = encoded.Length; + Encode(source, destination); + bytesWritten = length; return true; } /// Encodes the span of binary data (in-place) into UTF-8 encoded text represented as base-64-url. @@ -197,16 +132,41 @@ public static bool TryEncodeToUtf8InPlace(Span buffer, int dataLength, out { throw new ArgumentOutOfRangeException(nameof(dataLength)); } - var encodedLength = GetEncodedLength(dataLength); + var encodedLength = EncodedLength(dataLength); if (encodedLength > buffer.Length) { bytesWritten = 0; return false; } - var source = buffer.Slice(0, dataLength).ToArray(); - var encoded = EncodeToString(source); - WriteStringToBytes(encoded, buffer); - bytesWritten = encoded.Length; + var map = encodeMap; + var groups = dataLength / 3; + var sourceIndex = groups * 3; + var destinationIndex = groups * 4; + var remaining = dataLength - sourceIndex; + if (remaining == 1) + { + var value = buffer[sourceIndex] << 16; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = buffer[sourceIndex] << 16 | buffer[sourceIndex + 1] << 8; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + buffer[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + } + while (sourceIndex > 0) + { + sourceIndex -= 3; + destinationIndex -= 4; + var value = buffer[sourceIndex] << 16 | buffer[sourceIndex + 1] << 8 | buffer[sourceIndex + 2]; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + buffer[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + buffer[destinationIndex + 3] = (byte) map[value & 0x3F]; + } + bytesWritten = encodedLength; return true; } /// Decodes the span of UTF-16 encoded text represented as base-64-url into binary data. @@ -322,24 +282,96 @@ public static bool IsValid(ReadOnlySpan utf8Base64UrlText, out int decoded var chars = BytesToChars(utf8Base64UrlText); return IsValid(chars, out decodedLength); } - static string ToBase64UrlString(string base64) + const string encodeMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + static int EncodedLength(int bytesLength) => + checked((int) (((long) bytesLength * 4 + 2) / 3)); + static OperationStatus PlanEncode(int sourceLength, int destinationLength, bool isFinalBlock, out int bytesConsumed, out int written) { - var len = base64.Length; - while (len > 0 && base64[len - 1] == '=') + if (isFinalBlock) { - len--; + var total = EncodedLength(sourceLength); + if (total <= destinationLength) + { + bytesConsumed = sourceLength; + written = total; + return OperationStatus.Done; + } } - var chars = new char[len]; - for (var i = 0; i < len; i++) + var completeGroups = sourceLength / 3; + var groups = Math.Min(completeGroups, destinationLength / 4); + bytesConsumed = groups * 3; + written = groups * 4; + if (isFinalBlock || groups < completeGroups) { - chars[i] = base64[i] switch - { - '+' => '-', - '/' => '_', - _ => base64[i] - }; + return OperationStatus.DestinationTooSmall; + } + if (sourceLength % 3 > 0) + { + return OperationStatus.NeedMoreData; + } + return OperationStatus.Done; + } + static void Encode(ReadOnlySpan source, Span destination) + { + var map = encodeMap; + var sourceIndex = 0; + var destinationIndex = 0; + var end = source.Length - 2; + while (sourceIndex < end) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8 | source[sourceIndex + 2]; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = map[value >> 6 & 0x3F]; + destination[destinationIndex + 3] = map[value & 0x3F]; + sourceIndex += 3; + destinationIndex += 4; + } + var remaining = source.Length - sourceIndex; + if (remaining == 1) + { + var value = source[sourceIndex] << 16; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = map[value >> 6 & 0x3F]; + } + } + static void Encode(ReadOnlySpan source, Span destination) + { + var map = encodeMap; + var sourceIndex = 0; + var destinationIndex = 0; + var end = source.Length - 2; + while (sourceIndex < end) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8 | source[sourceIndex + 2]; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + destination[destinationIndex + 3] = (byte) map[value & 0x3F]; + sourceIndex += 3; + destinationIndex += 4; + } + var remaining = source.Length - sourceIndex; + if (remaining == 1) + { + var value = source[sourceIndex] << 16; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; } - return new string(chars); } static OperationStatus Decode(ReadOnlySpan source, Span destination, bool write, out int charsConsumed, out int bytesWritten, bool isFinalBlock) { @@ -478,13 +510,6 @@ static int DecodeValue(char c) } return -1; } - static void WriteStringToBytes(string source, Span destination) - { - for (var i = 0; i < source.Length; i++) - { - destination[i] = (byte)source[i]; - } - } static char[] BytesToChars(ReadOnlySpan source) { var chars = new char[source.Length]; diff --git a/src/Split/netcoreapp2.2/Base64Url.cs b/src/Split/netcoreapp2.2/Base64Url.cs index 817dcd19..88920e01 100644 --- a/src/Split/netcoreapp2.2/Base64Url.cs +++ b/src/Split/netcoreapp2.2/Base64Url.cs @@ -42,152 +42,87 @@ public static string EncodeToString(ReadOnlySpan source) { return string.Empty; } - var base64 = Convert.ToBase64String(source.ToArray()); - return ToBase64UrlString(base64); + var length = EncodedLength(source.Length); + if (length <= 256) + { + Span buffer = stackalloc char[256]; + buffer = buffer.Slice(0, length); + Encode(source, buffer); + return buffer.ToString(); + } + var rented = ArrayPool.Shared.Rent(length); + Encode(source, rented); + var result = new string(rented, 0, length); + ArrayPool.Shared.Return(rented); + return result; } /// Encodes the span of binary data into UTF-16 encoded text represented as base-64-url. public static int EncodeToChars(ReadOnlySpan source, Span destination) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { throw new ArgumentException("Destination is too small.", nameof(destination)); } - encoded.AsSpan().CopyTo(destination); - return encoded.Length; + Encode(source, destination); + return length; } /// Encodes the span of binary data into UTF-16 encoded text represented as base-64-url. public static OperationStatus EncodeToChars(ReadOnlySpan source, Span destination, out int bytesConsumed, out int charsWritten, bool isFinalBlock = true) { - if (source.IsEmpty) - { - charsWritten = 0; - bytesConsumed = 0; - return OperationStatus.Done; - } - var completeGroups = source.Length / 3; - var remainingBytes = source.Length % 3; - if (!isFinalBlock) - { - var groupsWeCanFit = Math.Min(completeGroups, destination.Length / 4); - bytesConsumed = groupsWeCanFit * 3; - charsWritten = groupsWeCanFit * 4; - if (bytesConsumed > 0) - { - EncodeToString(source.Slice(0, bytesConsumed)).AsSpan().CopyTo(destination); - } - if (groupsWeCanFit < completeGroups) - { - return OperationStatus.DestinationTooSmall; - } - return remainingBytes > 0 ? OperationStatus.NeedMoreData : OperationStatus.Done; - } - var totalChars = GetEncodedLength(source.Length); - if (totalChars <= destination.Length) - { - EncodeToString(source).AsSpan().CopyTo(destination); - charsWritten = totalChars; - bytesConsumed = source.Length; - return OperationStatus.Done; - } - var fitting = destination.Length / 4; - bytesConsumed = fitting * 3; - charsWritten = fitting * 4; - if (bytesConsumed > 0) - { - EncodeToString(source.Slice(0, bytesConsumed)).AsSpan().CopyTo(destination); - } - return OperationStatus.DestinationTooSmall; + var status = PlanEncode(source.Length, destination.Length, isFinalBlock, out bytesConsumed, out charsWritten); + Encode(source.Slice(0, bytesConsumed), destination); + return status; } /// Tries to encode the span of binary data into UTF-16 encoded text represented as base-64-url. public static bool TryEncodeToChars(ReadOnlySpan source, Span destination, out int charsWritten) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { charsWritten = 0; return false; } - encoded.AsSpan().CopyTo(destination); - charsWritten = encoded.Length; + Encode(source, destination); + charsWritten = length; return true; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static byte[] EncodeToUtf8(ReadOnlySpan source) { - var chars = EncodeToString(source); - var result = new byte[chars.Length]; - for (var i = 0; i < chars.Length; i++) - { - result[i] = (byte)chars[i]; - } + var result = new byte[EncodedLength(source.Length)]; + Encode(source, result); return result; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static int EncodeToUtf8(ReadOnlySpan source, Span destination) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { throw new ArgumentException("Destination is too small.", nameof(destination)); } - WriteStringToBytes(encoded, destination); - return encoded.Length; + Encode(source, destination); + return length; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static OperationStatus EncodeToUtf8(ReadOnlySpan source, Span destination, out int bytesConsumed, out int bytesWritten, bool isFinalBlock = true) { - if (source.IsEmpty) - { - bytesWritten = 0; - bytesConsumed = 0; - return OperationStatus.Done; - } - var completeGroups = source.Length / 3; - var remainingBytes = source.Length % 3; - if (!isFinalBlock) - { - var groupsWeCanFit = Math.Min(completeGroups, destination.Length / 4); - bytesConsumed = groupsWeCanFit * 3; - bytesWritten = groupsWeCanFit * 4; - if (bytesConsumed > 0) - { - WriteStringToBytes(EncodeToString(source.Slice(0, bytesConsumed)), destination); - } - if (groupsWeCanFit < completeGroups) - { - return OperationStatus.DestinationTooSmall; - } - return remainingBytes > 0 ? OperationStatus.NeedMoreData : OperationStatus.Done; - } - var totalBytes = GetEncodedLength(source.Length); - if (totalBytes <= destination.Length) - { - WriteStringToBytes(EncodeToString(source), destination); - bytesWritten = totalBytes; - bytesConsumed = source.Length; - return OperationStatus.Done; - } - var fitting = destination.Length / 4; - bytesConsumed = fitting * 3; - bytesWritten = fitting * 4; - if (bytesConsumed > 0) - { - WriteStringToBytes(EncodeToString(source.Slice(0, bytesConsumed)), destination); - } - return OperationStatus.DestinationTooSmall; + var status = PlanEncode(source.Length, destination.Length, isFinalBlock, out bytesConsumed, out bytesWritten); + Encode(source.Slice(0, bytesConsumed), destination); + return status; } /// Tries to encode the span of binary data into UTF-8 encoded text represented as base-64-url. public static bool TryEncodeToUtf8(ReadOnlySpan source, Span destination, out int bytesWritten) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { bytesWritten = 0; return false; } - WriteStringToBytes(encoded, destination); - bytesWritten = encoded.Length; + Encode(source, destination); + bytesWritten = length; return true; } /// Encodes the span of binary data (in-place) into UTF-8 encoded text represented as base-64-url. @@ -197,16 +132,41 @@ public static bool TryEncodeToUtf8InPlace(Span buffer, int dataLength, out { throw new ArgumentOutOfRangeException(nameof(dataLength)); } - var encodedLength = GetEncodedLength(dataLength); + var encodedLength = EncodedLength(dataLength); if (encodedLength > buffer.Length) { bytesWritten = 0; return false; } - var source = buffer.Slice(0, dataLength).ToArray(); - var encoded = EncodeToString(source); - WriteStringToBytes(encoded, buffer); - bytesWritten = encoded.Length; + var map = encodeMap; + var groups = dataLength / 3; + var sourceIndex = groups * 3; + var destinationIndex = groups * 4; + var remaining = dataLength - sourceIndex; + if (remaining == 1) + { + var value = buffer[sourceIndex] << 16; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = buffer[sourceIndex] << 16 | buffer[sourceIndex + 1] << 8; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + buffer[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + } + while (sourceIndex > 0) + { + sourceIndex -= 3; + destinationIndex -= 4; + var value = buffer[sourceIndex] << 16 | buffer[sourceIndex + 1] << 8 | buffer[sourceIndex + 2]; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + buffer[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + buffer[destinationIndex + 3] = (byte) map[value & 0x3F]; + } + bytesWritten = encodedLength; return true; } /// Decodes the span of UTF-16 encoded text represented as base-64-url into binary data. @@ -322,24 +282,96 @@ public static bool IsValid(ReadOnlySpan utf8Base64UrlText, out int decoded var chars = BytesToChars(utf8Base64UrlText); return IsValid(chars, out decodedLength); } - static string ToBase64UrlString(string base64) + const string encodeMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + static int EncodedLength(int bytesLength) => + checked((int) (((long) bytesLength * 4 + 2) / 3)); + static OperationStatus PlanEncode(int sourceLength, int destinationLength, bool isFinalBlock, out int bytesConsumed, out int written) { - var len = base64.Length; - while (len > 0 && base64[len - 1] == '=') + if (isFinalBlock) { - len--; + var total = EncodedLength(sourceLength); + if (total <= destinationLength) + { + bytesConsumed = sourceLength; + written = total; + return OperationStatus.Done; + } } - var chars = new char[len]; - for (var i = 0; i < len; i++) + var completeGroups = sourceLength / 3; + var groups = Math.Min(completeGroups, destinationLength / 4); + bytesConsumed = groups * 3; + written = groups * 4; + if (isFinalBlock || groups < completeGroups) { - chars[i] = base64[i] switch - { - '+' => '-', - '/' => '_', - _ => base64[i] - }; + return OperationStatus.DestinationTooSmall; + } + if (sourceLength % 3 > 0) + { + return OperationStatus.NeedMoreData; + } + return OperationStatus.Done; + } + static void Encode(ReadOnlySpan source, Span destination) + { + var map = encodeMap; + var sourceIndex = 0; + var destinationIndex = 0; + var end = source.Length - 2; + while (sourceIndex < end) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8 | source[sourceIndex + 2]; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = map[value >> 6 & 0x3F]; + destination[destinationIndex + 3] = map[value & 0x3F]; + sourceIndex += 3; + destinationIndex += 4; + } + var remaining = source.Length - sourceIndex; + if (remaining == 1) + { + var value = source[sourceIndex] << 16; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = map[value >> 6 & 0x3F]; + } + } + static void Encode(ReadOnlySpan source, Span destination) + { + var map = encodeMap; + var sourceIndex = 0; + var destinationIndex = 0; + var end = source.Length - 2; + while (sourceIndex < end) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8 | source[sourceIndex + 2]; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + destination[destinationIndex + 3] = (byte) map[value & 0x3F]; + sourceIndex += 3; + destinationIndex += 4; + } + var remaining = source.Length - sourceIndex; + if (remaining == 1) + { + var value = source[sourceIndex] << 16; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; } - return new string(chars); } static OperationStatus Decode(ReadOnlySpan source, Span destination, bool write, out int charsConsumed, out int bytesWritten, bool isFinalBlock) { @@ -478,13 +510,6 @@ static int DecodeValue(char c) } return -1; } - static void WriteStringToBytes(string source, Span destination) - { - for (var i = 0; i < source.Length; i++) - { - destination[i] = (byte)source[i]; - } - } static char[] BytesToChars(ReadOnlySpan source) { var chars = new char[source.Length]; diff --git a/src/Split/netcoreapp3.0/Base64Url.cs b/src/Split/netcoreapp3.0/Base64Url.cs index 817dcd19..88920e01 100644 --- a/src/Split/netcoreapp3.0/Base64Url.cs +++ b/src/Split/netcoreapp3.0/Base64Url.cs @@ -42,152 +42,87 @@ public static string EncodeToString(ReadOnlySpan source) { return string.Empty; } - var base64 = Convert.ToBase64String(source.ToArray()); - return ToBase64UrlString(base64); + var length = EncodedLength(source.Length); + if (length <= 256) + { + Span buffer = stackalloc char[256]; + buffer = buffer.Slice(0, length); + Encode(source, buffer); + return buffer.ToString(); + } + var rented = ArrayPool.Shared.Rent(length); + Encode(source, rented); + var result = new string(rented, 0, length); + ArrayPool.Shared.Return(rented); + return result; } /// Encodes the span of binary data into UTF-16 encoded text represented as base-64-url. public static int EncodeToChars(ReadOnlySpan source, Span destination) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { throw new ArgumentException("Destination is too small.", nameof(destination)); } - encoded.AsSpan().CopyTo(destination); - return encoded.Length; + Encode(source, destination); + return length; } /// Encodes the span of binary data into UTF-16 encoded text represented as base-64-url. public static OperationStatus EncodeToChars(ReadOnlySpan source, Span destination, out int bytesConsumed, out int charsWritten, bool isFinalBlock = true) { - if (source.IsEmpty) - { - charsWritten = 0; - bytesConsumed = 0; - return OperationStatus.Done; - } - var completeGroups = source.Length / 3; - var remainingBytes = source.Length % 3; - if (!isFinalBlock) - { - var groupsWeCanFit = Math.Min(completeGroups, destination.Length / 4); - bytesConsumed = groupsWeCanFit * 3; - charsWritten = groupsWeCanFit * 4; - if (bytesConsumed > 0) - { - EncodeToString(source.Slice(0, bytesConsumed)).AsSpan().CopyTo(destination); - } - if (groupsWeCanFit < completeGroups) - { - return OperationStatus.DestinationTooSmall; - } - return remainingBytes > 0 ? OperationStatus.NeedMoreData : OperationStatus.Done; - } - var totalChars = GetEncodedLength(source.Length); - if (totalChars <= destination.Length) - { - EncodeToString(source).AsSpan().CopyTo(destination); - charsWritten = totalChars; - bytesConsumed = source.Length; - return OperationStatus.Done; - } - var fitting = destination.Length / 4; - bytesConsumed = fitting * 3; - charsWritten = fitting * 4; - if (bytesConsumed > 0) - { - EncodeToString(source.Slice(0, bytesConsumed)).AsSpan().CopyTo(destination); - } - return OperationStatus.DestinationTooSmall; + var status = PlanEncode(source.Length, destination.Length, isFinalBlock, out bytesConsumed, out charsWritten); + Encode(source.Slice(0, bytesConsumed), destination); + return status; } /// Tries to encode the span of binary data into UTF-16 encoded text represented as base-64-url. public static bool TryEncodeToChars(ReadOnlySpan source, Span destination, out int charsWritten) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { charsWritten = 0; return false; } - encoded.AsSpan().CopyTo(destination); - charsWritten = encoded.Length; + Encode(source, destination); + charsWritten = length; return true; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static byte[] EncodeToUtf8(ReadOnlySpan source) { - var chars = EncodeToString(source); - var result = new byte[chars.Length]; - for (var i = 0; i < chars.Length; i++) - { - result[i] = (byte)chars[i]; - } + var result = new byte[EncodedLength(source.Length)]; + Encode(source, result); return result; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static int EncodeToUtf8(ReadOnlySpan source, Span destination) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { throw new ArgumentException("Destination is too small.", nameof(destination)); } - WriteStringToBytes(encoded, destination); - return encoded.Length; + Encode(source, destination); + return length; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static OperationStatus EncodeToUtf8(ReadOnlySpan source, Span destination, out int bytesConsumed, out int bytesWritten, bool isFinalBlock = true) { - if (source.IsEmpty) - { - bytesWritten = 0; - bytesConsumed = 0; - return OperationStatus.Done; - } - var completeGroups = source.Length / 3; - var remainingBytes = source.Length % 3; - if (!isFinalBlock) - { - var groupsWeCanFit = Math.Min(completeGroups, destination.Length / 4); - bytesConsumed = groupsWeCanFit * 3; - bytesWritten = groupsWeCanFit * 4; - if (bytesConsumed > 0) - { - WriteStringToBytes(EncodeToString(source.Slice(0, bytesConsumed)), destination); - } - if (groupsWeCanFit < completeGroups) - { - return OperationStatus.DestinationTooSmall; - } - return remainingBytes > 0 ? OperationStatus.NeedMoreData : OperationStatus.Done; - } - var totalBytes = GetEncodedLength(source.Length); - if (totalBytes <= destination.Length) - { - WriteStringToBytes(EncodeToString(source), destination); - bytesWritten = totalBytes; - bytesConsumed = source.Length; - return OperationStatus.Done; - } - var fitting = destination.Length / 4; - bytesConsumed = fitting * 3; - bytesWritten = fitting * 4; - if (bytesConsumed > 0) - { - WriteStringToBytes(EncodeToString(source.Slice(0, bytesConsumed)), destination); - } - return OperationStatus.DestinationTooSmall; + var status = PlanEncode(source.Length, destination.Length, isFinalBlock, out bytesConsumed, out bytesWritten); + Encode(source.Slice(0, bytesConsumed), destination); + return status; } /// Tries to encode the span of binary data into UTF-8 encoded text represented as base-64-url. public static bool TryEncodeToUtf8(ReadOnlySpan source, Span destination, out int bytesWritten) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { bytesWritten = 0; return false; } - WriteStringToBytes(encoded, destination); - bytesWritten = encoded.Length; + Encode(source, destination); + bytesWritten = length; return true; } /// Encodes the span of binary data (in-place) into UTF-8 encoded text represented as base-64-url. @@ -197,16 +132,41 @@ public static bool TryEncodeToUtf8InPlace(Span buffer, int dataLength, out { throw new ArgumentOutOfRangeException(nameof(dataLength)); } - var encodedLength = GetEncodedLength(dataLength); + var encodedLength = EncodedLength(dataLength); if (encodedLength > buffer.Length) { bytesWritten = 0; return false; } - var source = buffer.Slice(0, dataLength).ToArray(); - var encoded = EncodeToString(source); - WriteStringToBytes(encoded, buffer); - bytesWritten = encoded.Length; + var map = encodeMap; + var groups = dataLength / 3; + var sourceIndex = groups * 3; + var destinationIndex = groups * 4; + var remaining = dataLength - sourceIndex; + if (remaining == 1) + { + var value = buffer[sourceIndex] << 16; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = buffer[sourceIndex] << 16 | buffer[sourceIndex + 1] << 8; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + buffer[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + } + while (sourceIndex > 0) + { + sourceIndex -= 3; + destinationIndex -= 4; + var value = buffer[sourceIndex] << 16 | buffer[sourceIndex + 1] << 8 | buffer[sourceIndex + 2]; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + buffer[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + buffer[destinationIndex + 3] = (byte) map[value & 0x3F]; + } + bytesWritten = encodedLength; return true; } /// Decodes the span of UTF-16 encoded text represented as base-64-url into binary data. @@ -322,24 +282,96 @@ public static bool IsValid(ReadOnlySpan utf8Base64UrlText, out int decoded var chars = BytesToChars(utf8Base64UrlText); return IsValid(chars, out decodedLength); } - static string ToBase64UrlString(string base64) + const string encodeMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + static int EncodedLength(int bytesLength) => + checked((int) (((long) bytesLength * 4 + 2) / 3)); + static OperationStatus PlanEncode(int sourceLength, int destinationLength, bool isFinalBlock, out int bytesConsumed, out int written) { - var len = base64.Length; - while (len > 0 && base64[len - 1] == '=') + if (isFinalBlock) { - len--; + var total = EncodedLength(sourceLength); + if (total <= destinationLength) + { + bytesConsumed = sourceLength; + written = total; + return OperationStatus.Done; + } } - var chars = new char[len]; - for (var i = 0; i < len; i++) + var completeGroups = sourceLength / 3; + var groups = Math.Min(completeGroups, destinationLength / 4); + bytesConsumed = groups * 3; + written = groups * 4; + if (isFinalBlock || groups < completeGroups) { - chars[i] = base64[i] switch - { - '+' => '-', - '/' => '_', - _ => base64[i] - }; + return OperationStatus.DestinationTooSmall; + } + if (sourceLength % 3 > 0) + { + return OperationStatus.NeedMoreData; + } + return OperationStatus.Done; + } + static void Encode(ReadOnlySpan source, Span destination) + { + var map = encodeMap; + var sourceIndex = 0; + var destinationIndex = 0; + var end = source.Length - 2; + while (sourceIndex < end) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8 | source[sourceIndex + 2]; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = map[value >> 6 & 0x3F]; + destination[destinationIndex + 3] = map[value & 0x3F]; + sourceIndex += 3; + destinationIndex += 4; + } + var remaining = source.Length - sourceIndex; + if (remaining == 1) + { + var value = source[sourceIndex] << 16; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = map[value >> 6 & 0x3F]; + } + } + static void Encode(ReadOnlySpan source, Span destination) + { + var map = encodeMap; + var sourceIndex = 0; + var destinationIndex = 0; + var end = source.Length - 2; + while (sourceIndex < end) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8 | source[sourceIndex + 2]; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + destination[destinationIndex + 3] = (byte) map[value & 0x3F]; + sourceIndex += 3; + destinationIndex += 4; + } + var remaining = source.Length - sourceIndex; + if (remaining == 1) + { + var value = source[sourceIndex] << 16; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; } - return new string(chars); } static OperationStatus Decode(ReadOnlySpan source, Span destination, bool write, out int charsConsumed, out int bytesWritten, bool isFinalBlock) { @@ -478,13 +510,6 @@ static int DecodeValue(char c) } return -1; } - static void WriteStringToBytes(string source, Span destination) - { - for (var i = 0; i < source.Length; i++) - { - destination[i] = (byte)source[i]; - } - } static char[] BytesToChars(ReadOnlySpan source) { var chars = new char[source.Length]; diff --git a/src/Split/netcoreapp3.1/Base64Url.cs b/src/Split/netcoreapp3.1/Base64Url.cs index 817dcd19..88920e01 100644 --- a/src/Split/netcoreapp3.1/Base64Url.cs +++ b/src/Split/netcoreapp3.1/Base64Url.cs @@ -42,152 +42,87 @@ public static string EncodeToString(ReadOnlySpan source) { return string.Empty; } - var base64 = Convert.ToBase64String(source.ToArray()); - return ToBase64UrlString(base64); + var length = EncodedLength(source.Length); + if (length <= 256) + { + Span buffer = stackalloc char[256]; + buffer = buffer.Slice(0, length); + Encode(source, buffer); + return buffer.ToString(); + } + var rented = ArrayPool.Shared.Rent(length); + Encode(source, rented); + var result = new string(rented, 0, length); + ArrayPool.Shared.Return(rented); + return result; } /// Encodes the span of binary data into UTF-16 encoded text represented as base-64-url. public static int EncodeToChars(ReadOnlySpan source, Span destination) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { throw new ArgumentException("Destination is too small.", nameof(destination)); } - encoded.AsSpan().CopyTo(destination); - return encoded.Length; + Encode(source, destination); + return length; } /// Encodes the span of binary data into UTF-16 encoded text represented as base-64-url. public static OperationStatus EncodeToChars(ReadOnlySpan source, Span destination, out int bytesConsumed, out int charsWritten, bool isFinalBlock = true) { - if (source.IsEmpty) - { - charsWritten = 0; - bytesConsumed = 0; - return OperationStatus.Done; - } - var completeGroups = source.Length / 3; - var remainingBytes = source.Length % 3; - if (!isFinalBlock) - { - var groupsWeCanFit = Math.Min(completeGroups, destination.Length / 4); - bytesConsumed = groupsWeCanFit * 3; - charsWritten = groupsWeCanFit * 4; - if (bytesConsumed > 0) - { - EncodeToString(source.Slice(0, bytesConsumed)).AsSpan().CopyTo(destination); - } - if (groupsWeCanFit < completeGroups) - { - return OperationStatus.DestinationTooSmall; - } - return remainingBytes > 0 ? OperationStatus.NeedMoreData : OperationStatus.Done; - } - var totalChars = GetEncodedLength(source.Length); - if (totalChars <= destination.Length) - { - EncodeToString(source).AsSpan().CopyTo(destination); - charsWritten = totalChars; - bytesConsumed = source.Length; - return OperationStatus.Done; - } - var fitting = destination.Length / 4; - bytesConsumed = fitting * 3; - charsWritten = fitting * 4; - if (bytesConsumed > 0) - { - EncodeToString(source.Slice(0, bytesConsumed)).AsSpan().CopyTo(destination); - } - return OperationStatus.DestinationTooSmall; + var status = PlanEncode(source.Length, destination.Length, isFinalBlock, out bytesConsumed, out charsWritten); + Encode(source.Slice(0, bytesConsumed), destination); + return status; } /// Tries to encode the span of binary data into UTF-16 encoded text represented as base-64-url. public static bool TryEncodeToChars(ReadOnlySpan source, Span destination, out int charsWritten) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { charsWritten = 0; return false; } - encoded.AsSpan().CopyTo(destination); - charsWritten = encoded.Length; + Encode(source, destination); + charsWritten = length; return true; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static byte[] EncodeToUtf8(ReadOnlySpan source) { - var chars = EncodeToString(source); - var result = new byte[chars.Length]; - for (var i = 0; i < chars.Length; i++) - { - result[i] = (byte)chars[i]; - } + var result = new byte[EncodedLength(source.Length)]; + Encode(source, result); return result; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static int EncodeToUtf8(ReadOnlySpan source, Span destination) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { throw new ArgumentException("Destination is too small.", nameof(destination)); } - WriteStringToBytes(encoded, destination); - return encoded.Length; + Encode(source, destination); + return length; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static OperationStatus EncodeToUtf8(ReadOnlySpan source, Span destination, out int bytesConsumed, out int bytesWritten, bool isFinalBlock = true) { - if (source.IsEmpty) - { - bytesWritten = 0; - bytesConsumed = 0; - return OperationStatus.Done; - } - var completeGroups = source.Length / 3; - var remainingBytes = source.Length % 3; - if (!isFinalBlock) - { - var groupsWeCanFit = Math.Min(completeGroups, destination.Length / 4); - bytesConsumed = groupsWeCanFit * 3; - bytesWritten = groupsWeCanFit * 4; - if (bytesConsumed > 0) - { - WriteStringToBytes(EncodeToString(source.Slice(0, bytesConsumed)), destination); - } - if (groupsWeCanFit < completeGroups) - { - return OperationStatus.DestinationTooSmall; - } - return remainingBytes > 0 ? OperationStatus.NeedMoreData : OperationStatus.Done; - } - var totalBytes = GetEncodedLength(source.Length); - if (totalBytes <= destination.Length) - { - WriteStringToBytes(EncodeToString(source), destination); - bytesWritten = totalBytes; - bytesConsumed = source.Length; - return OperationStatus.Done; - } - var fitting = destination.Length / 4; - bytesConsumed = fitting * 3; - bytesWritten = fitting * 4; - if (bytesConsumed > 0) - { - WriteStringToBytes(EncodeToString(source.Slice(0, bytesConsumed)), destination); - } - return OperationStatus.DestinationTooSmall; + var status = PlanEncode(source.Length, destination.Length, isFinalBlock, out bytesConsumed, out bytesWritten); + Encode(source.Slice(0, bytesConsumed), destination); + return status; } /// Tries to encode the span of binary data into UTF-8 encoded text represented as base-64-url. public static bool TryEncodeToUtf8(ReadOnlySpan source, Span destination, out int bytesWritten) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { bytesWritten = 0; return false; } - WriteStringToBytes(encoded, destination); - bytesWritten = encoded.Length; + Encode(source, destination); + bytesWritten = length; return true; } /// Encodes the span of binary data (in-place) into UTF-8 encoded text represented as base-64-url. @@ -197,16 +132,41 @@ public static bool TryEncodeToUtf8InPlace(Span buffer, int dataLength, out { throw new ArgumentOutOfRangeException(nameof(dataLength)); } - var encodedLength = GetEncodedLength(dataLength); + var encodedLength = EncodedLength(dataLength); if (encodedLength > buffer.Length) { bytesWritten = 0; return false; } - var source = buffer.Slice(0, dataLength).ToArray(); - var encoded = EncodeToString(source); - WriteStringToBytes(encoded, buffer); - bytesWritten = encoded.Length; + var map = encodeMap; + var groups = dataLength / 3; + var sourceIndex = groups * 3; + var destinationIndex = groups * 4; + var remaining = dataLength - sourceIndex; + if (remaining == 1) + { + var value = buffer[sourceIndex] << 16; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = buffer[sourceIndex] << 16 | buffer[sourceIndex + 1] << 8; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + buffer[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + } + while (sourceIndex > 0) + { + sourceIndex -= 3; + destinationIndex -= 4; + var value = buffer[sourceIndex] << 16 | buffer[sourceIndex + 1] << 8 | buffer[sourceIndex + 2]; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + buffer[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + buffer[destinationIndex + 3] = (byte) map[value & 0x3F]; + } + bytesWritten = encodedLength; return true; } /// Decodes the span of UTF-16 encoded text represented as base-64-url into binary data. @@ -322,24 +282,96 @@ public static bool IsValid(ReadOnlySpan utf8Base64UrlText, out int decoded var chars = BytesToChars(utf8Base64UrlText); return IsValid(chars, out decodedLength); } - static string ToBase64UrlString(string base64) + const string encodeMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + static int EncodedLength(int bytesLength) => + checked((int) (((long) bytesLength * 4 + 2) / 3)); + static OperationStatus PlanEncode(int sourceLength, int destinationLength, bool isFinalBlock, out int bytesConsumed, out int written) { - var len = base64.Length; - while (len > 0 && base64[len - 1] == '=') + if (isFinalBlock) { - len--; + var total = EncodedLength(sourceLength); + if (total <= destinationLength) + { + bytesConsumed = sourceLength; + written = total; + return OperationStatus.Done; + } } - var chars = new char[len]; - for (var i = 0; i < len; i++) + var completeGroups = sourceLength / 3; + var groups = Math.Min(completeGroups, destinationLength / 4); + bytesConsumed = groups * 3; + written = groups * 4; + if (isFinalBlock || groups < completeGroups) { - chars[i] = base64[i] switch - { - '+' => '-', - '/' => '_', - _ => base64[i] - }; + return OperationStatus.DestinationTooSmall; + } + if (sourceLength % 3 > 0) + { + return OperationStatus.NeedMoreData; + } + return OperationStatus.Done; + } + static void Encode(ReadOnlySpan source, Span destination) + { + var map = encodeMap; + var sourceIndex = 0; + var destinationIndex = 0; + var end = source.Length - 2; + while (sourceIndex < end) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8 | source[sourceIndex + 2]; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = map[value >> 6 & 0x3F]; + destination[destinationIndex + 3] = map[value & 0x3F]; + sourceIndex += 3; + destinationIndex += 4; + } + var remaining = source.Length - sourceIndex; + if (remaining == 1) + { + var value = source[sourceIndex] << 16; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = map[value >> 6 & 0x3F]; + } + } + static void Encode(ReadOnlySpan source, Span destination) + { + var map = encodeMap; + var sourceIndex = 0; + var destinationIndex = 0; + var end = source.Length - 2; + while (sourceIndex < end) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8 | source[sourceIndex + 2]; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + destination[destinationIndex + 3] = (byte) map[value & 0x3F]; + sourceIndex += 3; + destinationIndex += 4; + } + var remaining = source.Length - sourceIndex; + if (remaining == 1) + { + var value = source[sourceIndex] << 16; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; } - return new string(chars); } static OperationStatus Decode(ReadOnlySpan source, Span destination, bool write, out int charsConsumed, out int bytesWritten, bool isFinalBlock) { @@ -478,13 +510,6 @@ static int DecodeValue(char c) } return -1; } - static void WriteStringToBytes(string source, Span destination) - { - for (var i = 0; i < source.Length; i++) - { - destination[i] = (byte)source[i]; - } - } static char[] BytesToChars(ReadOnlySpan source) { var chars = new char[source.Length]; diff --git a/src/Split/netstandard2.0/Base64Url.cs b/src/Split/netstandard2.0/Base64Url.cs index 817dcd19..88920e01 100644 --- a/src/Split/netstandard2.0/Base64Url.cs +++ b/src/Split/netstandard2.0/Base64Url.cs @@ -42,152 +42,87 @@ public static string EncodeToString(ReadOnlySpan source) { return string.Empty; } - var base64 = Convert.ToBase64String(source.ToArray()); - return ToBase64UrlString(base64); + var length = EncodedLength(source.Length); + if (length <= 256) + { + Span buffer = stackalloc char[256]; + buffer = buffer.Slice(0, length); + Encode(source, buffer); + return buffer.ToString(); + } + var rented = ArrayPool.Shared.Rent(length); + Encode(source, rented); + var result = new string(rented, 0, length); + ArrayPool.Shared.Return(rented); + return result; } /// Encodes the span of binary data into UTF-16 encoded text represented as base-64-url. public static int EncodeToChars(ReadOnlySpan source, Span destination) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { throw new ArgumentException("Destination is too small.", nameof(destination)); } - encoded.AsSpan().CopyTo(destination); - return encoded.Length; + Encode(source, destination); + return length; } /// Encodes the span of binary data into UTF-16 encoded text represented as base-64-url. public static OperationStatus EncodeToChars(ReadOnlySpan source, Span destination, out int bytesConsumed, out int charsWritten, bool isFinalBlock = true) { - if (source.IsEmpty) - { - charsWritten = 0; - bytesConsumed = 0; - return OperationStatus.Done; - } - var completeGroups = source.Length / 3; - var remainingBytes = source.Length % 3; - if (!isFinalBlock) - { - var groupsWeCanFit = Math.Min(completeGroups, destination.Length / 4); - bytesConsumed = groupsWeCanFit * 3; - charsWritten = groupsWeCanFit * 4; - if (bytesConsumed > 0) - { - EncodeToString(source.Slice(0, bytesConsumed)).AsSpan().CopyTo(destination); - } - if (groupsWeCanFit < completeGroups) - { - return OperationStatus.DestinationTooSmall; - } - return remainingBytes > 0 ? OperationStatus.NeedMoreData : OperationStatus.Done; - } - var totalChars = GetEncodedLength(source.Length); - if (totalChars <= destination.Length) - { - EncodeToString(source).AsSpan().CopyTo(destination); - charsWritten = totalChars; - bytesConsumed = source.Length; - return OperationStatus.Done; - } - var fitting = destination.Length / 4; - bytesConsumed = fitting * 3; - charsWritten = fitting * 4; - if (bytesConsumed > 0) - { - EncodeToString(source.Slice(0, bytesConsumed)).AsSpan().CopyTo(destination); - } - return OperationStatus.DestinationTooSmall; + var status = PlanEncode(source.Length, destination.Length, isFinalBlock, out bytesConsumed, out charsWritten); + Encode(source.Slice(0, bytesConsumed), destination); + return status; } /// Tries to encode the span of binary data into UTF-16 encoded text represented as base-64-url. public static bool TryEncodeToChars(ReadOnlySpan source, Span destination, out int charsWritten) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { charsWritten = 0; return false; } - encoded.AsSpan().CopyTo(destination); - charsWritten = encoded.Length; + Encode(source, destination); + charsWritten = length; return true; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static byte[] EncodeToUtf8(ReadOnlySpan source) { - var chars = EncodeToString(source); - var result = new byte[chars.Length]; - for (var i = 0; i < chars.Length; i++) - { - result[i] = (byte)chars[i]; - } + var result = new byte[EncodedLength(source.Length)]; + Encode(source, result); return result; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static int EncodeToUtf8(ReadOnlySpan source, Span destination) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { throw new ArgumentException("Destination is too small.", nameof(destination)); } - WriteStringToBytes(encoded, destination); - return encoded.Length; + Encode(source, destination); + return length; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static OperationStatus EncodeToUtf8(ReadOnlySpan source, Span destination, out int bytesConsumed, out int bytesWritten, bool isFinalBlock = true) { - if (source.IsEmpty) - { - bytesWritten = 0; - bytesConsumed = 0; - return OperationStatus.Done; - } - var completeGroups = source.Length / 3; - var remainingBytes = source.Length % 3; - if (!isFinalBlock) - { - var groupsWeCanFit = Math.Min(completeGroups, destination.Length / 4); - bytesConsumed = groupsWeCanFit * 3; - bytesWritten = groupsWeCanFit * 4; - if (bytesConsumed > 0) - { - WriteStringToBytes(EncodeToString(source.Slice(0, bytesConsumed)), destination); - } - if (groupsWeCanFit < completeGroups) - { - return OperationStatus.DestinationTooSmall; - } - return remainingBytes > 0 ? OperationStatus.NeedMoreData : OperationStatus.Done; - } - var totalBytes = GetEncodedLength(source.Length); - if (totalBytes <= destination.Length) - { - WriteStringToBytes(EncodeToString(source), destination); - bytesWritten = totalBytes; - bytesConsumed = source.Length; - return OperationStatus.Done; - } - var fitting = destination.Length / 4; - bytesConsumed = fitting * 3; - bytesWritten = fitting * 4; - if (bytesConsumed > 0) - { - WriteStringToBytes(EncodeToString(source.Slice(0, bytesConsumed)), destination); - } - return OperationStatus.DestinationTooSmall; + var status = PlanEncode(source.Length, destination.Length, isFinalBlock, out bytesConsumed, out bytesWritten); + Encode(source.Slice(0, bytesConsumed), destination); + return status; } /// Tries to encode the span of binary data into UTF-8 encoded text represented as base-64-url. public static bool TryEncodeToUtf8(ReadOnlySpan source, Span destination, out int bytesWritten) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { bytesWritten = 0; return false; } - WriteStringToBytes(encoded, destination); - bytesWritten = encoded.Length; + Encode(source, destination); + bytesWritten = length; return true; } /// Encodes the span of binary data (in-place) into UTF-8 encoded text represented as base-64-url. @@ -197,16 +132,41 @@ public static bool TryEncodeToUtf8InPlace(Span buffer, int dataLength, out { throw new ArgumentOutOfRangeException(nameof(dataLength)); } - var encodedLength = GetEncodedLength(dataLength); + var encodedLength = EncodedLength(dataLength); if (encodedLength > buffer.Length) { bytesWritten = 0; return false; } - var source = buffer.Slice(0, dataLength).ToArray(); - var encoded = EncodeToString(source); - WriteStringToBytes(encoded, buffer); - bytesWritten = encoded.Length; + var map = encodeMap; + var groups = dataLength / 3; + var sourceIndex = groups * 3; + var destinationIndex = groups * 4; + var remaining = dataLength - sourceIndex; + if (remaining == 1) + { + var value = buffer[sourceIndex] << 16; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = buffer[sourceIndex] << 16 | buffer[sourceIndex + 1] << 8; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + buffer[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + } + while (sourceIndex > 0) + { + sourceIndex -= 3; + destinationIndex -= 4; + var value = buffer[sourceIndex] << 16 | buffer[sourceIndex + 1] << 8 | buffer[sourceIndex + 2]; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + buffer[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + buffer[destinationIndex + 3] = (byte) map[value & 0x3F]; + } + bytesWritten = encodedLength; return true; } /// Decodes the span of UTF-16 encoded text represented as base-64-url into binary data. @@ -322,24 +282,96 @@ public static bool IsValid(ReadOnlySpan utf8Base64UrlText, out int decoded var chars = BytesToChars(utf8Base64UrlText); return IsValid(chars, out decodedLength); } - static string ToBase64UrlString(string base64) + const string encodeMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + static int EncodedLength(int bytesLength) => + checked((int) (((long) bytesLength * 4 + 2) / 3)); + static OperationStatus PlanEncode(int sourceLength, int destinationLength, bool isFinalBlock, out int bytesConsumed, out int written) { - var len = base64.Length; - while (len > 0 && base64[len - 1] == '=') + if (isFinalBlock) { - len--; + var total = EncodedLength(sourceLength); + if (total <= destinationLength) + { + bytesConsumed = sourceLength; + written = total; + return OperationStatus.Done; + } } - var chars = new char[len]; - for (var i = 0; i < len; i++) + var completeGroups = sourceLength / 3; + var groups = Math.Min(completeGroups, destinationLength / 4); + bytesConsumed = groups * 3; + written = groups * 4; + if (isFinalBlock || groups < completeGroups) { - chars[i] = base64[i] switch - { - '+' => '-', - '/' => '_', - _ => base64[i] - }; + return OperationStatus.DestinationTooSmall; + } + if (sourceLength % 3 > 0) + { + return OperationStatus.NeedMoreData; + } + return OperationStatus.Done; + } + static void Encode(ReadOnlySpan source, Span destination) + { + var map = encodeMap; + var sourceIndex = 0; + var destinationIndex = 0; + var end = source.Length - 2; + while (sourceIndex < end) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8 | source[sourceIndex + 2]; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = map[value >> 6 & 0x3F]; + destination[destinationIndex + 3] = map[value & 0x3F]; + sourceIndex += 3; + destinationIndex += 4; + } + var remaining = source.Length - sourceIndex; + if (remaining == 1) + { + var value = source[sourceIndex] << 16; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = map[value >> 6 & 0x3F]; + } + } + static void Encode(ReadOnlySpan source, Span destination) + { + var map = encodeMap; + var sourceIndex = 0; + var destinationIndex = 0; + var end = source.Length - 2; + while (sourceIndex < end) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8 | source[sourceIndex + 2]; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + destination[destinationIndex + 3] = (byte) map[value & 0x3F]; + sourceIndex += 3; + destinationIndex += 4; + } + var remaining = source.Length - sourceIndex; + if (remaining == 1) + { + var value = source[sourceIndex] << 16; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; } - return new string(chars); } static OperationStatus Decode(ReadOnlySpan source, Span destination, bool write, out int charsConsumed, out int bytesWritten, bool isFinalBlock) { @@ -478,13 +510,6 @@ static int DecodeValue(char c) } return -1; } - static void WriteStringToBytes(string source, Span destination) - { - for (var i = 0; i < source.Length; i++) - { - destination[i] = (byte)source[i]; - } - } static char[] BytesToChars(ReadOnlySpan source) { var chars = new char[source.Length]; diff --git a/src/Split/netstandard2.1/Base64Url.cs b/src/Split/netstandard2.1/Base64Url.cs index 817dcd19..88920e01 100644 --- a/src/Split/netstandard2.1/Base64Url.cs +++ b/src/Split/netstandard2.1/Base64Url.cs @@ -42,152 +42,87 @@ public static string EncodeToString(ReadOnlySpan source) { return string.Empty; } - var base64 = Convert.ToBase64String(source.ToArray()); - return ToBase64UrlString(base64); + var length = EncodedLength(source.Length); + if (length <= 256) + { + Span buffer = stackalloc char[256]; + buffer = buffer.Slice(0, length); + Encode(source, buffer); + return buffer.ToString(); + } + var rented = ArrayPool.Shared.Rent(length); + Encode(source, rented); + var result = new string(rented, 0, length); + ArrayPool.Shared.Return(rented); + return result; } /// Encodes the span of binary data into UTF-16 encoded text represented as base-64-url. public static int EncodeToChars(ReadOnlySpan source, Span destination) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { throw new ArgumentException("Destination is too small.", nameof(destination)); } - encoded.AsSpan().CopyTo(destination); - return encoded.Length; + Encode(source, destination); + return length; } /// Encodes the span of binary data into UTF-16 encoded text represented as base-64-url. public static OperationStatus EncodeToChars(ReadOnlySpan source, Span destination, out int bytesConsumed, out int charsWritten, bool isFinalBlock = true) { - if (source.IsEmpty) - { - charsWritten = 0; - bytesConsumed = 0; - return OperationStatus.Done; - } - var completeGroups = source.Length / 3; - var remainingBytes = source.Length % 3; - if (!isFinalBlock) - { - var groupsWeCanFit = Math.Min(completeGroups, destination.Length / 4); - bytesConsumed = groupsWeCanFit * 3; - charsWritten = groupsWeCanFit * 4; - if (bytesConsumed > 0) - { - EncodeToString(source.Slice(0, bytesConsumed)).AsSpan().CopyTo(destination); - } - if (groupsWeCanFit < completeGroups) - { - return OperationStatus.DestinationTooSmall; - } - return remainingBytes > 0 ? OperationStatus.NeedMoreData : OperationStatus.Done; - } - var totalChars = GetEncodedLength(source.Length); - if (totalChars <= destination.Length) - { - EncodeToString(source).AsSpan().CopyTo(destination); - charsWritten = totalChars; - bytesConsumed = source.Length; - return OperationStatus.Done; - } - var fitting = destination.Length / 4; - bytesConsumed = fitting * 3; - charsWritten = fitting * 4; - if (bytesConsumed > 0) - { - EncodeToString(source.Slice(0, bytesConsumed)).AsSpan().CopyTo(destination); - } - return OperationStatus.DestinationTooSmall; + var status = PlanEncode(source.Length, destination.Length, isFinalBlock, out bytesConsumed, out charsWritten); + Encode(source.Slice(0, bytesConsumed), destination); + return status; } /// Tries to encode the span of binary data into UTF-16 encoded text represented as base-64-url. public static bool TryEncodeToChars(ReadOnlySpan source, Span destination, out int charsWritten) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { charsWritten = 0; return false; } - encoded.AsSpan().CopyTo(destination); - charsWritten = encoded.Length; + Encode(source, destination); + charsWritten = length; return true; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static byte[] EncodeToUtf8(ReadOnlySpan source) { - var chars = EncodeToString(source); - var result = new byte[chars.Length]; - for (var i = 0; i < chars.Length; i++) - { - result[i] = (byte)chars[i]; - } + var result = new byte[EncodedLength(source.Length)]; + Encode(source, result); return result; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static int EncodeToUtf8(ReadOnlySpan source, Span destination) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { throw new ArgumentException("Destination is too small.", nameof(destination)); } - WriteStringToBytes(encoded, destination); - return encoded.Length; + Encode(source, destination); + return length; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static OperationStatus EncodeToUtf8(ReadOnlySpan source, Span destination, out int bytesConsumed, out int bytesWritten, bool isFinalBlock = true) { - if (source.IsEmpty) - { - bytesWritten = 0; - bytesConsumed = 0; - return OperationStatus.Done; - } - var completeGroups = source.Length / 3; - var remainingBytes = source.Length % 3; - if (!isFinalBlock) - { - var groupsWeCanFit = Math.Min(completeGroups, destination.Length / 4); - bytesConsumed = groupsWeCanFit * 3; - bytesWritten = groupsWeCanFit * 4; - if (bytesConsumed > 0) - { - WriteStringToBytes(EncodeToString(source.Slice(0, bytesConsumed)), destination); - } - if (groupsWeCanFit < completeGroups) - { - return OperationStatus.DestinationTooSmall; - } - return remainingBytes > 0 ? OperationStatus.NeedMoreData : OperationStatus.Done; - } - var totalBytes = GetEncodedLength(source.Length); - if (totalBytes <= destination.Length) - { - WriteStringToBytes(EncodeToString(source), destination); - bytesWritten = totalBytes; - bytesConsumed = source.Length; - return OperationStatus.Done; - } - var fitting = destination.Length / 4; - bytesConsumed = fitting * 3; - bytesWritten = fitting * 4; - if (bytesConsumed > 0) - { - WriteStringToBytes(EncodeToString(source.Slice(0, bytesConsumed)), destination); - } - return OperationStatus.DestinationTooSmall; + var status = PlanEncode(source.Length, destination.Length, isFinalBlock, out bytesConsumed, out bytesWritten); + Encode(source.Slice(0, bytesConsumed), destination); + return status; } /// Tries to encode the span of binary data into UTF-8 encoded text represented as base-64-url. public static bool TryEncodeToUtf8(ReadOnlySpan source, Span destination, out int bytesWritten) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { bytesWritten = 0; return false; } - WriteStringToBytes(encoded, destination); - bytesWritten = encoded.Length; + Encode(source, destination); + bytesWritten = length; return true; } /// Encodes the span of binary data (in-place) into UTF-8 encoded text represented as base-64-url. @@ -197,16 +132,41 @@ public static bool TryEncodeToUtf8InPlace(Span buffer, int dataLength, out { throw new ArgumentOutOfRangeException(nameof(dataLength)); } - var encodedLength = GetEncodedLength(dataLength); + var encodedLength = EncodedLength(dataLength); if (encodedLength > buffer.Length) { bytesWritten = 0; return false; } - var source = buffer.Slice(0, dataLength).ToArray(); - var encoded = EncodeToString(source); - WriteStringToBytes(encoded, buffer); - bytesWritten = encoded.Length; + var map = encodeMap; + var groups = dataLength / 3; + var sourceIndex = groups * 3; + var destinationIndex = groups * 4; + var remaining = dataLength - sourceIndex; + if (remaining == 1) + { + var value = buffer[sourceIndex] << 16; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = buffer[sourceIndex] << 16 | buffer[sourceIndex + 1] << 8; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + buffer[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + } + while (sourceIndex > 0) + { + sourceIndex -= 3; + destinationIndex -= 4; + var value = buffer[sourceIndex] << 16 | buffer[sourceIndex + 1] << 8 | buffer[sourceIndex + 2]; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + buffer[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + buffer[destinationIndex + 3] = (byte) map[value & 0x3F]; + } + bytesWritten = encodedLength; return true; } /// Decodes the span of UTF-16 encoded text represented as base-64-url into binary data. @@ -322,24 +282,96 @@ public static bool IsValid(ReadOnlySpan utf8Base64UrlText, out int decoded var chars = BytesToChars(utf8Base64UrlText); return IsValid(chars, out decodedLength); } - static string ToBase64UrlString(string base64) + const string encodeMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + static int EncodedLength(int bytesLength) => + checked((int) (((long) bytesLength * 4 + 2) / 3)); + static OperationStatus PlanEncode(int sourceLength, int destinationLength, bool isFinalBlock, out int bytesConsumed, out int written) { - var len = base64.Length; - while (len > 0 && base64[len - 1] == '=') + if (isFinalBlock) { - len--; + var total = EncodedLength(sourceLength); + if (total <= destinationLength) + { + bytesConsumed = sourceLength; + written = total; + return OperationStatus.Done; + } } - var chars = new char[len]; - for (var i = 0; i < len; i++) + var completeGroups = sourceLength / 3; + var groups = Math.Min(completeGroups, destinationLength / 4); + bytesConsumed = groups * 3; + written = groups * 4; + if (isFinalBlock || groups < completeGroups) { - chars[i] = base64[i] switch - { - '+' => '-', - '/' => '_', - _ => base64[i] - }; + return OperationStatus.DestinationTooSmall; + } + if (sourceLength % 3 > 0) + { + return OperationStatus.NeedMoreData; + } + return OperationStatus.Done; + } + static void Encode(ReadOnlySpan source, Span destination) + { + var map = encodeMap; + var sourceIndex = 0; + var destinationIndex = 0; + var end = source.Length - 2; + while (sourceIndex < end) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8 | source[sourceIndex + 2]; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = map[value >> 6 & 0x3F]; + destination[destinationIndex + 3] = map[value & 0x3F]; + sourceIndex += 3; + destinationIndex += 4; + } + var remaining = source.Length - sourceIndex; + if (remaining == 1) + { + var value = source[sourceIndex] << 16; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = map[value >> 6 & 0x3F]; + } + } + static void Encode(ReadOnlySpan source, Span destination) + { + var map = encodeMap; + var sourceIndex = 0; + var destinationIndex = 0; + var end = source.Length - 2; + while (sourceIndex < end) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8 | source[sourceIndex + 2]; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + destination[destinationIndex + 3] = (byte) map[value & 0x3F]; + sourceIndex += 3; + destinationIndex += 4; + } + var remaining = source.Length - sourceIndex; + if (remaining == 1) + { + var value = source[sourceIndex] << 16; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; } - return new string(chars); } static OperationStatus Decode(ReadOnlySpan source, Span destination, bool write, out int charsConsumed, out int bytesWritten, bool isFinalBlock) { @@ -478,13 +510,6 @@ static int DecodeValue(char c) } return -1; } - static void WriteStringToBytes(string source, Span destination) - { - for (var i = 0; i < source.Length; i++) - { - destination[i] = (byte)source[i]; - } - } static char[] BytesToChars(ReadOnlySpan source) { var chars = new char[source.Length]; diff --git a/src/Split/uap10.0/Base64Url.cs b/src/Split/uap10.0/Base64Url.cs index 817dcd19..88920e01 100644 --- a/src/Split/uap10.0/Base64Url.cs +++ b/src/Split/uap10.0/Base64Url.cs @@ -42,152 +42,87 @@ public static string EncodeToString(ReadOnlySpan source) { return string.Empty; } - var base64 = Convert.ToBase64String(source.ToArray()); - return ToBase64UrlString(base64); + var length = EncodedLength(source.Length); + if (length <= 256) + { + Span buffer = stackalloc char[256]; + buffer = buffer.Slice(0, length); + Encode(source, buffer); + return buffer.ToString(); + } + var rented = ArrayPool.Shared.Rent(length); + Encode(source, rented); + var result = new string(rented, 0, length); + ArrayPool.Shared.Return(rented); + return result; } /// Encodes the span of binary data into UTF-16 encoded text represented as base-64-url. public static int EncodeToChars(ReadOnlySpan source, Span destination) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { throw new ArgumentException("Destination is too small.", nameof(destination)); } - encoded.AsSpan().CopyTo(destination); - return encoded.Length; + Encode(source, destination); + return length; } /// Encodes the span of binary data into UTF-16 encoded text represented as base-64-url. public static OperationStatus EncodeToChars(ReadOnlySpan source, Span destination, out int bytesConsumed, out int charsWritten, bool isFinalBlock = true) { - if (source.IsEmpty) - { - charsWritten = 0; - bytesConsumed = 0; - return OperationStatus.Done; - } - var completeGroups = source.Length / 3; - var remainingBytes = source.Length % 3; - if (!isFinalBlock) - { - var groupsWeCanFit = Math.Min(completeGroups, destination.Length / 4); - bytesConsumed = groupsWeCanFit * 3; - charsWritten = groupsWeCanFit * 4; - if (bytesConsumed > 0) - { - EncodeToString(source.Slice(0, bytesConsumed)).AsSpan().CopyTo(destination); - } - if (groupsWeCanFit < completeGroups) - { - return OperationStatus.DestinationTooSmall; - } - return remainingBytes > 0 ? OperationStatus.NeedMoreData : OperationStatus.Done; - } - var totalChars = GetEncodedLength(source.Length); - if (totalChars <= destination.Length) - { - EncodeToString(source).AsSpan().CopyTo(destination); - charsWritten = totalChars; - bytesConsumed = source.Length; - return OperationStatus.Done; - } - var fitting = destination.Length / 4; - bytesConsumed = fitting * 3; - charsWritten = fitting * 4; - if (bytesConsumed > 0) - { - EncodeToString(source.Slice(0, bytesConsumed)).AsSpan().CopyTo(destination); - } - return OperationStatus.DestinationTooSmall; + var status = PlanEncode(source.Length, destination.Length, isFinalBlock, out bytesConsumed, out charsWritten); + Encode(source.Slice(0, bytesConsumed), destination); + return status; } /// Tries to encode the span of binary data into UTF-16 encoded text represented as base-64-url. public static bool TryEncodeToChars(ReadOnlySpan source, Span destination, out int charsWritten) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { charsWritten = 0; return false; } - encoded.AsSpan().CopyTo(destination); - charsWritten = encoded.Length; + Encode(source, destination); + charsWritten = length; return true; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static byte[] EncodeToUtf8(ReadOnlySpan source) { - var chars = EncodeToString(source); - var result = new byte[chars.Length]; - for (var i = 0; i < chars.Length; i++) - { - result[i] = (byte)chars[i]; - } + var result = new byte[EncodedLength(source.Length)]; + Encode(source, result); return result; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static int EncodeToUtf8(ReadOnlySpan source, Span destination) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { throw new ArgumentException("Destination is too small.", nameof(destination)); } - WriteStringToBytes(encoded, destination); - return encoded.Length; + Encode(source, destination); + return length; } /// Encodes the span of binary data into UTF-8 encoded text represented as base-64-url. public static OperationStatus EncodeToUtf8(ReadOnlySpan source, Span destination, out int bytesConsumed, out int bytesWritten, bool isFinalBlock = true) { - if (source.IsEmpty) - { - bytesWritten = 0; - bytesConsumed = 0; - return OperationStatus.Done; - } - var completeGroups = source.Length / 3; - var remainingBytes = source.Length % 3; - if (!isFinalBlock) - { - var groupsWeCanFit = Math.Min(completeGroups, destination.Length / 4); - bytesConsumed = groupsWeCanFit * 3; - bytesWritten = groupsWeCanFit * 4; - if (bytesConsumed > 0) - { - WriteStringToBytes(EncodeToString(source.Slice(0, bytesConsumed)), destination); - } - if (groupsWeCanFit < completeGroups) - { - return OperationStatus.DestinationTooSmall; - } - return remainingBytes > 0 ? OperationStatus.NeedMoreData : OperationStatus.Done; - } - var totalBytes = GetEncodedLength(source.Length); - if (totalBytes <= destination.Length) - { - WriteStringToBytes(EncodeToString(source), destination); - bytesWritten = totalBytes; - bytesConsumed = source.Length; - return OperationStatus.Done; - } - var fitting = destination.Length / 4; - bytesConsumed = fitting * 3; - bytesWritten = fitting * 4; - if (bytesConsumed > 0) - { - WriteStringToBytes(EncodeToString(source.Slice(0, bytesConsumed)), destination); - } - return OperationStatus.DestinationTooSmall; + var status = PlanEncode(source.Length, destination.Length, isFinalBlock, out bytesConsumed, out bytesWritten); + Encode(source.Slice(0, bytesConsumed), destination); + return status; } /// Tries to encode the span of binary data into UTF-8 encoded text represented as base-64-url. public static bool TryEncodeToUtf8(ReadOnlySpan source, Span destination, out int bytesWritten) { - var encoded = EncodeToString(source); - if (encoded.Length > destination.Length) + var length = EncodedLength(source.Length); + if (length > destination.Length) { bytesWritten = 0; return false; } - WriteStringToBytes(encoded, destination); - bytesWritten = encoded.Length; + Encode(source, destination); + bytesWritten = length; return true; } /// Encodes the span of binary data (in-place) into UTF-8 encoded text represented as base-64-url. @@ -197,16 +132,41 @@ public static bool TryEncodeToUtf8InPlace(Span buffer, int dataLength, out { throw new ArgumentOutOfRangeException(nameof(dataLength)); } - var encodedLength = GetEncodedLength(dataLength); + var encodedLength = EncodedLength(dataLength); if (encodedLength > buffer.Length) { bytesWritten = 0; return false; } - var source = buffer.Slice(0, dataLength).ToArray(); - var encoded = EncodeToString(source); - WriteStringToBytes(encoded, buffer); - bytesWritten = encoded.Length; + var map = encodeMap; + var groups = dataLength / 3; + var sourceIndex = groups * 3; + var destinationIndex = groups * 4; + var remaining = dataLength - sourceIndex; + if (remaining == 1) + { + var value = buffer[sourceIndex] << 16; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = buffer[sourceIndex] << 16 | buffer[sourceIndex + 1] << 8; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + buffer[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + } + while (sourceIndex > 0) + { + sourceIndex -= 3; + destinationIndex -= 4; + var value = buffer[sourceIndex] << 16 | buffer[sourceIndex + 1] << 8 | buffer[sourceIndex + 2]; + buffer[destinationIndex] = (byte) map[value >> 18]; + buffer[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + buffer[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + buffer[destinationIndex + 3] = (byte) map[value & 0x3F]; + } + bytesWritten = encodedLength; return true; } /// Decodes the span of UTF-16 encoded text represented as base-64-url into binary data. @@ -322,24 +282,96 @@ public static bool IsValid(ReadOnlySpan utf8Base64UrlText, out int decoded var chars = BytesToChars(utf8Base64UrlText); return IsValid(chars, out decodedLength); } - static string ToBase64UrlString(string base64) + const string encodeMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + static int EncodedLength(int bytesLength) => + checked((int) (((long) bytesLength * 4 + 2) / 3)); + static OperationStatus PlanEncode(int sourceLength, int destinationLength, bool isFinalBlock, out int bytesConsumed, out int written) { - var len = base64.Length; - while (len > 0 && base64[len - 1] == '=') + if (isFinalBlock) { - len--; + var total = EncodedLength(sourceLength); + if (total <= destinationLength) + { + bytesConsumed = sourceLength; + written = total; + return OperationStatus.Done; + } } - var chars = new char[len]; - for (var i = 0; i < len; i++) + var completeGroups = sourceLength / 3; + var groups = Math.Min(completeGroups, destinationLength / 4); + bytesConsumed = groups * 3; + written = groups * 4; + if (isFinalBlock || groups < completeGroups) { - chars[i] = base64[i] switch - { - '+' => '-', - '/' => '_', - _ => base64[i] - }; + return OperationStatus.DestinationTooSmall; + } + if (sourceLength % 3 > 0) + { + return OperationStatus.NeedMoreData; + } + return OperationStatus.Done; + } + static void Encode(ReadOnlySpan source, Span destination) + { + var map = encodeMap; + var sourceIndex = 0; + var destinationIndex = 0; + var end = source.Length - 2; + while (sourceIndex < end) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8 | source[sourceIndex + 2]; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = map[value >> 6 & 0x3F]; + destination[destinationIndex + 3] = map[value & 0x3F]; + sourceIndex += 3; + destinationIndex += 4; + } + var remaining = source.Length - sourceIndex; + if (remaining == 1) + { + var value = source[sourceIndex] << 16; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8; + destination[destinationIndex] = map[value >> 18]; + destination[destinationIndex + 1] = map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = map[value >> 6 & 0x3F]; + } + } + static void Encode(ReadOnlySpan source, Span destination) + { + var map = encodeMap; + var sourceIndex = 0; + var destinationIndex = 0; + var end = source.Length - 2; + while (sourceIndex < end) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8 | source[sourceIndex + 2]; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; + destination[destinationIndex + 3] = (byte) map[value & 0x3F]; + sourceIndex += 3; + destinationIndex += 4; + } + var remaining = source.Length - sourceIndex; + if (remaining == 1) + { + var value = source[sourceIndex] << 16; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + } + else if (remaining == 2) + { + var value = source[sourceIndex] << 16 | source[sourceIndex + 1] << 8; + destination[destinationIndex] = (byte) map[value >> 18]; + destination[destinationIndex + 1] = (byte) map[value >> 12 & 0x3F]; + destination[destinationIndex + 2] = (byte) map[value >> 6 & 0x3F]; } - return new string(chars); } static OperationStatus Decode(ReadOnlySpan source, Span destination, bool write, out int charsConsumed, out int bytesWritten, bool isFinalBlock) { @@ -478,13 +510,6 @@ static int DecodeValue(char c) } return -1; } - static void WriteStringToBytes(string source, Span destination) - { - for (var i = 0; i < source.Length; i++) - { - destination[i] = (byte)source[i]; - } - } static char[] BytesToChars(ReadOnlySpan source) { var chars = new char[source.Length]; diff --git a/src/Tests/Base64UrlTests.cs b/src/Tests/Base64UrlTests.cs index 736d3403..800c0135 100644 --- a/src/Tests/Base64UrlTests.cs +++ b/src/Tests/Base64UrlTests.cs @@ -2,6 +2,8 @@ using System.Buffers; using System.Buffers.Text; +using System.Collections.Generic; +using System.Linq; using System.Text; public class Base64UrlTests @@ -409,6 +411,206 @@ public async Task DecodeFromUtf8_OperationStatus_Done() await Assert.That(bytesWritten).IsEqualTo(3); await Assert.That(destination.AsSpan(0, 3).ToArray()).IsEquivalentTo(new byte[] {1, 2, 3}); } + + static string ReferenceEncode(byte[] bytes) => + Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_'); + + static byte[] PatternBytes(int length) + { + var bytes = new byte[length]; + + for (var i = 0; i < length; i++) + { + bytes[i] = unchecked((byte) (i * 37 + 11)); + } + + return bytes; + } + + [Test] + public async Task Encode_Alphabet() + { + const string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + var source = Convert.FromBase64String(alphabet.Replace('-', '+').Replace('_', '/')); + + await Assert.That(Base64Url.EncodeToString(source)).IsEqualTo(alphabet); + await Assert.That(Encoding.ASCII.GetString(Base64Url.EncodeToUtf8(source))).IsEqualTo(alphabet); + } + + [Test] + public async Task Encode_AllOverloads_MatchReference() + { + var failures = new List(); + + // 0 to 300 covers every remainder, and both the stack and the pooled path of EncodeToString + for (var length = 0; length <= 300; length++) + { + var source = PatternBytes(length); + var expected = ReferenceEncode(source); + var expectedUtf8 = Encoding.ASCII.GetBytes(expected); + + void Check(string name, bool condition) + { + if (!condition) + { + failures.Add($"{name} length {length}"); + } + } + + Check("GetEncodedLength", Base64Url.GetEncodedLength(length) == expected.Length); + Check("EncodeToString", Base64Url.EncodeToString(source) == expected); + Check("EncodeToUtf8", Base64Url.EncodeToUtf8(source).SequenceEqual(expectedUtf8)); + + // one spare element, to check nothing is written past the end + var chars = new char[expected.Length + 1]; + chars[expected.Length] = '!'; + var written = Base64Url.EncodeToChars(source, chars); + Check("EncodeToChars", written == expected.Length && new string(chars) == expected + "!"); + + chars = new char[expected.Length + 1]; + chars[expected.Length] = '!'; + var success = Base64Url.TryEncodeToChars(source, chars, out written); + Check("TryEncodeToChars", success && written == expected.Length && new string(chars) == expected + "!"); + + chars = new char[expected.Length + 1]; + chars[expected.Length] = '!'; + var status = Base64Url.EncodeToChars(source, chars, out var consumed, out written); + Check("EncodeToChars status", status == OperationStatus.Done && consumed == length && written == expected.Length && new string(chars) == expected + "!"); + + var bytes = new byte[expected.Length + 1]; + bytes[expected.Length] = 0xEE; + written = Base64Url.EncodeToUtf8(source, bytes); + Check("EncodeToUtf8 destination", written == expected.Length && bytes.AsSpan(0, written).SequenceEqual(expectedUtf8) && bytes[expected.Length] == 0xEE); + + bytes = new byte[expected.Length + 1]; + bytes[expected.Length] = 0xEE; + success = Base64Url.TryEncodeToUtf8(source, bytes, out written); + Check("TryEncodeToUtf8", success && written == expected.Length && bytes.AsSpan(0, written).SequenceEqual(expectedUtf8) && bytes[expected.Length] == 0xEE); + + bytes = new byte[expected.Length + 1]; + bytes[expected.Length] = 0xEE; + status = Base64Url.EncodeToUtf8(source, bytes, out consumed, out written); + Check("EncodeToUtf8 status", status == OperationStatus.Done && consumed == length && written == expected.Length && bytes.AsSpan(0, written).SequenceEqual(expectedUtf8) && bytes[expected.Length] == 0xEE); + + bytes = new byte[expected.Length + 1]; + bytes[expected.Length] = 0xEE; + source.CopyTo(bytes, 0); + success = Base64Url.TryEncodeToUtf8InPlace(bytes, length, out written); + Check("TryEncodeToUtf8InPlace", success && written == expected.Length && bytes.AsSpan(0, written).SequenceEqual(expectedUtf8) && bytes[expected.Length] == 0xEE); + + if (length > 0) + { + Check("TryEncodeToChars too small", !Base64Url.TryEncodeToChars(source, new char[expected.Length - 1], out _)); + Check("TryEncodeToUtf8 too small", !Base64Url.TryEncodeToUtf8(source, new byte[expected.Length - 1], out _)); + } + } + + await Assert.That(failures).IsEmpty(); + } + + [Test] + public async Task EncodeToString_Large() + { + var source = PatternBytes(100_000); + await Assert.That(Base64Url.EncodeToString(source)).IsEqualTo(ReferenceEncode(source)); + } + + [Test] + public async Task Encode_DestinationTooSmall_Throws() + { + var source = PatternBytes(10); + await Assert.That(() => Base64Url.EncodeToChars(source, new char[13])).Throws(); + await Assert.That(() => Base64Url.EncodeToUtf8(source, new byte[13])).Throws(); + } + + [Test] + public async Task TryEncodeToUtf8InPlace_TooSmall() + { + var buffer = PatternBytes(10); + var success = Base64Url.TryEncodeToUtf8InPlace(buffer, 10, out var written); + await Assert.That(success).IsFalse(); + await Assert.That(written).IsEqualTo(0); + await Assert.That(buffer).IsEquivalentTo(PatternBytes(10)); + } + + [Test] + public async Task EncodeToChars_OperationStatus_Blocks() + { + var source = PatternBytes(10); + var expected = ReferenceEncode(source); + + // final block that does not fit: only the complete groups that fit are written + var destination = new char[9]; + var status = Base64Url.EncodeToChars(source, destination, out var consumed, out var written); + var text = new string(destination, 0, written); + await Assert.That(status).IsEqualTo(OperationStatus.DestinationTooSmall); + await Assert.That(consumed).IsEqualTo(6); + await Assert.That(written).IsEqualTo(8); + await Assert.That(text).IsEqualTo(expected.Substring(0, 8)); + await Assert.That(destination[8]).IsEqualTo('\0'); + + // the trailing partial group is left for the next block + destination = new char[20]; + status = Base64Url.EncodeToChars(source, destination, out consumed, out written, isFinalBlock: false); + text = new string(destination, 0, written); + await Assert.That(status).IsEqualTo(OperationStatus.NeedMoreData); + await Assert.That(consumed).IsEqualTo(9); + await Assert.That(written).IsEqualTo(12); + await Assert.That(text).IsEqualTo(expected.Substring(0, 12)); + + destination = new char[7]; + status = Base64Url.EncodeToChars(source, destination, out consumed, out written, isFinalBlock: false); + text = new string(destination, 0, written); + await Assert.That(status).IsEqualTo(OperationStatus.DestinationTooSmall); + await Assert.That(consumed).IsEqualTo(3); + await Assert.That(written).IsEqualTo(4); + await Assert.That(text).IsEqualTo(expected.Substring(0, 4)); + + destination = new char[12]; + status = Base64Url.EncodeToChars(source.AsSpan(0, 9), destination, out consumed, out written, isFinalBlock: false); + text = new string(destination, 0, written); + await Assert.That(status).IsEqualTo(OperationStatus.Done); + await Assert.That(consumed).IsEqualTo(9); + await Assert.That(written).IsEqualTo(12); + await Assert.That(text).IsEqualTo(expected.Substring(0, 12)); + + status = Base64Url.EncodeToChars(ReadOnlySpan.Empty, Span.Empty, out consumed, out written); + await Assert.That(status).IsEqualTo(OperationStatus.Done); + await Assert.That(consumed).IsEqualTo(0); + await Assert.That(written).IsEqualTo(0); + } + + [Test] + public async Task EncodeToUtf8_OperationStatus_Blocks() + { + var source = PatternBytes(10); + var expected = ReferenceEncode(source); + + var destination = new byte[9]; + var status = Base64Url.EncodeToUtf8(source, destination, out var consumed, out var written); + var text = Encoding.ASCII.GetString(destination, 0, written); + await Assert.That(status).IsEqualTo(OperationStatus.DestinationTooSmall); + await Assert.That(consumed).IsEqualTo(6); + await Assert.That(written).IsEqualTo(8); + await Assert.That(text).IsEqualTo(expected.Substring(0, 8)); + await Assert.That(destination[8]).IsEqualTo((byte) 0); + + destination = new byte[20]; + status = Base64Url.EncodeToUtf8(source, destination, out consumed, out written, isFinalBlock: false); + text = Encoding.ASCII.GetString(destination, 0, written); + await Assert.That(status).IsEqualTo(OperationStatus.NeedMoreData); + await Assert.That(consumed).IsEqualTo(9); + await Assert.That(written).IsEqualTo(12); + await Assert.That(text).IsEqualTo(expected.Substring(0, 12)); + + destination = new byte[7]; + status = Base64Url.EncodeToUtf8(source, destination, out consumed, out written, isFinalBlock: false); + text = Encoding.ASCII.GetString(destination, 0, written); + await Assert.That(status).IsEqualTo(OperationStatus.DestinationTooSmall); + await Assert.That(consumed).IsEqualTo(3); + await Assert.That(written).IsEqualTo(4); + await Assert.That(text).IsEqualTo(expected.Substring(0, 4)); + } } #endif