Skip to content

Commit

Permalink
b64_encode: Optimization code
Browse files Browse the repository at this point in the history
Signed-off-by: Jianhui Zhao <jianhuizhao329@gmail.com>
  • Loading branch information
Jianhui Zhao committed May 13, 2019
1 parent 6c07c96 commit 2444718
Showing 1 changed file with 19 additions and 22 deletions.
41 changes: 19 additions & 22 deletions src/utils.c
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ int parse_url(const char *url, char *host, int host_len,
} else {
return -1;
}

host_pos = url;

p = strchr(url, ':');
Expand Down Expand Up @@ -166,41 +166,37 @@ int tcp_connect(const char *host, int port, int flags, bool *inprogress, int *ea
int b64_encode(const void *src, size_t srclen, void *dest, size_t destsize)
{
char *Base64 =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
const uint8_t *input = src;
char *output = dest;

while (srclen > 0) {
int skip = 1;
int i0 = input[0] >> 2;
int skip = 1;
int i1 = (input[0] & 0x3) << 4;
int i2 = 64;
int i3 = 64;

if (destsize < 5)
return -1;

*output++ = Base64[i0];

if (srclen > 1) {
int i1 = ((input[0] & 0x3) << 4) + (input[1] >> 4);
*output++ = Base64[i1];
skip++;
i1 += input[1] >> 4;
i2 = (input[1] & 0xF) << 2;

if (srclen > 2) {
int i2 = ((input[1] & 0xF) << 2) + (input[2] >> 6);
int i3 = input[2] & 0x3F;
*output++ = Base64[i2];
*output++ = Base64[i3];
skip = 3;
} else {
int i2 = ((input[1] & 0xF) << 2);
*output++ = Base64[i2];
*output++ = '=';
skip = 2;
i2 += input[2] >> 6;
i3 = input[2] & 0x3F;
skip++;
}
} else {
int i1 = (input[0] & 0x3) << 4;
*output++ = Base64[i1];
*output++ = '=';
*output++ = '=';
}

*output++ = Base64[i0];
*output++ = Base64[i1];
*output++ = Base64[i2];
*output++ = Base64[i3];

input += skip;
srclen -= skip;
destsize -= 4;
Expand All @@ -209,3 +205,4 @@ int b64_encode(const void *src, size_t srclen, void *dest, size_t destsize)
*output++ = 0;
return output - (char *)dest - 1;
}

0 comments on commit 2444718

Please sign in to comment.