#pragma once #include #include #include #include #include namespace Void::Encoding::Url { namespace Detail { // RFC 3986 unreserved characters: ALPHA / DIGIT / "-" / "." / "_" / "~". [[nodiscard]] constexpr std::array make_unreserved() noexcept { std::array t{}; for (char c = 'A'; c <= 'Z'; ++c) t[static_cast(c)] = true; for (char c = 'a'; c <= 'z'; ++c) t[static_cast(c)] = true; for (char c = '0'; c <= '9'; ++c) t[static_cast(c)] = true; for (char c : {'-', '.', '_', '~'}) t[static_cast(c)] = true; return t; } inline constexpr std::array unreserved = make_unreserved(); inline constexpr std::string_view hex_upper = "0123456789ABCDEF"; [[nodiscard]] constexpr int hex_value(unsigned char c) noexcept { 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; return -1; } } // namespace Detail /// Percent-encode `s` per RFC 3986. Unreserved characters pass through; every /// other byte becomes %XX (uppercase hex). When `space_as_plus` is true a space /// is emitted as '+' (application/x-www-form-urlencoded form encoding) instead /// of %20. [[nodiscard]] inline std::string encode(std::string_view s, bool space_as_plus = false) { std::string out; out.reserve(s.size() * 3); for (unsigned char c : s) { if (Detail::unreserved[c]) { out += static_cast(c); } else if (space_as_plus && c == ' ') { out += '+'; } else { out += '%'; out += Detail::hex_upper[c >> 4]; out += Detail::hex_upper[c & 0x0F]; } } return out; } /// Encode for a query-string value: form encoding with spaces as '+'. [[nodiscard]] inline std::string query_encode(std::string_view s) { return encode(s, /*space_as_plus=*/true); } /// Decode a percent-encoded string. '+' is treated as a space when /// `plus_as_space` is true (form decoding). Returns nullopt on a malformed /// escape (a '%' not followed by two hex digits). [[nodiscard]] inline std::optional decode(std::string_view s, bool plus_as_space = false) { std::string out; out.reserve(s.size()); for (std::size_t i = 0; i < s.size(); ++i) { const unsigned char c = static_cast(s[i]); if (c == '%') { if (i + 2 >= s.size()) return std::nullopt; const int hi = Detail::hex_value(static_cast(s[i + 1])); const int lo = Detail::hex_value(static_cast(s[i + 2])); if (hi < 0 || lo < 0) return std::nullopt; out += static_cast((hi << 4) | lo); i += 2; } else if (plus_as_space && c == '+') { out += ' '; } else { out += static_cast(c); } } return out; } } // namespace Void::Encoding::Url