| 4211 | std::string valueToString(bool value) { return value ? "true" : "false"; } |
| 4212 | |
| 4213 | std::string valueToQuotedString(const char* value) { |
| 4214 | if (value == NULL) |
| 4215 | return ""; |
| 4216 | // Not sure how to handle unicode... |
| 4217 | if (strpbrk(value, "\"\\\b\f\n\r\t") == NULL && |
| 4218 | !containsControlCharacter(value)) |
| 4219 | return std::string("\"") + value + "\""; |
| 4220 | // We have to walk value and escape any special characters. |
| 4221 | // Appending to std::string is not efficient, but this should be rare. |
| 4222 | // (Note: forward slashes are *not* rare, but I am not escaping them.) |
| 4223 | std::string::size_type maxsize = |
| 4224 | strlen(value) * 2 + 3; // allescaped+quotes+NULL |
| 4225 | std::string result; |
| 4226 | result.reserve(maxsize); // to avoid lots of mallocs |
| 4227 | result += "\""; |
| 4228 | for (const char* c = value; *c != 0; ++c) { |
| 4229 | switch (*c) { |
| 4230 | case '\"': |
| 4231 | result += "\\\""; |
| 4232 | break; |
| 4233 | case '\\': |
| 4234 | result += "\\\\"; |
| 4235 | break; |
| 4236 | case '\b': |
| 4237 | result += "\\b"; |
| 4238 | break; |
| 4239 | case '\f': |
| 4240 | result += "\\f"; |
| 4241 | break; |
| 4242 | case '\n': |
| 4243 | result += "\\n"; |
| 4244 | break; |
| 4245 | case '\r': |
| 4246 | result += "\\r"; |
| 4247 | break; |
| 4248 | case '\t': |
| 4249 | result += "\\t"; |
| 4250 | break; |
| 4251 | // case '/': |
| 4252 | // Even though \/ is considered a legal escape in JSON, a bare |
| 4253 | // slash is also legal, so I see no reason to escape it. |
| 4254 | // (I hope I am not misunderstanding something. |
| 4255 | // blep notes: actually escaping \/ may be useful in javascript to avoid </ |
| 4256 | // sequence. |
| 4257 | // Should add a flag to allow this compatibility mode and prevent this |
| 4258 | // sequence from occurring. |
| 4259 | default: |
| 4260 | if (isControlCharacter(*c)) { |
| 4261 | std::ostringstream oss; |
| 4262 | oss << "\\u" << std::hex << std::uppercase << std::setfill('0') |
| 4263 | << std::setw(4) << static_cast<int>(*c); |
| 4264 | result += oss.str(); |
| 4265 | } else { |
| 4266 | result += *c; |
| 4267 | } |
| 4268 | break; |
| 4269 | } |
| 4270 | } |
no test coverage detected