| 4447 | } |
| 4448 | |
| 4449 | static JSONCPP_STRING valueToQuotedStringN(const char* value, unsigned length) { |
| 4450 | if (value == NULL) |
| 4451 | return ""; |
| 4452 | |
| 4453 | if (!isAnyCharRequiredQuoting(value, length)) |
| 4454 | return JSONCPP_STRING("\"") + value + "\""; |
| 4455 | // We have to walk value and escape any special characters. |
| 4456 | // Appending to JSONCPP_STRING is not efficient, but this should be rare. |
| 4457 | // (Note: forward slashes are *not* rare, but I am not escaping them.) |
| 4458 | JSONCPP_STRING::size_type maxsize = length * 2 + 3; // allescaped+quotes+NULL |
| 4459 | JSONCPP_STRING result; |
| 4460 | result.reserve(maxsize); // to avoid lots of mallocs |
| 4461 | result += "\""; |
| 4462 | char const* end = value + length; |
| 4463 | for (const char* c = value; c != end; ++c) { |
| 4464 | switch (*c) { |
| 4465 | case '\"': |
| 4466 | result += "\\\""; |
| 4467 | break; |
| 4468 | case '\\': |
| 4469 | result += "\\\\"; |
| 4470 | break; |
| 4471 | case '\b': |
| 4472 | result += "\\b"; |
| 4473 | break; |
| 4474 | case '\f': |
| 4475 | result += "\\f"; |
| 4476 | break; |
| 4477 | case '\n': |
| 4478 | result += "\\n"; |
| 4479 | break; |
| 4480 | case '\r': |
| 4481 | result += "\\r"; |
| 4482 | break; |
| 4483 | case '\t': |
| 4484 | result += "\\t"; |
| 4485 | break; |
| 4486 | // case '/': |
| 4487 | // Even though \/ is considered a legal escape in JSON, a bare |
| 4488 | // slash is also legal, so I see no reason to escape it. |
| 4489 | // (I hope I am not misunderstanding something.) |
| 4490 | // blep notes: actually escaping \/ may be useful in javascript to avoid </ |
| 4491 | // sequence. |
| 4492 | // Should add a flag to allow this compatibility mode and prevent this |
| 4493 | // sequence from occurring. |
| 4494 | default: { |
| 4495 | unsigned int cp = utf8ToCodepoint(c, end); |
| 4496 | // don't escape non-control characters |
| 4497 | // (short escape sequence are applied above) |
| 4498 | if (cp < 0x80 && cp >= 0x20) |
| 4499 | result += static_cast<char>(cp); |
| 4500 | else if (cp < 0x10000) { // codepoint is in Basic Multilingual Plane |
| 4501 | result += "\\u"; |
| 4502 | result += toHex16Bit(cp); |
| 4503 | } else { // codepoint is not in Basic Multilingual Plane |
| 4504 | // convert to surrogate pair first |
| 4505 | cp -= 0x10000; |
| 4506 | result += "\\u"; |
no test coverage detected