Skip to content

Commit 3b58acc

Browse files
committed
Use integer division trick to get exact base64 length and avoid modulo operation
1 parent 1810cfe commit 3b58acc

File tree

1 file changed

+8
-6
lines changed

1 file changed

+8
-6
lines changed

src/Http/Headers/src/ContentDispositionHeaderValue.cs

+8-6
Original file line numberDiff line numberDiff line change
@@ -544,16 +544,18 @@ private bool RequiresEncoding(StringSegment input)
544544
[MethodImpl(MethodImplOptions.AggressiveInlining)]
545545
private static int GetBase64Length(int inputLength)
546546
{
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
547+
// Based on https://github.com/dotnet/runtime/blob/ac21254184f5a6cec884d8d4049c80d905170b38/src/libraries/System.Memory/src/System/Buffers/Text/Base64Encoder.cs#L150
550548

551-
if (outlen > int.MaxValue)
549+
const int MaximumEncodeLength = (int.MaxValue / 4) * 3; // 1610612733
550+
551+
if ((uint)inputLength <= MaximumEncodeLength)
552552
{
553-
throw new OutOfMemoryException();
553+
return ((inputLength + 2) / 3) * 4;
554554
}
555555

556-
return (int)outlen;
556+
Throw();
557+
static void Throw() => throw new OutOfMemoryException();
558+
throw null!;
557559
}
558560

559561
// Encode using MIME encoding

0 commit comments

Comments
 (0)