Skip to content

Instantly share code, notes, and snippets.

@kadukf
Created April 23, 2020 20:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kadukf/f0193b4581e00bca5d4b810ca5aac8d4 to your computer and use it in GitHub Desktop.
Save kadukf/f0193b4581e00bca5d4b810ca5aac8d4 to your computer and use it in GitHub Desktop.
Base64Encoding.UsingSpanBase64
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