| 4689 | static void appendHex(String &result, unsigned ch) { result.append("\\u").append(toHex16Bit(ch)); } |
| 4690 | |
| 4691 | static String valueToQuotedStringN(const char *value, size_t length, bool emitUTF8 = false) |
| 4692 | { |
| 4693 | if (value == nullptr) |
| 4694 | return ""; |
| 4695 | |
| 4696 | if (!doesAnyCharRequireEscaping(value, length)) |
| 4697 | return String("\"") + value + "\""; |
| 4698 | // We have to walk value and escape any special characters. |
| 4699 | // Appending to String is not efficient, but this should be rare. |
| 4700 | // (Note: forward slashes are *not* rare, but I am not escaping them.) |
| 4701 | String::size_type maxsize = length * 2 + 3; // allescaped+quotes+NULL |
| 4702 | String result; |
| 4703 | result.reserve(maxsize); // to avoid lots of mallocs |
| 4704 | result += "\""; |
| 4705 | char const *end = value + length; |
| 4706 | for (const char *c = value; c != end; ++c) |
| 4707 | { |
| 4708 | switch (*c) |
| 4709 | { |
| 4710 | case '\"': |
| 4711 | result += "\\\""; |
| 4712 | break; |
| 4713 | case '\\': |
| 4714 | result += "\\\\"; |
| 4715 | break; |
| 4716 | case '\b': |
| 4717 | result += "\\b"; |
| 4718 | break; |
| 4719 | case '\f': |
| 4720 | result += "\\f"; |
| 4721 | break; |
| 4722 | case '\n': |
| 4723 | result += "\\n"; |
| 4724 | break; |
| 4725 | case '\r': |
| 4726 | result += "\\r"; |
| 4727 | break; |
| 4728 | case '\t': |
| 4729 | result += "\\t"; |
| 4730 | break; |
| 4731 | // case '/': |
| 4732 | // Even though \/ is considered a legal escape in JSON, a bare |
| 4733 | // slash is also legal, so I see no reason to escape it. |
| 4734 | // (I hope I am not misunderstanding something.) |
| 4735 | // blep notes: actually escaping \/ may be useful in javascript to avoid </ |
| 4736 | // sequence. |
| 4737 | // Should add a flag to allow this compatibility mode and prevent this |
| 4738 | // sequence from occurring. |
| 4739 | default: |
| 4740 | { |
| 4741 | if (emitUTF8) |
| 4742 | { |
| 4743 | unsigned codepoint = static_cast<unsigned char>(*c); |
| 4744 | if (codepoint < 0x20) |
| 4745 | { |
| 4746 | appendHex(result, codepoint); |
| 4747 | } |
| 4748 | else |
no test coverage detected