Merge pull request #1959 from G10h4ck/rsbase64_fixup

RsBase64 handle correcly 0 lenght buffer encoding and padding
This commit is contained in:
G10h4ck 2020-05-28 18:45:04 +02:00 committed by GitHub
commit 968f234bfd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 15 additions and 5 deletions

View File

@ -21,8 +21,6 @@
* *
*******************************************************************************/
#include <cmath>
#include "util/rsbase64.h"
#include "util/rsdebug.h"
@ -40,6 +38,12 @@
rs_view_ptr<const uint8_t> data, size_t len, std::string& outString,
bool padding, bool urlSafe )
{
if(!data || !len)
{
outString.clear();
return;
}
const char* sDict = urlSafe ? uDict : bDict;
// Workaround if input and output are the same buffer.
@ -137,9 +141,11 @@
/*static*/ size_t RsBase64::encodedSize(size_t decodedSize, bool padding)
{
if(padding) return 4 * (decodedSize + 2) / 3;
return static_cast<size_t>(
std::ceil(4L * static_cast<double>(decodedSize) / 3L) );
if(!decodedSize) return 0;
// 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; }
};