Created
April 23, 2020 20:29
-
-
Save kadukf/f0193b4581e00bca5d4b810ca5aac8d4 to your computer and use it in GitHub Desktop.
Base64Encoding.UsingSpanBase64
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static string UsingSpanBase64(Guid oid, params string[] input) | |
{ | |
var totalUtf8Bytes = 36; // GUID.Format(D) = 36 bytes | |
for (int i = 0; i < input.Length; i++) | |
{ | |
totalUtf8Bytes += Encoding.UTF8.GetByteCount(input[i]); | |
} | |
Span<byte> resultSpan = stackalloc byte[Base64.GetMaxEncodedToUtf8Length(totalUtf8Bytes)]; | |
if (!Utf8Formatter.TryFormat(oid, resultSpan, out int writtenBytes) || writtenBytes != 36) | |
{ | |
throw new ArithmeticException(); | |
} | |
for (int i = 0; i < input.Length; i++) | |
{ | |
var ixs = EncodingHelper.GetUtf8Bytes(input[i].AsSpan(), resultSpan.Slice(writtenBytes)); | |
writtenBytes += ixs; | |
} | |
OperationStatus status = Base64.EncodeToUtf8InPlace(resultSpan, totalUtf8Bytes, out int base64Written); | |
if (status != OperationStatus.Done) | |
{ | |
throw new ArithmeticException(); | |
} | |
var base64String = EncodingHelper.GetUrlSafeString(resultSpan.Slice(0, base64Written)); | |
return base64String; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment