@@ -42,30 +42,22 @@ void appendUnsignedAsHex(uint16_t number, StringBuilder* dst)
4242 }
4343}
4444
45- void escapeStringForJSON(const String& str, StringBuilder* dst)
46- {
47- for (unsigned i = 0; i < str.length(); ++i) {
48- uint16_t c = str[i];
49- if (!escapeChar(c, dst)) {
50- if (c < 32 || c > 126 || c == '<' || c == '>') {
51- // 1. Escaping <, > to prevent script execution.
52- // 2. Technically, we could also pass through c > 126 as UTF8, but this
53- // is also optional. It would also be a pain to implement here.
54- appendUnsignedAsHex(c, dst);
55- } else {
56- StringUtil::builderAppend(*dst, c);
57- }
45+ template <typename Char>
46+ void escapeStringForJSONInternal(const Char* str, unsigned len,
47+ StringBuilder* dst)
48+ {
49+ for (unsigned i = 0; i < len; ++i) {
50+ Char c = str[i];
51+ if (escapeChar(c, dst))
52+ continue;
53+ if (c < 32 || c > 126) {
54+ appendUnsignedAsHex(c, dst);
55+ } else {
56+ StringUtil::builderAppend(*dst, c);
5857 }
5958 }
6059}
6160
62- void doubleQuoteStringForJSON(const String& str, StringBuilder* dst)
63- {
64- StringUtil::builderAppend(*dst, '"');
65- escapeStringForJSON(str, dst);
66- StringUtil::builderAppend(*dst, '"');
67- }
68-
6961} // anonymous namespace
7062
7163bool Value::asBoolean(bool*) const
@@ -181,7 +173,7 @@ bool StringValue::asString(String* output) const
181173void StringValue::writeJSON(StringBuilder* output) const
182174{
183175 DCHECK(type() == TypeString);
184- doubleQuoteStringForJSON(m_stringValue, output );
176+ StringUtil::builderAppendQuotedString(*output, m_stringValue );
185177}
186178
187179std::unique_ptr<Value> StringValue::clone() const
@@ -336,7 +328,7 @@ void DictionaryValue::writeJSON(StringBuilder* output) const
336328 CHECK(it != m_data.end());
337329 if (i)
338330 StringUtil::builderAppend(*output, ',');
339- doubleQuoteStringForJSON( it->first, output );
331+ StringUtil::builderAppendQuotedString(*output, it->first);
340332 StringUtil::builderAppend(*output, ':');
341333 it->second->writeJSON(output);
342334 }
@@ -402,6 +394,16 @@ protocol::Value* ListValue::at(size_t index)
402394 return m_data[index].get();
403395}
404396
397+ void escapeLatinStringForJSON(const uint8_t* str, unsigned len, StringBuilder* dst)
398+ {
399+ escapeStringForJSONInternal<uint8_t>(str, len, dst);
400+ }
401+
402+ void escapeWideStringForJSON(const uint16_t* str, unsigned len, StringBuilder* dst)
403+ {
404+ escapeStringForJSONInternal<uint16_t>(str, len, dst);
405+ }
406+
405407{% for namespace in config.protocol.namespace %}
406408} // namespace {{namespace}}
407409{% endfor %}
0 commit comments