speedup base64 code by reserving memory

This commit is contained in:
Benjamin Sergeant 2019-09-24 14:17:03 -07:00
parent d3cee46e93
commit 5c18ffdae2
2 changed files with 10 additions and 2 deletions

View File

@ -35,15 +35,21 @@ namespace ix
"0123456789+/";
std::string base64_encode(const std::string& data, size_t len)
{
const char* bytes_to_encode = data.c_str();
return base64_encode(bytes_to_encode, len);
}
std::string base64_encode(const char* bytes_to_encode, size_t len)
{
std::string ret;
ret.reserve(((len + 2) / 3) * 4);
int i = 0;
int j = 0;
unsigned char char_array_3[3];
unsigned char char_array_4[4];
const char* bytes_to_encode = data.c_str();
while(len--)
{
char_array_3[i++] = *(bytes_to_encode++);
@ -95,6 +101,7 @@ namespace ix
int in_ = 0;
unsigned char char_array_4[4], char_array_3[3];
std::string ret;
ret.reserve(((in_len + 3) / 4) * 3);
while(in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_]))
{

View File

@ -11,5 +11,6 @@
namespace ix
{
std::string base64_encode(const std::string& data, size_t len);
std::string base64_encode(const char* data, size_t len);
std::string base64_decode(const std::string& encoded_string);
} // namespace ix