diff --git a/include/Void/Data/Json.hpp b/include/Void/Data/Json.hpp index 3994c4a..5ef7fc6 100644 --- a/include/Void/Data/Json.hpp +++ b/include/Void/Data/Json.hpp @@ -580,23 +580,52 @@ namespace Void::Json break; case 'u': { - if (pos + 4 > src.size()) { - return std::unexpected{ - err("incomplete \\uXXXX")}; - } - const auto hex = src.substr(pos, 4); + auto read_hex4 = + [&](std::size_t at, + unsigned& out_cp) -> bool { + if (at + 4 > src.size()) { + return false; + } + const auto h = src.substr(at, 4); + const auto [p, e] = std::from_chars( + h.data(), h.data() + 4, out_cp, 16); + return e == std::errc{} && + p == h.data() + 4; + }; + unsigned cp = 0; - const auto [p, e] = std::from_chars( - hex.data(), hex.data() + 4, cp, 16); - if (e != std::errc{} || - p != hex.data() + 4) { + if (!read_hex4(pos, cp)) { return std::unexpected{ err("invalid \\uXXXX escape")}; } for (std::size_t i = 0; i < 4; ++i) { advance(); } - // Encode as UTF-8 + + // Combine a UTF-16 surrogate pair + // (\uD800-\uDBFF followed by \uDC00-\uDFFF) + // into one code point, so astral characters + // (emoji, …) become valid 4-byte UTF-8 + // instead of two invalid encoded surrogates. + if (cp >= 0xD800 && cp <= 0xDBFF) { + unsigned lo = 0; + if (pos + 1 < src.size() && + src[pos] == '\\' && + src[pos + 1] == 'u' && + read_hex4(pos + 2, lo) && + lo >= 0xDC00 && lo <= 0xDFFF) { + cp = 0x10000u + + ((cp - 0xD800u) << 10) + + (lo - 0xDC00u); + for (std::size_t i = 0; i < 6; ++i) { + advance(); + } + } + // A lone surrogate falls through and is + // encoded as-is. + } + + // Encode as UTF-8. if (cp < 0x80) { out += static_cast(cp); } else if (cp < 0x800) { @@ -604,13 +633,22 @@ namespace Void::Json static_cast(0xC0 | (cp >> 6)); out += static_cast(0x80 | (cp & 0x3F)); - } else { + } else if (cp < 0x10000) { out += static_cast(0xE0 | (cp >> 12)); out += static_cast( 0x80 | ((cp >> 6) & 0x3F)); out += static_cast(0x80 | (cp & 0x3F)); + } else { + out += static_cast(0xF0 | + (cp >> 18)); + out += static_cast( + 0x80 | ((cp >> 12) & 0x3F)); + out += static_cast( + 0x80 | ((cp >> 6) & 0x3F)); + out += static_cast(0x80 | + (cp & 0x3F)); } break; }