Some refactoring
diff --git a/src/passes/Print.cpp b/src/passes/Print.cpp index 0581427..5ccef12 100644 --- a/src/passes/Print.cpp +++ b/src/passes/Print.cpp
@@ -3709,29 +3709,9 @@ doIndent(o, indent); o << ";; custom section \"" << section.name << "\", size " << section.data.size(); - // The contents are printable if they are valid UTF-8 and all the ASCII - // characters are printable (non-ASCII bytes are part of multi-byte UTF-8 - // sequences, which we emit as-is). - bool isPrintable = String::isUTF8( - std::string_view(section.data.data(), section.data.size())); - for (auto c : section.data) { - auto u = static_cast<unsigned char>(c); - if (u < 0x80 && !isprint(u)) { - isPrintable = false; - break; - } - } - if (isPrintable) { - o << ", contents: "; - // std::quoted is not available in all the supported compilers yet. - o << '"'; - for (auto c : section.data) { - if (c == '\\' || c == '"') { - o << '\\'; - } - o << c; - } - o << '"'; + std::string_view sectionData(section.data.data(), section.data.size()); + if (String::isPrintableUTF8(sectionData)) { + o << ", contents: " << std::quoted(sectionData); } o << maybeNewLine; }
diff --git a/src/support/string.cpp b/src/support/string.cpp index 8e09d05..d3fbcec 100644 --- a/src/support/string.cpp +++ b/src/support/string.cpp
@@ -484,6 +484,21 @@ return true; } +bool isPrintableUTF8(std::string_view str) { + while (!str.empty()) { + auto u = takeWTF8CodePoint(str); + if (!u) { + return false; // Invalid encoding + } + // Reject ASCII control chars (0x00-0x1F), DEL (0x7F), and surrogates + // (0xD800-0xDFFF) + if (*u < 0x20 || *u == 0x7F || (0xD800 <= *u && *u < 0xE000)) { + return false; + } + } + return true; +} + std::ostream& unescapeUTF8JSONtoWTF16(std::ostream& os, const char* str) { std::string_view view(str); size_t i = 0;
diff --git a/src/support/string.h b/src/support/string.h index 6a7617e..4e9d108 100644 --- a/src/support/string.h +++ b/src/support/string.h
@@ -123,6 +123,10 @@ // Whether the string is valid UTF-8. bool isUTF8(std::string_view str); +// Whether the string is both valid UTF-8 and doesn't contain unprintable +// characters e.g. ASCII control characters. +bool isPrintableUTF8(std::string_view str); + // Given a string of properly-escaped JSON in UTF8, unescape it into WTF16. std::ostream& unescapeUTF8JSONtoWTF16(std::ostream& os, const char* str);