#include "base64.h"

static const char b64_enc_table[] =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

void base64_encode (const uint8_t *in, size_t ilen, char *out) {
    size_t out_len = 0;
    for (size_t i = 0; i < ilen; i += 3) {
        uint32_t triple = 0;
        int remain = ilen - i;

        triple |= in[i] << 16;
        if (remain > 1)
            triple |= in[i + 1] << 8;
        if (remain > 2)
            triple |= in[i + 2];

        out[out_len++] = b64_enc_table[(triple >> 18) & 0x3F];
        out[out_len++] = b64_enc_table[(triple >> 12) & 0x3F];
        out[out_len++] = (remain > 1) ? b64_enc_table[(triple >> 6) & 0x3F] : '=';
        out[out_len++] = (remain > 2) ? b64_enc_table[triple & 0x3F] : '=';
    }
}
