-
Notifications
You must be signed in to change notification settings - Fork 4
/
urlcode.cpp
68 lines (55 loc) · 1.22 KB
/
urlcode.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include "urlcode.h"
char UrlCode::FromHex(char ch)
{
return isdigit(ch) ? ch - '0' : tolower(ch) - 'a' + 10;
}
char UrlCode::ToHex(char code)
{
static char hex[] = "0123456789abcdef";
return hex[code & 15];
}
std::string UrlCode::Decode(std::string url)
{
const char *pstr = url.c_str();
char *buf = new char[url.length() + 1];
char *pbuf = buf;
while (*pstr) {
if (*pstr == '%') {
if (pstr[1] && pstr[2]) {
*pbuf++ = FromHex(pstr[1]) << 4 | FromHex(pstr[2]);
pstr += 2;
}
} else if (*pstr == '+') {
*pbuf++ = ' ';
} else {
*pbuf++ = *pstr;
}
pstr++;
}
*pbuf = '\0';
std::string decoded = buf;
delete buf;
return decoded;
}
std::string UrlCode::Encode(std::string url)
{
const char *pstr = url.c_str();
char *buf = new char[url.length() * 3 + 1];
char *pbuf = buf;
while (*pstr) {
if (isalnum(*pstr) || *pstr == '-' || *pstr == '_' || *pstr == '.' || *pstr == '~') {
*pbuf++ = *pstr;
} else if (*pstr == ' ') {
*pbuf++ = '+';
} else {
*pbuf++ = '%';
*pbuf++ = ToHex(*pstr >> 4);
*pbuf++ = ToHex(*pstr & 15);
}
pstr++;
}
*pbuf = '\0';
std::string encoded = buf;
delete buf;
return encoded;
}