#include "Void/TeamSpeak/Protocol/Util.hpp" #include #include namespace Void::TeamSpeak::Protocol::Util { namespace { constexpr char kEnc[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; std::array makeDecodeTable() { std::array t{}; t.fill(-1); for (int i = 0; i < 64; ++i) { t[static_cast(kEnc[i])] = static_cast(i); } return t; } const std::array kDec = makeDecodeTable(); } // namespace std::string base64Encode(ByteView data) { std::string out; out.reserve((data.size() + 2) / 3 * 4); size_t i = 0; for (; i + 3 <= data.size(); i += 3) { uint32_t n = (static_cast(data[i]) << 16) | (static_cast(data[i + 1]) << 8) | static_cast(data[i + 2]); out.push_back(kEnc[(n >> 18) & 0x3f]); out.push_back(kEnc[(n >> 12) & 0x3f]); out.push_back(kEnc[(n >> 6) & 0x3f]); out.push_back(kEnc[n & 0x3f]); } const size_t rem = data.size() - i; if (rem == 1) { uint32_t n = static_cast(data[i]) << 16; out.push_back(kEnc[(n >> 18) & 0x3f]); out.push_back(kEnc[(n >> 12) & 0x3f]); out.push_back('='); out.push_back('='); } else if (rem == 2) { uint32_t n = (static_cast(data[i]) << 16) | (static_cast(data[i + 1]) << 8); out.push_back(kEnc[(n >> 18) & 0x3f]); out.push_back(kEnc[(n >> 12) & 0x3f]); out.push_back(kEnc[(n >> 6) & 0x3f]); out.push_back('='); } return out; } Bytes base64Decode(const std::string& text) { Bytes out; out.reserve(text.size() / 4 * 3); uint32_t buf = 0; int bits = 0; for (char c : text) { if (c == '=' || c == '\n' || c == '\r' || c == ' ') { continue; } int8_t v = kDec[static_cast(c)]; if (v < 0) { throw std::runtime_error("invalid base64 character"); } buf = (buf << 6) | static_cast(v); bits += 6; if (bits >= 8) { bits -= 8; out.push_back(static_cast((buf >> bits) & 0xff)); } } return out; } std::string toHex(ByteView data) { static const char* h = "0123456789abcdef"; std::string out; out.reserve(data.size() * 2); for (uint8_t b : data) { out.push_back(h[b >> 4]); out.push_back(h[b & 0x0f]); } return out; } Bytes fromHex(const std::string& hex) { auto nib = [](char c) -> int { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'a' && c <= 'f') return c - 'a' + 10; if (c >= 'A' && c <= 'F') return c - 'A' + 10; throw std::runtime_error("invalid hex character"); }; if (hex.size() % 2 != 0) { throw std::runtime_error("odd-length hex string"); } Bytes out; out.reserve(hex.size() / 2); for (size_t i = 0; i < hex.size(); i += 2) { out.push_back(static_cast((nib(hex[i]) << 4) | nib(hex[i + 1]))); } return out; } } // namespace Void::TeamSpeak::Protocol::Util