From c6aa76122e209350b8a7b3cb8b5bc8127a3722e7 Mon Sep 17 00:00:00 2001
From: Benjamin Lutz <mail@maxlor.com>
Date: Mon, 16 Sep 2013 14:37:34 +0200
Subject: [PATCH] Fix size miscalculation in QByteArray::toBase64

The size calculation in QByteArray::toBase64 overcalculates the size
required for the output by up to 3 Bytes. This is fixed, which also
implies that truncate() at the end is needed only if OmitTrailingEquals
is used.

Task-number: QTBUG-32436
Change-Id: I92a893047e7aca027c4aa0a6655bcca514585ff5
Reviewed-by: Oswald Buddenhagen <oswald.buddenhagen@theqtcompany.com>
Reviewed-by: Thiago Macieira <thiago.macieira@intel.com>
---
 src/corelib/tools/qbytearray.cpp | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)

diff --git a/src/corelib/tools/qbytearray.cpp b/src/corelib/tools/qbytearray.cpp
index a622221bd31..6ac442d27b2 100644
--- a/src/corelib/tools/qbytearray.cpp
+++ b/src/corelib/tools/qbytearray.cpp
@@ -3571,7 +3571,7 @@ QByteArray QByteArray::toBase64(Base64Options options) const
     const char padchar = '=';
     int padlen = 0;
 
-    QByteArray tmp((d->size * 4) / 3 + 3, Qt::Uninitialized);
+    QByteArray tmp((d->size + 2) / 3 * 4, Qt::Uninitialized);
 
     int i = 0;
     char *out = tmp.data();
@@ -3609,8 +3609,9 @@ QByteArray QByteArray::toBase64(Base64Options options) const
             *out++ = alphabet[m];
         }
     }
-
-    tmp.truncate(out - tmp.data());
+    Q_ASSERT((options & OmitTrailingEquals) || (out == tmp.size() + tmp.data()));
+    if (options & OmitTrailingEquals)
+        tmp.truncate(out - tmp.data());
     return tmp;
 }
 
-- 
GitLab