Skip to content

Use integer division trick to get exact base64 length #31442

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 1, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 1 addition & 16 deletions src/Http/Headers/src/ContentDispositionHeaderValue.cs
Original file line number Diff line number Diff line change
Expand Up @@ -541,27 +541,12 @@ private bool RequiresEncoding(StringSegment input)
return false;
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int GetBase64Length(int inputLength)
{
// Copied from https://github.com/dotnet/runtime/blob/82ca681cbac89d813a3ce397e0c665e6c051ed67/src/libraries/System.Private.CoreLib/src/System/Convert.cs#L2530
long outlen = ((long)inputLength) / 3 * 4; // the base length - we want integer division here.
outlen += ((inputLength % 3) != 0) ? 4 : 0; // at most 4 more chars for the remainder

if (outlen > int.MaxValue)
{
throw new OutOfMemoryException();
}

return (int)outlen;
}

// Encode using MIME encoding
// And adds surrounding quotes, Encoded data must always be quoted, the equals signs are invalid in tokens
private string EncodeMimeWithQuotes(StringSegment input)
{
var requiredLength = MimePrefix.Length +
GetBase64Length(Encoding.UTF8.GetByteCount(input.AsSpan())) +
Base64.GetMaxEncodedToUtf8Length(Encoding.UTF8.GetByteCount(input.AsSpan())) +
MimeSuffix.Length;
Span<byte> buffer = requiredLength <= 256
? (stackalloc byte[256]).Slice(0, requiredLength)
Expand Down