From 01f33407182b48546816b2d9f830600996df3efa Mon Sep 17 00:00:00 2001 From: Benjamin Sergeant Date: Tue, 24 Sep 2019 14:17:03 -0700 Subject: [PATCH] speedup base64 code by reserving memory --- ixcrypto/ixcrypto/IXBase64.cpp | 11 +++++++++-- ixcrypto/ixcrypto/IXBase64.h | 1 + 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/ixcrypto/ixcrypto/IXBase64.cpp b/ixcrypto/ixcrypto/IXBase64.cpp index 2cee0f69..a2b4001b 100644 --- a/ixcrypto/ixcrypto/IXBase64.cpp +++ b/ixcrypto/ixcrypto/IXBase64.cpp @@ -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_])) { diff --git a/ixcrypto/ixcrypto/IXBase64.h b/ixcrypto/ixcrypto/IXBase64.h index 38527ea2..07bad77b 100644 --- a/ixcrypto/ixcrypto/IXBase64.h +++ b/ixcrypto/ixcrypto/IXBase64.h @@ -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