blob: 4d18dfce349036f8a5b26345a152749fb50940f0 [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.
*/
#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_