Skip to content

Commit 16ae1dc

Browse files
committed
fmt: Use escaped UTF-8 encoding for json strings
1 parent 4494500 commit 16ae1dc

2 files changed

Lines changed: 23 additions & 6 deletions

File tree

generators/include/pl/formatters/formatter_json.hpp

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -67,11 +67,28 @@ namespace pl::gen::fmt {
6767
const auto string = pattern->toString();
6868

6969
std::string result;
70-
for (char c : string) {
71-
if (std::isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~')
72-
result += c;
73-
else
74-
result += ::fmt::format("%{:02X}", c);
70+
for (const auto &ch : wolv::util::utf8ToUtf32(string, true).value()) {
71+
switch (ch) {
72+
case U'"': result += "\\\""; break;
73+
case U'\\': result += "\\\\"; break;
74+
case U'\b': result += "\\b"; break;
75+
case U'\f': result += "\\f"; break;
76+
case U'\n': result += "\\n"; break;
77+
case U'\r': result += "\\r"; break;
78+
case U'\t': result += "\\t"; break;
79+
default:
80+
if (ch < 0x20) {
81+
result += ::fmt::format("\\u{:04x}", static_cast<u32>(ch));
82+
} else if (ch <= 0xFFFF) {
83+
result += static_cast<char>(ch);
84+
} else {
85+
u32 code = static_cast<u32>(ch) - 0x10000;
86+
u16 highSurrogate = 0xD800 + ((code >> 10) & 0x3FF);
87+
u16 lowSurrogate = 0xDC00 + (code & 0x3FF);
88+
result += ::fmt::format("\\u{:04x}\\u{:04x}", highSurrogate, lowSurrogate);
89+
}
90+
break;
91+
}
7592
}
7693

7794
addLine(pattern->getVariableName(), ::fmt::format("\"{}\",", result));

0 commit comments

Comments
 (0)