PageRenderTime 13ms CodeModel.GetById 1ms app.highlight 10ms RepoModel.GetById 1ms app.codeStats 0ms

/cgi/parser.cpp

https://bitbucket.org/nileshgr/cxxcms/
C++ | 81 lines | 53 code | 14 blank | 14 comment | 30 complexity | 06b05f595cb02e9e838a7f35d5d387eb MD5 | raw file
 1#include <cgi/cgi.hpp>
 2
 3/*! \file parser.cpp
 4  \brief Implementation of CGI::Parser
 5*/
 6
 7namespace CGI {
 8
 9  /*
10   * Implementation of the Parser class
11   */
12
13  /*
14   * Constructor has been defined in the header itself
15   * because it should be inlined, it conatins just one function call to setQstr()
16   */
17
18  void Parser::_sanitize(std::string& s, size_t n) const {
19    size_t i;
20    for (i = n; i < s.size(); i++) {
21      if (s.at(i) == '&' or s.at(i) == '=' or s.at(i) == ';') {
22	if (i == 0) break;
23	if (s.at(i-1) == '&' or s.at(i-1) == '=' or s.at(i-1) == ';') {
24	  s.erase(i,1);
25	  _sanitize(s,i);
26	}
27      }
28    }
29        
30    while (s.at(0) == '=' or s.at(0) == '&' or s.at(0) == ';')
31      s.erase(0,1);
32      
33    while (s.at(s.size()-1) == '=' or s.at(s.size()-1) == '&' or s.at(s.size()-1) == ';')
34      s.erase(s.size()-1,1);
35  }
36
37  Dict_ptr_t Parser::parse() const {    
38    std::string copy = getQstr(), extract = "";
39    _sanitize(copy);
40
41    size_t delimiter = std::string::npos;
42    Dict_ptr_t ret (new Dict_t);
43    std::string key = "", value = "";
44
45    while(copy.size()) {
46      if((delimiter = copy.find('&')) != std::string::npos or
47	 (delimiter = copy.find(';')) != std::string::npos) {
48	extract = copy.substr(0, delimiter);
49	copy.erase(0, delimiter + 1);
50      }
51      else {
52	extract = copy;
53	copy.clear();
54      }
55      if((delimiter = extract.find('=')) != std::string::npos) {
56	key  = extract.substr(0, delimiter);
57	value = extract.substr(delimiter + 1);
58	extract.clear();
59      }
60      else {
61	key = extract;
62	value = "";
63	extract.clear();
64      }
65      if((delimiter = key.find('%')) != std::string::npos)
66	key.replace(delimiter, delimiter + 3, 1, decodeHex(key.substr(delimiter, delimiter + 3)));
67
68      /*
69       * For some strange reason value.find() returns pos + 1 for position for %
70       * Hence a hack has been added here. If troublesome, remove -1 and change 4 to 3.
71       */
72      
73      if((delimiter = value.find('%') != std::string::npos))
74	value.replace(delimiter-1, delimiter + 4, 1, decodeHex(value.substr(delimiter-1, delimiter + 4)));
75      
76      ret->insert(Tuple_t(key, value));
77    }
78    return ret;
79  }
80  
81}