Text: add base32 codecs (#43)

This commit is contained in:
faumaray committed 2026-12-03 15:44:14 +03:00
1 parent b3c566ed4d
commit 2eb3bd230a
2 files changed
+564

No files matched your search

+273
View File
@@ -0,0 +1,273 @@
#pragma once
#include <Void/Text/Bounded.hpp>
#include <algorithm>
#include <array>
#include <cstddef>
#include <cstdint>
#include <optional>
#include <span>
#include <string>
#include <string_view>
#include <vector>
namespace Void::Encoding::Base32
{
namespace Detail
{
/// RFC 4648 section 6 alphabet.
constexpr std::string_view alphabet =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
/// Crockford alphabet: no I, L, O or U.
constexpr std::string_view alphabet_crockford =
"0123456789ABCDEFGHJKMNPQRSTVWXYZ";
constexpr char to_lower_ascii(char c) noexcept
{
return (c >= 'A' && c <= 'Z') ? static_cast<char>(c + ('a' - 'A')) : c;
}
[[nodiscard]] constexpr std::array<std::int8_t, 256>
make_rfc_table() noexcept
{
std::array<std::int8_t, 256> t{};
t.fill(-1);
for (std::size_t i = 0; i < 32; ++i) {
const char upper = alphabet[i];
t[static_cast<unsigned char>(upper)] =
static_cast<std::int8_t>(i);
t[static_cast<unsigned char>(to_lower_ascii(upper))] =
static_cast<std::int8_t>(i);
}
return t;
}
[[nodiscard]] constexpr std::array<std::int8_t, 256>
make_crockford_table() noexcept
{
std::array<std::int8_t, 256> t{};
t.fill(-1);
for (std::size_t i = 0; i < 32; ++i) {
const char upper = alphabet_crockford[i];
t[static_cast<unsigned char>(upper)] =
static_cast<std::int8_t>(i);
t[static_cast<unsigned char>(to_lower_ascii(upper))] =
static_cast<std::int8_t>(i);
}
// Crockford aliases: I and L are 1, O is 0.
for (const char c : {'I', 'i', 'L', 'l'}) {
t[static_cast<unsigned char>(c)] = 1;
}
for (const char c : {'O', 'o'}) {
t[static_cast<unsigned char>(c)] = 0;
}
// U is deliberately absent (rejected).
return t;
}
/// Overwrite partial output before discarding it so a failed decode
/// does not leave decoded plaintext behind in freed storage.
inline void wipe(std::string& out) noexcept
{
std::fill(out.begin(), out.end(), '\0');
out.clear();
}
inline std::string encode_with(std::span<const std::byte> data,
std::string_view alpha,
bool pad)
{
std::string out;
out.reserve(((data.size() + 4) / 5) * 8);
std::uint32_t buffer = 0;
int bits = 0;
for (const std::byte raw : data) {
buffer = (buffer << 8) |
static_cast<std::uint32_t>(
static_cast<std::uint8_t>(raw));
bits += 8;
while (bits >= 5) {
bits -= 5;
out += alpha[(buffer >> bits) & 0x1FU];
}
buffer &= bits == 0 ? 0U : ((1U << bits) - 1U);
}
if (bits != 0) {
out += alpha[(buffer << (5 - bits)) & 0x1FU];
}
if (pad) {
while (out.size() % 8 != 0) {
out += '=';
}
}
return out;
}
inline std::optional<std::string>
decode_with(std::string_view s,
const std::array<std::int8_t, 256>& table,
bool allow_padding,
bool skip_separators,
Void::Text::TextLimits limits)
{
if (s.size() > limits.max_input) {
return std::nullopt;
}
std::string out;
out.reserve((s.size() * 5) / 8);
std::uint32_t buffer = 0;
int bits = 0;
std::size_t symbols = 0;
std::size_t padding = 0;
bool saw_padding = false;
for (const char encoded : s) {
const auto character = static_cast<unsigned char>(encoded);
if (skip_separators && encoded == '-') {
continue;
}
if (allow_padding && encoded == '=') {
saw_padding = true;
++padding;
continue;
}
if (saw_padding) {
wipe(out);
return std::nullopt;
}
const std::int8_t value = table[character];
if (value < 0) {
wipe(out);
return std::nullopt;
}
buffer = (buffer << 5) | static_cast<std::uint32_t>(value);
bits += 5;
++symbols;
if (bits >= 8) {
bits -= 8;
out += static_cast<char>((buffer >> bits) & 0xFFU);
if (out.size() > limits.max_output) {
wipe(out);
return std::nullopt;
}
buffer &= bits == 0 ? 0U : ((1U << bits) - 1U);
}
}
const std::size_t remainder = symbols % 8;
if (remainder == 1 || remainder == 3 || remainder == 6) {
wipe(out);
return std::nullopt;
}
const std::size_t expected_padding =
remainder == 0 ? 0 : 8 - remainder;
if (padding != 0 && padding != expected_padding) {
wipe(out);
return std::nullopt;
}
// Non-zero trailing pad bits mean the text is not canonical.
if (bits != 0 && buffer != 0) {
wipe(out);
return std::nullopt;
}
return out;
}
} // namespace Detail
/// Encode bytes to RFC 4648 Base32 (uppercase, with padding).
[[nodiscard]] inline std::string encode(std::span<const std::byte> data)
{
return Detail::encode_with(data, Detail::alphabet, true);
}
/// Encode an unsigned-byte view without forcing callers to reinterpret
/// their binary buffers as text.
[[nodiscard]] inline std::string encode(std::span<const std::uint8_t> data)
{
return encode(std::as_bytes(data));
}
/// Encode a string_view to RFC 4648 Base32.
[[nodiscard]] inline std::string encode(std::string_view s)
{
return encode(std::as_bytes(std::span{s.data(), s.size()}));
}
/// Decode RFC 4648 Base32. Accepts padded or unpadded text and is
/// case-insensitive. Returns nullopt for invalid characters, impossible
/// lengths, malformed padding, non-zero trailing bits, or limits exceeded.
[[nodiscard]] inline std::optional<std::string>
decode(std::string_view s, Void::Text::TextLimits limits = {})
{
static constexpr auto table = Detail::make_rfc_table();
return Detail::decode_with(
s, table, /*allow_padding=*/true, /*skip_separators=*/false, limits);
}
/// Decode RFC 4648 Base32 into an explicitly binary buffer.
[[nodiscard]] inline std::optional<std::vector<std::byte>>
decode_bytes(std::string_view s, Void::Text::TextLimits limits = {})
{
const auto decoded = decode(s, limits);
if (!decoded) {
return std::nullopt;
}
const auto bytes =
std::as_bytes(std::span{decoded->data(), decoded->size()});
return std::vector<std::byte>{bytes.begin(), bytes.end()};
}
/// Encode bytes to Crockford Base32 (uppercase, no padding).
[[nodiscard]] inline std::string
encode_crockford(std::span<const std::byte> data)
{
return Detail::encode_with(data, Detail::alphabet_crockford, false);
}
[[nodiscard]] inline std::string
encode_crockford(std::span<const std::uint8_t> data)
{
return encode_crockford(std::as_bytes(data));
}
[[nodiscard]] inline std::string encode_crockford(std::string_view s)
{
return encode_crockford(std::as_bytes(std::span{s.data(), s.size()}));
}
/// Decode Crockford Base32. Case-insensitive; I/L map to 1, O maps to 0,
/// U is rejected, and '-' separators are skipped. Returns nullopt on
/// invalid input, impossible lengths, non-zero trailing bits, or limits
/// exceeded.
[[nodiscard]] inline std::optional<std::string>
decode_crockford(std::string_view s, Void::Text::TextLimits limits = {})
{
static constexpr auto table = Detail::make_crockford_table();
return Detail::decode_with(
s, table, /*allow_padding=*/false, /*skip_separators=*/true, limits);
}
/// Decode Crockford Base32 into an explicitly binary buffer.
[[nodiscard]] inline std::optional<std::vector<std::byte>>
decode_crockford_bytes(std::string_view s,
Void::Text::TextLimits limits = {})
{
const auto decoded = decode_crockford(s, limits);
if (!decoded) {
return std::nullopt;
}
const auto bytes =
std::as_bytes(std::span{decoded->data(), decoded->size()});
return std::vector<std::byte>{bytes.begin(), bytes.end()};
}
} // namespace Void::Encoding::Base32