wfut  0.2.4
A client side C++ implementation of WFUT (WorldForge Update Tool).
Encoder.cpp
1 // This file may be redistributed and modified only under the terms of
2 // the GNU Lesser General Public License (See COPYING for details).
3 // Copyright (C) 2007 Simon Goodall
4 
5 #include <cstdio>
6 
7 #include "libwfut/Encoder.h"
8 #ifdef _WIN32
9 #define snprintf _snprintf
10 #endif
11 namespace WFUT {
12 
13 std::string Encoder::encodeString(const std::string &str) {
14  std::string out;
15 
16  for (size_t i = 0; i < str.size(); ++i) {
17  char c = str[i];
18  // Check char ranges
19  if ((c >= 'a' && c <= 'z')
20  || (c >= 'A' && c <= 'Z')
21  || (c >= '0' && c <= '9') ) {
22  out += c;
23  // Check individual chars
24  } else if (c == '-' || c == '_' || c == '.' || c == '*') {
25  out += c;
26  // Special case for a space
27  } else if (c == ' ') {
28  out += '+';
29  // Convert everything else to char codes
30  } else {
31  char buf[4];
32  buf[3] = '\0';
33  snprintf(buf, 4, "%%%2.2X", c);
34  out += buf;
35  }
36  }
37 
38  return out;
39 }
40 
41 std::string Encoder::decodeString(const std::string &str) {
42  std::string out;
43 
44  for (size_t i = 0; i < str.size(); ++i) {
45  char c = str[i];
46  if (c == '%') {
47  const char *buf = &str.c_str()[i];
48  unsigned int u;
49  sscanf(buf, "%%%2x", &u);
50  out += (char)u;
51  i+=2; // Increment counter against extra chars just used
52  } else if (c == '+') {
53  out += ' ';
54  } else {
55  out +=c;
56  }
57  }
58 
59  return out;
60 }
61 
62 std::string Encoder::encodeURL(const std::string &str) {
63  std::string out;
64 
65  for (size_t i = 0; i < str.size(); ++i) {
66  char c = str[i];
67  // Check char ranges
68  if ((c >= 'a' && c <= 'z')
69  || (c >= 'A' && c <= 'Z')
70  || (c >= '0' && c <= '9') ) {
71  out += c;
72  // Special case chars
73  } else if (c == '-' || c == '_' || c == '.' || c == '|' || c == '~' || c == '*' || c == '\'' || c == '(' || c == ')') {
74  out += c;
75  // More special case chars
76  } else if (c == ';' || c == '/' || c == '?' || c == ':' || c == '@' || c == '&' || c == '=' || c == '+' || c == '$' || c == ',') {
77  out += c;
78  // Convert everything else to char codes
79  } else {
80  char buf[4];
81  buf[3] = '\0';
82  snprintf(buf, 4, "%%%2.2X", c);
83  out += buf;
84  }
85  }
86 
87  return out;
88 }
89 
90 } /* namespace WFUT */
static std::string decodeString(const std::string &str)
Definition: Encoder.cpp:41
static std::string encodeURL(const std::string &str)
Definition: Encoder.cpp:62
static std::string encodeString(const std::string &str)
Definition: Encoder.cpp:13