From a15cdeae6ee61a4304890400c647137db6afc049 Mon Sep 17 00:00:00 2001 From: Maxime Coste Date: Mon, 7 Mar 2016 22:38:37 +0000 Subject: [PATCH] Fix json escaping of strings --- src/json_ui.cc | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/src/json_ui.cc b/src/json_ui.cc index eb576094..ee90eaa0 100644 --- a/src/json_ui.cc +++ b/src/json_ui.cc @@ -29,7 +29,31 @@ template String to_json(const Vector& vec) { return to_json(ArrayView{vec}); } String to_json(int i) { return to_string(i); } -String to_json(StringView s) { return format(R"("{}")", escape(s, "\"", '\\')); } +String to_json(StringView str) +{ + String res; + res.reserve(str.length() + 4); + res += '"'; + for (auto it = str.begin(), end = str.end(); it != end; ) + { + auto next = std::find_if(it, end, [](char c) { + return c == '\\' or c == '"' or (c >= 0 and c <= 0x1F); + }); + + res += StringView{it, next}; + if (next == end) + break; + + char buf[7] = {'\\', *next, 0}; + if (*next >= 0 and *next <= 0x1F) + sprintf(buf, "\\u%04x", *next); + + res += buf; + it = next+1; + } + res += '"'; + return res; +} String to_json(Color color) {