| 3158 | std::string valueToString(bool value) { return value ? "true" : "false"; } |
| 3159 | |
| 3160 | std::string valueToQuotedString(const char *value) { |
| 3161 | if (value == NULL) |
| 3162 | return ""; |
| 3163 | // Not sure how to handle unicode... |
| 3164 | if (strpbrk(value, "\"\\\b\f\n\r\t") == NULL && |
| 3165 | !containsControlCharacter(value)) |
| 3166 | return std::string("\"") + value + "\""; |
| 3167 | // We have to walk value and escape any special characters. |
| 3168 | // Appending to std::string is not efficient, but this should be rare. |
| 3169 | // (Note: forward slashes are *not* rare, but I am not escaping them.) |
| 3170 | std::string::size_type maxsize = |
| 3171 | strlen(value) * 2 + 3; // allescaped+quotes+NULL |
| 3172 | std::string result; |
| 3173 | result.reserve(maxsize); // to avoid lots of mallocs |
| 3174 | result += "\""; |
| 3175 | for (const char *c = value; *c != 0; ++c) { |
| 3176 | switch (*c) { |
| 3177 | case '\"': |
| 3178 | result += "\\\""; |
| 3179 | break; |
| 3180 | case '\\': |
| 3181 | result += "\\\\"; |
| 3182 | break; |
| 3183 | case '\b': |
| 3184 | result += "\\b"; |
| 3185 | break; |
| 3186 | case '\f': |
| 3187 | result += "\\f"; |
| 3188 | break; |
| 3189 | case '\n': |
| 3190 | result += "\\n"; |
| 3191 | break; |
| 3192 | case '\r': |
| 3193 | result += "\\r"; |
| 3194 | break; |
| 3195 | case '\t': |
| 3196 | result += "\\t"; |
| 3197 | break; |
| 3198 | // case '/': |
| 3199 | // Even though \/ is considered a legal escape in JSON, a bare |
| 3200 | // slash is also legal, so I see no reason to escape it. |
| 3201 | // (I hope I am not misunderstanding something. |
| 3202 | // blep notes: actually escaping \/ may be useful in javascript to avoid </ |
| 3203 | // sequence. |
| 3204 | // Should add a flag to allow this compatibility mode and prevent this |
| 3205 | // sequence from occurring. |
| 3206 | default: |
| 3207 | if (isControlCharacter(*c)) { |
| 3208 | std::ostringstream oss; |
| 3209 | oss << "\\u" << std::hex << std::uppercase << std::setfill('0') |
| 3210 | << std::setw(4) << static_cast<int>(*c); |
| 3211 | result += oss.str(); |
| 3212 | } else { |
| 3213 | result += *c; |
| 3214 | } |
| 3215 | break; |
| 3216 | } |
| 3217 | } |
no test coverage detected