Commit 1dcce458 authored by Geoff Simmons's avatar Geoff Simmons

simplify base64_encode()

parent 38346b3e
......@@ -61,6 +61,7 @@ base64_encode(const enum encoding enc, char *restrict const buf,
const struct b64_alphabet *alpha = &b64_alphabet[enc];
char *p = buf;
const uint8_t *in = (uint8_t *)inbuf;
const uint8_t * const end = in + inlength;
AN(buf);
AN(alpha);
......@@ -70,34 +71,30 @@ base64_encode(const enum encoding enc, char *restrict const buf,
|| maxlen < base64nopad_encode_l(inlength))
return -1;
while (in < (uint8_t *)inbuf + inlength) {
uint8_t idx;
size_t rest = ((uint8_t *)inbuf + inlength) - in;
while (end - in >= 3) {
*p++ = alpha->b64[(in[0] >> 2) & 0x3f];
idx = (in[0] << 4);
if (rest > 1)
idx += (in[1] >> 4);
*p++ = alpha->b64[idx & 0x3f];
if (rest > 1) {
idx = (in[1] << 2);
if (rest > 2)
idx += in[2] >> 6;
*p++ = alpha->b64[idx & 0x3f];
}
else if (alpha->padding)
*p++ = alpha->padding;
if (rest > 2)
*p++ = alpha->b64[in[2] & 0x3f];
else if (alpha->padding)
*p++ = alpha->padding;
*p++ = alpha->b64[((in[0] << 4) | (in[1] >> 4)) & 0x3f];
*p++ = alpha->b64[((in[1] << 2) | (in[2] >> 6)) & 0x3f];
*p++ = alpha->b64[in[2] & 0x3f];
in += 3;
}
if (end - in > 0) {
*p++ = alpha->b64[(in[0] >> 2) & 0x3f];
if (end - in == 1) {
*p++ = alpha->b64[(in[0] << 4) & 0x3f];
if (alpha->padding) {
*p++ = alpha->padding;
*p++ = alpha->padding;
}
}
else {
*p++ = alpha->b64[((in[0] << 4) | (in[1] >> 4)) & 0x3f];
*p++ = alpha->b64[(in[1] << 2) & 0x3f];
if (alpha->padding) {
*p++ = alpha->padding;
}
}
}
assert(p >= buf && p - buf <= maxlen);
return p - buf;
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment