| 4341 | } |
| 4342 | |
| 4343 | static String valueToQuotedStringN(const char *value, unsigned length) { |
| 4344 | if (value == nullptr) |
| 4345 | return ""; |
| 4346 | |
| 4347 | if (!isAnyCharRequiredQuoting(value, length)) |
| 4348 | return String("\"") + value + "\""; |
| 4349 | // We have to walk value and escape any special characters. |
| 4350 | // Appending to String is not efficient, but this should be rare. |
| 4351 | // (Note: forward slashes are *not* rare, but I am not escaping them.) |
| 4352 | String::size_type maxsize = length * 2 + 3; // allescaped+quotes+NULL |
| 4353 | String result; |
| 4354 | result.reserve(maxsize); // to avoid lots of mallocs |
| 4355 | result += "\""; |
| 4356 | char const *end = value + length; |
| 4357 | for (const char *c = value; c != end; ++c) { |
| 4358 | switch (*c) { |
| 4359 | case '\"': |
| 4360 | result += "\\\""; |
| 4361 | break; |
| 4362 | case '\\': |
| 4363 | result += "\\\\"; |
| 4364 | break; |
| 4365 | case '\b': |
| 4366 | result += "\\b"; |
| 4367 | break; |
| 4368 | case '\f': |
| 4369 | result += "\\f"; |
| 4370 | break; |
| 4371 | case '\n': |
| 4372 | result += "\\n"; |
| 4373 | break; |
| 4374 | case '\r': |
| 4375 | result += "\\r"; |
| 4376 | break; |
| 4377 | case '\t': |
| 4378 | result += "\\t"; |
| 4379 | break; |
| 4380 | // case '/': |
| 4381 | // Even though \/ is considered a legal escape in JSON, a bare |
| 4382 | // slash is also legal, so I see no reason to escape it. |
| 4383 | // (I hope I am not misunderstanding something.) |
| 4384 | // blep notes: actually escaping \/ may be useful in javascript to avoid </ |
| 4385 | // sequence. |
| 4386 | // Should add a flag to allow this compatibility mode and prevent this |
| 4387 | // sequence from occurring. |
| 4388 | default: { |
| 4389 | unsigned int cp = utf8ToCodepoint(c, end); |
| 4390 | // don't escape non-control characters |
| 4391 | // (short escape sequence are applied above) |
| 4392 | if (cp < 0x80 && cp >= 0x20) |
| 4393 | result += static_cast<char>(cp); |
| 4394 | else if (cp < 0x10000) { // codepoint is in Basic Multilingual Plane |
| 4395 | result += "\\u"; |
| 4396 | result += toHex16Bit(cp); |
| 4397 | } else { // codepoint is not in Basic Multilingual Plane |
| 4398 | // convert to surrogate pair first |
| 4399 | cp -= 0x10000; |
| 4400 | result += "\\u"; |
no test coverage detected