| 4395 | } |
| 4396 | |
| 4397 | static JSONCPP_STRING valueToQuotedStringN(const char* value, unsigned length) { |
| 4398 | if (value == NULL) |
| 4399 | return ""; |
| 4400 | |
| 4401 | if (!isAnyCharRequiredQuoting(value, length)) |
| 4402 | return JSONCPP_STRING("\"") + value + "\""; |
| 4403 | // We have to walk value and escape any special characters. |
| 4404 | // Appending to JSONCPP_STRING is not efficient, but this should be rare. |
| 4405 | // (Note: forward slashes are *not* rare, but I am not escaping them.) |
| 4406 | JSONCPP_STRING::size_type maxsize = |
| 4407 | length * 2 + 3; // allescaped+quotes+NULL |
| 4408 | JSONCPP_STRING result; |
| 4409 | result.reserve(maxsize); // to avoid lots of mallocs |
| 4410 | result += "\""; |
| 4411 | char const* end = value + length; |
| 4412 | for (const char* c = value; c != end; ++c) { |
| 4413 | switch (*c) { |
| 4414 | case '\"': |
| 4415 | result += "\\\""; |
| 4416 | break; |
| 4417 | case '\\': |
| 4418 | result += "\\\\"; |
| 4419 | break; |
| 4420 | case '\b': |
| 4421 | result += "\\b"; |
| 4422 | break; |
| 4423 | case '\f': |
| 4424 | result += "\\f"; |
| 4425 | break; |
| 4426 | case '\n': |
| 4427 | result += "\\n"; |
| 4428 | break; |
| 4429 | case '\r': |
| 4430 | result += "\\r"; |
| 4431 | break; |
| 4432 | case '\t': |
| 4433 | result += "\\t"; |
| 4434 | break; |
| 4435 | // case '/': |
| 4436 | // Even though \/ is considered a legal escape in JSON, a bare |
| 4437 | // slash is also legal, so I see no reason to escape it. |
| 4438 | // (I hope I am not misunderstanding something.) |
| 4439 | // blep notes: actually escaping \/ may be useful in javascript to avoid </ |
| 4440 | // sequence. |
| 4441 | // Should add a flag to allow this compatibility mode and prevent this |
| 4442 | // sequence from occurring. |
| 4443 | default: { |
| 4444 | unsigned int cp = utf8ToCodepoint(c, end); |
| 4445 | // don't escape non-control characters |
| 4446 | // (short escape sequence are applied above) |
| 4447 | if (cp < 0x80 && cp >= 0x20) |
| 4448 | result += static_cast<char>(cp); |
| 4449 | else if (cp < 0x10000) { // codepoint is in Basic Multilingual Plane |
| 4450 | result += "\\u"; |
| 4451 | result += toHex16Bit(cp); |
| 4452 | } |
| 4453 | else { // codepoint is not in Basic Multilingual Plane |
| 4454 | // convert to surrogate pair first |
no test coverage detected