RsBase64 calculate size properly and avoid FP math

This commit is contained in:
Gioacchino Mazzurco 2020-05-28 17:57:42 +02:00
parent 3332c32a84
commit d76f397358
No known key found for this signature in database
GPG Key ID: A1FBCA3872E87051
2 changed files with 8 additions and 5 deletions

View File

@ -21,8 +21,6 @@
* *
*******************************************************************************/
#include <cmath>
#include "util/rsbase64.h"
#include "util/rsdebug.h"
@ -144,9 +142,10 @@
/*static*/ size_t RsBase64::encodedSize(size_t decodedSize, bool padding)
{
if(!decodedSize) return 0;
if(padding) return 4 * (decodedSize + 2) / 3;
return static_cast<size_t>(
std::ceil(4L * static_cast<double>(decodedSize) / 3L) );
// Thanks https://stackoverflow.com/a/45401395
if(padding) return ceilDivision(decodedSize, 3) * 4;
return ceilDivision(decodedSize * 8, 6);
}
/*static*/ std::tuple<size_t, std::error_condition> RsBase64::decodedSize(

View File

@ -137,4 +137,8 @@ private:
*/
static inline bool isBase64Char(char c)
{ return rDict[static_cast<uint8_t>(c)] >= 0; }
/** Perform ceil division without floating point operations */
static inline size_t ceilDivision(size_t dividend, size_t divisor)
{ return (dividend + divisor - 1) / divisor; }
};