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