blob: da826d135c995dfea0faa17004ed8f2a47f53a05 [file] [log] [blame]
/*
* Copyright 2023 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "encode.h"
const char base64_alphabet[64] = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'};
void encode(const uint8_t* const in, size_t in_len, char* out) {
size_t rem = in_len % 3;
size_t out_idx = 0;
for (int i = 0; i < (in_len - rem); i += 3) {
out[out_idx++] = base64_alphabet[(in[0 + i] >> 2)];
out[out_idx++] =
base64_alphabet[((in[0 + i] & 0x3) << 4) | (in[1 + i] >> 4)];
out[out_idx++] =
base64_alphabet[((in[1 + i] & 0xf) << 2) | (in[2 + i] >> 6)];
out[out_idx++] = base64_alphabet[(in[2 + i] & 0x3f)];
}
if (rem == 2) {
out[out_idx++] = base64_alphabet[in[in_len - rem] >> 2];
out[out_idx++] = base64_alphabet[((in[in_len - rem] & 0x3) << 4) |
(in[in_len - rem + 1] >> 4)];
out[out_idx++] = base64_alphabet[((in[in_len - rem + 1] & 0xf) << 2)];
out[out_idx++] = '=';
} else if (rem == 1) {
out[out_idx++] = base64_alphabet[in[in_len - rem] >> 2];
out[out_idx++] = base64_alphabet[((in[in_len - rem] & 0x3) << 4) |
(in[in_len - rem + 1] >> 4)];
out[out_idx++] = '=';
out[out_idx++] = '=';
}
// NULL-terminate.
out[out_idx] = 0;
}