]> git.tdb.fi Git - libs/net.git/blob - source/utils.cpp
Support handling requests asynchronously
[libs/net.git] / source / utils.cpp
1 /* $Id$
2
3 This file is part of libmsphttp
4 Copyright © 2009  Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
6 */
7
8 #include <msp/strings/formatter.h>
9 #include "utils.h"
10
11 using namespace std;
12
13 namespace {
14
15 const char reserved[]=" :/?#[]@!$&'()*+,;=%";
16
17 bool is_reserved(char c)
18 {
19         for(const char *r=reserved; *r; ++r)
20                 if(c==*r)
21                         return true;
22         return false;
23 }
24
25 }
26
27 namespace Msp {
28 namespace Http {
29
30 string urlencode(const string &str)
31 {
32         string result;
33         for(string::const_iterator i=str.begin(); i!=str.end(); ++i)
34         {
35                 if(is_reserved(*i))
36                         result+=format("%%%02X", *i);
37                 else
38                         result+=*i;
39         }
40         return result;
41 }
42
43 string urldecode(const string &str)
44 {
45         string result;
46         for(unsigned i=0; i<str.size(); ++i)
47         {
48                 char c=str[i];
49                 if(c=='%')
50                 {
51                         if(i+3>str.size())
52                                 throw InvalidParameterValue("Malformed data");
53                         result+=lexical_cast<unsigned char>(str.substr(i+1, 2), "x");
54                         i+=2;
55                 }
56                 else if(c=='+')
57                         result+=' ';
58                 else
59                         result+=c;
60         }
61         return result;
62 }
63
64 } // namespace Http
65 } // namespace Msp