#include <array>
#include <cstdint>
#include <limits>
#include "cow_string.hpp"
#include "memory_resource.hpp"
#include "transformer/base64_encode.hpp"
namespace ddwaf::transformer {
bool base64_encode::transform_impl(cow_string &str)
{
if (str.length() >= std::numeric_limits<cow_string::size_type>::max() / 4 * 3) {
return false;
}
const cow_string::size_type encoded_length = (str.length() + 2) / 3 * 4;
auto *alloc = memory::get_default_resource();
auto *new_string = static_cast<char *>(alloc->allocate(encoded_length, alignof(char)));
if (new_string == nullptr) {
return false;
}
static constexpr std::array<char, 66> b64Encoding{'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', '+',
'-'};
cow_string::size_type read = 0;
cow_string::size_type write = 0;
for (; read + 2 < str.length(); read += 3) {
const std::array<uint8_t, 4> quartet{static_cast<uint8_t>(str.at<uint8_t>(read) >> 2),
static_cast<uint8_t>(
(str.at<uint8_t>(read) & 0x3) << 4 | (str.at<uint8_t>(read + 1) >> 4)),
static_cast<uint8_t>(
(str.at<uint8_t>(read + 1) & 0xf) << 2 | str.at<uint8_t>(read + 2) >> 6),
static_cast<uint8_t>(str.at<uint8_t>(read + 2) & 0x3f)};
new_string[write++] = b64Encoding[quartet[0]];
new_string[write++] = b64Encoding[quartet[1]];
new_string[write++] = b64Encoding[quartet[2]];
new_string[write++] = b64Encoding[quartet[3]];
}
if (read < str.length()) {
const uint8_t first_byte = str.at<uint8_t>(read) >> 2;
uint8_t second_byte = (str.at<uint8_t>(read) & 0x3) << 4;
new_string[write++] = b64Encoding[first_byte];
if (read + 1 >= str.length()) {
new_string[write++] = b64Encoding[second_byte];
new_string[write++] = '=';
} else {
second_byte |= (str.at<uint8_t>(read + 1) >> 4);
const uint8_t third_byte = (str.at<uint8_t>(read + 1) & 0xf) << 2;
new_string[write++] = b64Encoding[second_byte];
new_string[write++] = b64Encoding[third_byte];
}
new_string[write++] = '=';
}
str.replace_buffer(new_string, write, encoded_length);
return true;
}
}