Files
Library/include/Void/Text/Hex.hpp
faumaray 3851aeb703
CI / GCC 16 / C++26 / werror (push) Failing after 3m9s
CI / GCC 16 / C++26 / sanitizers (push) Failing after 10m15s
CI / GCC 16 / C++26 / default (push) Failing after 13m1s
Update
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-20 01:18:53 +03:00

104 lines
2.6 KiB
C++

#pragma once
#include <cstdint>
#include <optional>
#include <span>
#include <string>
#include <string_view>
#include <vector>
namespace Void::Encoding::Hex
{
/// Encode bytes to lowercase hex string.
[[nodiscard]] inline std::string encode(std::span<const std::byte> data)
{
constexpr std::string_view digits = "0123456789abcdef";
std::string out;
out.reserve(data.size() * 2);
for (auto b : data) {
const auto v = static_cast<std::uint8_t>(b);
out += digits[v >> 4];
out += digits[v & 0xF];
}
return out;
}
/// Encode an unsigned-byte view without treating binary data as text.
[[nodiscard]] inline std::string encode(std::span<const std::uint8_t> data)
{
return encode(std::as_bytes(data));
}
[[nodiscard]] inline std::string encode(std::string_view s)
{
return encode(std::as_bytes(std::span{s.data(), s.size()}));
}
/// Decode hex string to bytes. Returns nullopt on invalid input.
[[nodiscard]] inline std::optional<std::string> decode(std::string_view s)
{
if (s.size() % 2 != 0) {
return std::nullopt;
}
auto hex_val = [](char c) -> std::optional<std::uint8_t> {
if (c >= '0' && c <= '9') {
return static_cast<std::uint8_t>(c - '0');
}
if (c >= 'a' && c <= 'f') {
return static_cast<std::uint8_t>(c - 'a' + 10);
}
if (c >= 'A' && c <= 'F') {
return static_cast<std::uint8_t>(c - 'A' + 10);
}
return std::nullopt;
};
std::string out;
out.reserve(s.size() / 2);
for (std::size_t i = 0; i < s.size(); i += 2) {
auto hi = hex_val(s[i]);
auto lo = hex_val(s[i + 1]);
if (!hi || !lo) {
return std::nullopt;
}
out += static_cast<char>((*hi << 4) | *lo);
}
return out;
}
/// Decode hexadecimal text into an explicitly binary buffer.
[[nodiscard]] inline std::optional<std::vector<std::byte>>
decode_bytes(std::string_view s)
{
const auto decoded = decode(s);
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()};
}
/// Uppercase hex encoding.
[[nodiscard]] inline std::string
encode_upper(std::span<const std::byte> data)
{
constexpr std::string_view digits = "0123456789ABCDEF";
std::string out;
out.reserve(data.size() * 2);
for (auto b : data) {
const auto v = static_cast<std::uint8_t>(b);
out += digits[v >> 4];
out += digits[v & 0xF];
}
return out;
}
[[nodiscard]] inline std::string encode_upper(std::string_view s)
{
return encode_upper(std::as_bytes(std::span{s.data(), s.size()}));
}
} // namespace Void::Encoding::Hex