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