Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

base64: encode without snprintf: a 29x speedup #10026

Closed
wants to merge 7 commits into from
Closed
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 19 additions & 24 deletions lib/base64.c
Original file line number Diff line number Diff line change
Expand Up @@ -196,9 +196,9 @@ static CURLcode base64_encode(const char *table64,
if(!output)
return CURLE_OUT_OF_MEMORY;

while(insize > 0) {
while(insize) {
for(i = inputparts = 0; i < 3; i++) {
if(insize > 0) {
if(insize) {
inputparts++;
ibuf[i] = (unsigned char) *indata;
indata++;
Expand All @@ -208,39 +208,34 @@ static CURLcode base64_encode(const char *table64,
ibuf[i] = 0;
}

obuf[0] = (unsigned char) ((ibuf[0] & 0xFC) >> 2);
obuf[1] = (unsigned char) (((ibuf[0] & 0x03) << 4) | \
((ibuf[1] & 0xF0) >> 4));
obuf[2] = (unsigned char) (((ibuf[1] & 0x0F) << 2) | \
((ibuf[2] & 0xC0) >> 6));
obuf[3] = (unsigned char) (ibuf[2] & 0x3F);
obuf[0] = ibuf[0] >> 2;
obuf[1] = (((ibuf[0] & 0x03) << 4) | ((ibuf[1] & 0xF0) >> 4));

*output++ = table64[obuf[0]];
*output++ = table64[obuf[1]];

switch(inputparts) {
case 1: /* only one byte read */
i = msnprintf(output, 5, "%c%c%s%s",
table64[obuf[0]],
table64[obuf[1]],
padstr,
padstr);
if(*padstr) {
*output++ = *padstr;
*output++ = *padstr;
}
break;

case 2: /* two bytes read */
i = msnprintf(output, 5, "%c%c%c%s",
table64[obuf[0]],
table64[obuf[1]],
table64[obuf[2]],
padstr);
obuf[2] = (((ibuf[1] & 0x0F) << 2) | ((ibuf[2] & 0xC0) >> 6));
*output++ = table64[obuf[2]];
if(*padstr)
*output++ = *padstr;
break;

default:
i = msnprintf(output, 5, "%c%c%c%c",
table64[obuf[0]],
table64[obuf[1]],
table64[obuf[2]],
table64[obuf[3]]);
obuf[2] = (((ibuf[1] & 0x0F) << 2) | ((ibuf[2] & 0xC0) >> 6));
obuf[3] = ibuf[2] & 0x3F;
*output++ = table64[obuf[2]];
*output++ = table64[obuf[3]];
break;
}
output += i;
}

/* Zero terminate */
Expand Down