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