00001
00002
00003
00004
00005
00006
00007
00008 #include <string>
00009 #include <cassert>
00010 #include <stdexcept>
00011 #include <sstream>
00012 #include <iomanip>
00013 #include <cctype>
00014 #include <algorithm>
00015
00016 namespace libtorrent
00017 {
00018 std::string unescape_string(std::string const& s)
00019 {
00020 std::string ret;
00021 for (std::string::const_iterator i = s.begin(); i != s.end(); ++i)
00022 {
00023 if(*i == '+')
00024 {
00025 ret += ' ';
00026 }
00027 else if (*i != '%')
00028 {
00029 ret += *i;
00030 }
00031 else
00032 {
00033 ++i;
00034 if (i == s.end())
00035 throw std::runtime_error("invalid escaped string");
00036
00037 int high;
00038 if(*i >= '0' && *i <= '9') high = *i - '0';
00039 else if(*i >= 'A' && *i <= 'F') high = *i + 10 - 'A';
00040 else if(*i >= 'a' && *i <= 'f') high = *i + 10 - 'a';
00041 else throw std::runtime_error("invalid escaped string");
00042
00043 ++i;
00044 if (i == s.end())
00045 throw std::runtime_error("invalid escaped string");
00046
00047 int low;
00048 if(*i >= '0' && *i <= '9') low = *i - '0';
00049 else if(*i >= 'A' && *i <= 'F') low = *i + 10 - 'A';
00050 else if(*i >= 'a' && *i <= 'f') low = *i + 10 - 'a';
00051 else throw std::runtime_error("invalid escaped string");
00052
00053 ret += char(high * 16 + low);
00054 }
00055 }
00056 return ret;
00057 }
00058
00059 std::string escape_string(const char* str, int len)
00060 {
00061 assert(str != 0);
00062 assert(len >= 0);
00063
00064
00065
00066
00067 static const char unreserved_chars[] = "-_.!~*()"
00068 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
00069 "0123456789";
00070
00071 std::stringstream ret;
00072 ret << std::hex << std::setfill('0');
00073 for (int i = 0; i < len; ++i)
00074 {
00075 if (std::count(
00076 unreserved_chars
00077 , unreserved_chars+sizeof(unreserved_chars)-1
00078 , *str))
00079 {
00080 ret << *str;
00081 }
00082 else
00083 {
00084 ret << '%'
00085 << std::setw(2)
00086 << (int)static_cast<unsigned char>(*str);
00087 }
00088 ++str;
00089 }
00090 return ret.str();
00091 }
00092
00093 std::string escape_path(const char* str, int len)
00094 {
00095 assert(str != 0);
00096 assert(len >= 0);
00097 static const char unreserved_chars[] = "/-_.!~*()"
00098 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
00099 "0123456789";
00100
00101 std::stringstream ret;
00102 ret << std::hex << std::setfill('0');
00103 for (int i = 0; i < len; ++i)
00104 {
00105 if (std::count(
00106 unreserved_chars
00107 , unreserved_chars+sizeof(unreserved_chars)-1
00108 , *str))
00109 {
00110 ret << *str;
00111 }
00112 else
00113 {
00114 ret << '%'
00115 << std::setw(2)
00116 << (int)static_cast<unsigned char>(*str);
00117 }
00118 ++str;
00119 }
00120 return ret.str();
00121 }
00122 }