parse_string() * * Parse a string, starting at the current position. */
| 475 | * Parse a string, starting at the current position. |
| 476 | */ |
| 477 | string parse_string() { |
| 478 | string out; |
| 479 | long last_escaped_codepoint = -1; |
| 480 | while (true) { |
| 481 | if (i == str.size()) |
| 482 | return fail("Unexpected end of input in string", ""); |
| 483 | |
| 484 | char ch = str[i++]; |
| 485 | |
| 486 | if (ch == '"') { |
| 487 | encode_utf8(last_escaped_codepoint, out); |
| 488 | return out; |
| 489 | } |
| 490 | |
| 491 | if (in_range(ch, 0, 0x1f)) |
| 492 | return fail("Unescaped " + esc(ch) + " in string", ""); |
| 493 | |
| 494 | // The usual case: non-escaped characters |
| 495 | if (ch != '\\') { |
| 496 | encode_utf8(last_escaped_codepoint, out); |
| 497 | last_escaped_codepoint = -1; |
| 498 | out += ch; |
| 499 | continue; |
| 500 | } |
| 501 | |
| 502 | // Handle escapes |
| 503 | if (i == str.size()) |
| 504 | return fail("Unexpected end of input in string", ""); |
| 505 | |
| 506 | ch = str[i++]; |
| 507 | |
| 508 | if (ch == 'u') { |
| 509 | // Extract 4-byte escape sequence |
| 510 | string esc = str.substr(i, 4); |
| 511 | // Explicitly check length of the substring. The following loop |
| 512 | // relies on std::string returning the terminating NUL when |
| 513 | // accessing str[length]. Checking here reduces brittleness. |
| 514 | if (esc.length() < 4) { |
| 515 | return fail("Bad \\u escape: " + esc, ""); |
| 516 | } |
| 517 | for (size_t j = 0; j < 4; j++) { |
| 518 | if (!in_range(esc[j], 'a', 'f') && !in_range(esc[j], 'A', 'F') |
| 519 | && !in_range(esc[j], '0', '9')) |
| 520 | return fail("Bad \\u escape: " + esc, ""); |
| 521 | } |
| 522 | |
| 523 | long codepoint = strtol(esc.data(), nullptr, 16); |
| 524 | |
| 525 | // JSON specifies that characters outside the BMP shall be encoded as a pair |
| 526 | // of 4-hex-digit \u escapes encoding their surrogate pair components. Check |
| 527 | // whether we're in the middle of such a beast: the previous codepoint was an |
| 528 | // escaped lead (high) surrogate, and this is a trail (low) surrogate. |
| 529 | if (in_range(last_escaped_codepoint, 0xD800, 0xDBFF) |
| 530 | && in_range(codepoint, 0xDC00, 0xDFFF)) { |
| 531 | // Reassemble the two surrogate pairs into one astral-plane character, per |
| 532 | // the UTF-16 algorithm. |
| 533 | encode_utf8((((last_escaped_codepoint - 0xD800) << 10) |
| 534 | | (codepoint - 0xDC00)) + 0x10000, out); |