Skip to content

Commit 2afcac2

Browse files
authored
Use integer division trick to get exact base64 length (#31442)
1 parent 05ac9a4 commit 2afcac2

File tree

1 file changed

+1
-16
lines changed

1 file changed

+1
-16
lines changed

src/Http/Headers/src/ContentDispositionHeaderValue.cs

Lines changed: 1 addition & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -541,27 +541,12 @@ private bool RequiresEncoding(StringSegment input)
541541
return false;
542542
}
543543

544-
[MethodImpl(MethodImplOptions.AggressiveInlining)]
545-
private static int GetBase64Length(int inputLength)
546-
{
547-
// Copied from https://github.com/dotnet/runtime/blob/82ca681cbac89d813a3ce397e0c665e6c051ed67/src/libraries/System.Private.CoreLib/src/System/Convert.cs#L2530
548-
long outlen = ((long)inputLength) / 3 * 4; // the base length - we want integer division here.
549-
outlen += ((inputLength % 3) != 0) ? 4 : 0; // at most 4 more chars for the remainder
550-
551-
if (outlen > int.MaxValue)
552-
{
553-
throw new OutOfMemoryException();
554-
}
555-
556-
return (int)outlen;
557-
}
558-
559544
// Encode using MIME encoding
560545
// And adds surrounding quotes, Encoded data must always be quoted, the equals signs are invalid in tokens
561546
private string EncodeMimeWithQuotes(StringSegment input)
562547
{
563548
var requiredLength = MimePrefix.Length +
564-
GetBase64Length(Encoding.UTF8.GetByteCount(input.AsSpan())) +
549+
Base64.GetMaxEncodedToUtf8Length(Encoding.UTF8.GetByteCount(input.AsSpan())) +
565550
MimeSuffix.Length;
566551
Span<byte> buffer = requiredLength <= 256
567552
? (stackalloc byte[256]).Slice(0, requiredLength)

0 commit comments

Comments
 (0)