File tree Expand file tree Collapse file tree 2 files changed +52
-0
lines changed
Expand file tree Collapse file tree 2 files changed +52
-0
lines changed Original file line number Diff line number Diff line change 11#include < cassert>
22#include < cstring>
33#include < cstdarg>
4+ #include < cctype>
45#include < algorithm>
56#include < filesystem>
67#include < boost/asio/version.hpp>
@@ -811,6 +812,52 @@ namespace http
811812 return ret;
812813 }
813814
815+ // ----------------------------------------------------------------------------------------------------------------
816+
817+ static char from_hex (char ch) {return std::isdigit (ch) ? ch - ' 0' : std::tolower (ch) - ' a' + 10 ;}
818+ static char to_hex (char code) {constexpr char hex[] = " 0123456789abcdef" ; return hex[code & 15 ];}
819+
820+ std::string url_encode (std::string_view str)
821+ {
822+ std::string ret (str.size ()*3 +1 , ' \0 ' );
823+ char * buf = &ret[0 ];
824+
825+ for (auto c : str)
826+ {
827+ if (std::isalnum (c) || c == ' -' || c == ' _' || c == ' .' || c == ' ~' )
828+ *buf++ = c;
829+ else if (c == ' ' )
830+ *buf++ = ' +' ;
831+ else
832+ *buf++ = ' %' , *buf++ = to_hex (c >> 4 ), *buf++ = to_hex (c & 15 );
833+ }
834+
835+ ret.resize (strlen (ret.data ()));
836+ return ret;
837+ }
838+
839+ std::string url_decode (std::string_view str)
840+ {
841+ std::string ret (str.size () + 1 , ' \0 ' );
842+ char * buf = &ret[0 ];
843+
844+ for (size_t i = 0 ; i < str.size () ; ++i)
845+ {
846+ if (str[i] == ' %' && str.size () > (i+2 ))
847+ {
848+ *buf++ = from_hex (str[i+1 ]) << 4 | from_hex (str[i+2 ]);
849+ i += 2 ;
850+ }
851+ else if (str[i] == ' +' )
852+ *buf++ = ' ' ;
853+ else
854+ *buf++ = str[i];
855+ }
856+
857+ ret.resize (strlen (ret.data ()));
858+ return ret;
859+ }
860+
814861// ----------------------------------------------------------------------------------------------------------------
815862
816863 bool header::contains_value (std::string_view v) const
Original file line number Diff line number Diff line change @@ -511,6 +511,11 @@ namespace http
511511 std::string base64_encode (const size_t ndata, const uint8_t * data);
512512 std::vector<uint8_t > base64_decode (std::string_view data);
513513
514+ // ----------------------------------------------------------------------------------------------------------------
515+
516+ std::string url_encode (std::string_view str);
517+ std::string url_decode (std::string_view str);
518+
514519// ----------------------------------------------------------------------------------------------------------------
515520
516521 struct header
You can’t perform that action at this time.
0 commit comments