Fix small overestimation of base64 encoding output length.
authorTom Lane <[email protected]>
Thu, 8 Jun 2023 15:24:31 +0000 (11:24 -0400)
committerTom Lane <[email protected]>
Thu, 8 Jun 2023 15:24:31 +0000 (11:24 -0400)
pg_base64_enc_len() and its clones overestimated the output
length by up to 2 bytes, as a result of sloppy thinking about
where to divide.  No callers require a precise estimate, so
this has no consequences worse than palloc'ing a byte or two
more than necessary.  We might as well get it right though.

This bug is very ancient, dating to commit 79d78bb26 which
added encode.c.  (The other instances were presumably copied
from there.)  Still, it doesn't quite seem worth back-ing.

Oleg Tselebrovskiy

Discussion: https://postgr.es/m/f94da55286a63022150bc266afdab754@postgrespro.ru

contrib/pgcrypto/pgp-armor.c
src/backend/utils/adt/encode.c
src/common/base64.c

index 679779a6ac26c6bcd55a1842bcace3f8df8f069f..9128756647c559db33eb388b8238794001fd2495 100644 (file)
@@ -165,7 +165,7 @@ pg_base64_enc_len(unsigned srclen)
    /*
     * 3 bytes will be converted to 4, linefeed after 76 chars
     */
-   return (srclen + 2) * 4 / 3 + srclen / (76 * 3 / 4);
+   return (srclen + 2) / 3 * 4 + srclen / (76 * 3 / 4);
 }
 
 static unsigned
index b92191de81e14e25ad09bff127cd7377568bcf16..e5ac3ad23dfc608087eee50a4ac49f6fed061b9f 100644 (file)
@@ -385,7 +385,7 @@ static uint64
 pg_base64_enc_len(const char *src, size_t srclen)
 {
    /* 3 bytes will be converted to 4, linefeed after 76 chars */
-   return ((uint64) srclen + 2) * 4 / 3 + (uint64) srclen / (76 * 3 / 4);
+   return ((uint64) srclen + 2) / 3 * 4 + (uint64) srclen / (76 * 3 / 4);
 }
 
 static uint64
index 2943ac76520a00339b1120820ba3d90615fa20fc..ec4eb49382cca6cf81cb35025bb47971c57ded4c 100644 (file)
@@ -224,7 +224,7 @@ int
 pg_b64_enc_len(int srclen)
 {
    /* 3 bytes will be converted to 4 */
-   return (srclen + 2) * 4 / 3;
+   return (srclen + 2) / 3 * 4;
 }
 
 /*