From f4d5c9a4353d6f85c45f0f2a5584ac23a3bee0a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?G=C3=BCnther=20Foidl?= Date: Wed, 31 Mar 2021 12:35:38 +0200 Subject: [PATCH 1/2] Use integer division trick to get exact base64 length and avoid modulo operation --- .../System.Private.CoreLib/src/System/Convert.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/libraries/System.Private.CoreLib/src/System/Convert.cs b/src/libraries/System.Private.CoreLib/src/System/Convert.cs index 05384d5449a35f..93c81464c3a0d1 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Convert.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Convert.cs @@ -2527,16 +2527,16 @@ private static unsafe int ConvertToBase64Array(char* outChars, byte* inData, int private static int ToBase64_CalculateAndValidateOutputLength(int inputLength, bool insertLineBreaks) { - 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 + // the base length - we want integer division here, at most 4 more chars for the remainder + long outlen = ((long)inputLength + 2) / 3 * 4; if (outlen == 0) return 0; if (insertLineBreaks) { - long newLines = outlen / base64LineBreakPosition; - if ((outlen % base64LineBreakPosition) == 0) + long newLines = Math.DivRem(outlen, base64LineBreakPosition, out long remainder); + if (remainder == 0) { --newLines; } From d6ea2d9d84a45bc6692d37c5ce7e88d18d7c5380 Mon Sep 17 00:00:00 2001 From: Stephen Toub Date: Thu, 1 Apr 2021 09:29:58 -0400 Subject: [PATCH 2/2] Update src/libraries/System.Private.CoreLib/src/System/Convert.cs Co-authored-by: Jan Kotas --- src/libraries/System.Private.CoreLib/src/System/Convert.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libraries/System.Private.CoreLib/src/System/Convert.cs b/src/libraries/System.Private.CoreLib/src/System/Convert.cs index 93c81464c3a0d1..d7b6b19d44c846 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Convert.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Convert.cs @@ -2535,7 +2535,7 @@ private static int ToBase64_CalculateAndValidateOutputLength(int inputLength, bo if (insertLineBreaks) { - long newLines = Math.DivRem(outlen, base64LineBreakPosition, out long remainder); + (long newLines, long remainder) = Math.DivRem(outlen, base64LineBreakPosition); if (remainder == 0) { --newLines;