blob: 57789b56c9ece40a453f40293a3129b7b5144185 [file]
// Copyright 2022 Google LLC
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
#ifndef SW_DEVICE_LIB_TESTING_TEST_ROM_PUPPETEER_UTILS_BASE64_H_
#define SW_DEVICE_LIB_TESTING_TEST_ROM_PUPPETEER_UTILS_BASE64_H_
#include <stdint.h>
// Simple base64-to-byte converter.
// Usage:
//
// Base64 b;
// b.put_b64('R');
// b.put_b64('m');
// b.put_b64('9');
// b.put_b64('v');
//
// printf("This should say 'Foo': %c%c%c\n",
// b.get_byte(), b.get_byte(), b.get_byte());
//
struct Base64 {
uint32_t accum = 0;
int count = 0;
void put_b64(uint8_t b) {
if (b == '=') return;
accum <<= 6;
if (b >= 'A' && b <= 'Z') accum |= b - 'A';
if (b >= 'a' && b <= 'z') accum |= b - 'a' + 26;
if (b >= '0' && b <= '9') accum |= b - '0' + 52;
if (b == '+') accum |= 62;
if (b == '/') accum |= 63;
count += 6;
}
void put_byte(uint8_t c) {
accum <<= 8;
accum |= c;
count += 8;
}
uint8_t get_b64() {
uint8_t b = (accum >> (count - 6)) & 0x3F;
count -= 6;
if (b <= 25) return 'A' + b;
if (b <= 51) return 'a' + b - 26;
if (b <= 61) return '0' + b - 52;
if (b == 62) return '+';
if (b == 63) return '/';
return -1;
}
uint8_t get_byte() {
uint8_t result = (accum >> (count - 8)) & 0xFF;
count -= 8;
return result;
}
};
#endif // SW_DEVICE_LIB_TESTING_TEST_ROM_PUPPETEER_UTILS_BASE64_H_