Skip to content

Commit 36aad2d

Browse files
author
me
committed
optimizing base64
1 parent 8a6d834 commit 36aad2d

1 file changed

Lines changed: 23 additions & 24 deletions

File tree

src/http.cpp

Lines changed: 23 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -703,40 +703,39 @@ namespace http
703703
std::string base64_encode(const size_t ndata, const uint8_t* data)
704704
{
705705
std::string ret;
706-
ret.reserve((ndata+2) / 3 * 4);
707-
uint8_t word{0};
708-
uint8_t off{6};
706+
ret.resize((ndata+2) / 3 * 4);
707+
size_t i{0};
708+
char* out{&ret[0]};
709709

710-
for (size_t i = 0 ; i < ndata ; ++i)
710+
while (i < ndata)
711711
{
712-
const uint8_t byte = data[i];
712+
*out++ = base64_encode_table[(data[i+0] & 0xfc) >> 2];
713713

714-
for (int j = 7 ; j >= 0 ; --j)
714+
if (i+1 < ndata)
715715
{
716-
const uint8_t bit = (byte >> j) & 0x1;
717-
718-
word |= (bit << --off);
716+
*out++ = base64_encode_table[((data[i+0] & 0x03) << 4) + ((data[i + 1] & 0xf0) >> 4)];
719717

720-
if (off == 0)
718+
if (i+2 < ndata)
721719
{
722-
assert(word < 64);
723-
ret.push_back(base64_encode_table[word]);
724-
off = 6;
725-
word = 0;
720+
*out++ = base64_encode_table[((data[i+1] & 0x0f) << 2) + ((data[i + 2] & 0xc0) >> 6)];
721+
*out++ = base64_encode_table[ data[i+2] & 0x3f];
722+
}
723+
else
724+
{
725+
*out++ = base64_encode_table[(data[i+1] & 0x0f) << 2];
726+
*out++ = '=';
726727
}
727728
}
728-
}
729-
730-
assert(off == 6 || off == 2 || off == 4);
729+
else
730+
{
731+
*out++ = base64_encode_table[(data[i+0] & 0x03) << 4];
732+
*out++ = '=';
733+
*out++ = '=';
734+
}
731735

732-
if (off < 6)
733-
{
734-
const size_t npadding = off / 2;
735-
ret.push_back(base64_encode_table[word]);
736-
for (size_t i = 0 ; i < npadding ; ++i)
737-
ret.push_back('=');
736+
i += 3;
738737
}
739-
738+
740739
return ret;
741740
}
742741

0 commit comments

Comments
 (0)