Line data Source code
1 : #include "UrlEncoding.h"
2 : #include <sstream>
3 :
4 : namespace Utils
5 : {
6 0 : static inline unsigned char to_hex(unsigned char x)
7 : {
8 0 : return x + (x > 9 ? ('A' - 10) : '0');
9 : }
10 :
11 0 : static inline unsigned char from_hex(unsigned char ch)
12 : {
13 0 : if (ch <= '9' && ch >= '0')
14 0 : ch -= '0';
15 0 : else if (ch <= 'f' && ch >= 'a')
16 0 : ch -= 'a' - 10;
17 0 : else if (ch <= 'F' && ch >= 'A')
18 0 : ch -= 'A' - 10;
19 : else
20 0 : ch = 0;
21 0 : return ch;
22 : }
23 :
24 0 : std::string UrlEncoding::encode(const std::string& unencoded)
25 : {
26 0 : std::ostringstream os;
27 :
28 0 : for (const auto& c : unencoded)
29 : {
30 0 : if ((c >= 'a' && c <= 'z') ||
31 0 : (c >= 'A' && c <= 'Z') ||
32 0 : (c >= '0' && c <= '9'))
33 : {
34 : // allowed
35 0 : os << c;
36 : }
37 0 : else if (c == ' ')
38 : {
39 : // space -> '+'
40 0 : os << '+';
41 : }
42 : else
43 : {
44 : // encode
45 0 : os << '%' << to_hex(c >> 4) << to_hex(c % 16);
46 : }
47 : }
48 :
49 0 : return os.str();
50 0 : }
51 :
52 0 : std::string UrlEncoding::decode(const std::string& encoded)
53 : {
54 0 : std::string result;
55 :
56 : std::string::size_type i;
57 0 : for (i = 0; i < encoded.size(); ++i)
58 : {
59 0 : if (encoded[i] == '+')
60 : {
61 0 : result += ' ';
62 : }
63 0 : else if (encoded[i] == '%' && encoded.size() > i + 2)
64 : {
65 0 : const unsigned char ch1 = from_hex(encoded[i + 1]);
66 0 : const unsigned char ch2 = from_hex(encoded[i + 2]);
67 0 : const unsigned char ch = (ch1 << 4) | ch2;
68 0 : result += ch;
69 0 : i += 2;
70 : }
71 : else
72 : {
73 0 : result += encoded[i];
74 : }
75 : }
76 :
77 0 : return result;
78 0 : }
79 : }
|