40inline constexpr std::string_view chars =
41 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
46static constexpr std::array<int, 256> build_decode_table() {
47 std::array<int, 256> table{};
48 for (
size_t i = 0; i < 256; ++i) {
51 for (
size_t i = 0; i < chars.size(); ++i) {
52 table[
static_cast<uint8_t
>(chars[i])] =
static_cast<int>(i);
57static constexpr auto decode_table = build_decode_table();
64 if (data.empty() || data.size() % 4 != 0)
return false;
66 size_t size = data.size();
69 for (
size_t i = 0; i < size; ++i) {
70 unsigned char c =
static_cast<uint8_t
>(data[i]);
75 if (i < size - 2 || (i == size - 2 && data[size - 1] !=
'='))
87 if (decode_table[c] == -1)
97inline std::string
encode(std::string_view data) {
101 out.reserve(((data.size() + 2) / 3) * 4);
102 for (
unsigned char c : data) {
103 val = (val << 8) + c;
106 out.push_back(chars[(val >> valb) & 0x3F]);
111 out.push_back(chars[((val << 8) >> (valb + 8)) & 0x3F]);
112 while (out.size() % 4)
121inline std::vector<uint8_t>
decode(std::string_view data) {
122 std::vector<uint8_t> out;
123 out.reserve((data.size() / 4) * 3);
126 for (
char c : data) {
129 int v = decode_table[
static_cast<uint8_t
>(c)];
132 val = (val << 6) + v;
135 out.push_back(
static_cast<uint8_t
>((val >> valb) & 0xFF));
std::vector< uint8_t > decode(std::string_view data)
Definition tec_base64.hpp:121
std::string encode(std::string_view data)
Definition tec_base64.hpp:97
bool is_valid(std::string_view data)
Definition tec_base64.hpp:63