From 8cebe56350decbc8a9792bd099813273c46ba621 Mon Sep 17 00:00:00 2001 From: whaffman Date: Thu, 30 Oct 2025 16:11:43 +0100 Subject: [PATCH] urlencode in utils --- webserv/utils/utils.cpp | 48 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/webserv/utils/utils.cpp b/webserv/utils/utils.cpp index d29db36..89efba3 100644 --- a/webserv/utils/utils.cpp +++ b/webserv/utils/utils.cpp @@ -153,4 +153,52 @@ uint32_t stateToEpoll(const ASocket::IoState &event) } return epollEvents; } + +std::string uriEncode(const std::string &value) +{ + std::ostringstream escaped; + escaped.fill('0'); + escaped << std::hex; + + for (char c : value) + { + // Keep alphanumeric and other accepted characters intact + if (isalnum(static_cast(c)) || c == '-' || c == '_' || c == '.' || c == '~') + { + escaped << c; + } + else + { + // Any other characters are percent-encoded + escaped << '%' << std::uppercase << std::setw(2) << int(static_cast(c)) << std::nouppercase; + } + } + + return escaped.str(); +} + +std::string uriDecode(const std::string &value) +{ + std::ostringstream unescaped; + size_t length = value.length(); + + for (size_t i = 0; i < length; ++i) + { + if (value[i] == '%' && i + 2 < length) + { + std::istringstream hexStream{value.substr(i + 1, 2)}; + int hexValue = 0; + hexStream >> std::hex >> hexValue; + unescaped << static_cast(hexValue); + i += 2; + } + else + { + unescaped << value[i]; + } + } + + return unescaped.str(); +} + } // namespace utils \ No newline at end of file