From b2dfeaf1b92781a89e2620360f079ec8f27c1f7d Mon Sep 17 00:00:00 2001 From: Hielke Morsink Date: Sun, 5 Sep 2021 12:44:58 +0200 Subject: [PATCH] Introduce String::URLEncode --- src/openrct2/core/String.cpp | 28 ++++++++++++++++++++++++++++ src/openrct2/core/String.hpp | 2 ++ 2 files changed, 30 insertions(+) diff --git a/src/openrct2/core/String.cpp b/src/openrct2/core/String.cpp index bb773e5df9..a1e9ff1370 100644 --- a/src/openrct2/core/String.cpp +++ b/src/openrct2/core/String.cpp @@ -14,7 +14,10 @@ #endif // __MINGW32__ #include +#include #include +#include +#include #include #include #ifndef _WIN32 @@ -823,6 +826,31 @@ namespace String return trunc; } + + std::string URLEncode(std::string_view value) + { + std::ostringstream escaped; + escaped.fill('0'); + escaped << std::hex; + + for (auto c : value) + { + // Keep alphanumeric and other accepted characters intact + if (std::isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') + { + escaped << c; + } + else + { + // Any other characters are percent-escaped + escaped << std::uppercase; + escaped << '%' << std::setw(2) << int32_t(static_cast(c)); + escaped << std::nouppercase; + } + } + + return escaped.str(); + } } // namespace String char32_t CodepointView::iterator::GetNextCodepoint(const char* ch, const char** next) diff --git a/src/openrct2/core/String.hpp b/src/openrct2/core/String.hpp index d4ce69210e..8c590ee207 100644 --- a/src/openrct2/core/String.hpp +++ b/src/openrct2/core/String.hpp @@ -178,6 +178,8 @@ namespace String */ std::string_view UTF8Truncate(std::string_view v, size_t size); + // Escapes special characters in a string to the percentage equivalent that can be used in URLs. + std::string URLEncode(std::string_view value); } // namespace String class CodepointView