From c9a4690d0cbeb849df6ff4deac96f885924be64c Mon Sep 17 00:00:00 2001 From: Jason Volk Date: Mon, 21 Jan 2019 14:21:13 -0800 Subject: [PATCH] ircd::json: Add escape mapping; unify the string generators. --- ircd/json.cc | 41 ++++++++++++++++++++++++++--------------- 1 file changed, 26 insertions(+), 15 deletions(-) diff --git a/ircd/json.cc b/ircd/json.cc index 9a78aad29..7544a0fff 100644 --- a/ircd/json.cc +++ b/ircd/json.cc @@ -211,19 +211,31 @@ struct ircd::json::output ,"number" }; - rule quoted + std::map escapes { - char_('"') << *char_ << char_('"') + { '"', "\\\"" }, + { '\\', "\\\\" }, + { '\b', "\\b" }, + { '\f', "\\f" }, + { '\n', "\\n" }, + { '\r', "\\r" }, + { '\t', "\\t" }, + { '\0', "\\0" }, }; - rule unquoted + karma::symbols escaped { - quote << *char_ << quote + "escaped" + }; + + rule character + { + escaped | char_ }; rule string { - quoted | unquoted + quote << *(character) << quote ,"string" }; @@ -263,7 +275,10 @@ struct ircd::json::output output() :output::base_type{rule<>{}} - {} + { + for(const auto &p : escapes) + escaped.add(p.first, p.second); + } }; struct ircd::json::expectation_failure @@ -2354,11 +2369,7 @@ ircd::json::stringify(mutable_buffer &buf, break; } - if(surrounds(sv, '"')) - printer(buf, printer.quoted, sv); - else - printer(buf, printer.unquoted, sv); - + printer(buf, printer.string, sv); break; } @@ -2498,11 +2509,11 @@ ircd::json::serialized(const value &v) if(v.serial) return v.len; - size_t ret(v.len); + thread_local char test_buffer[value::max_string_size]; const string_view sv{v.string, v.len}; - ret += !startswith(sv, '"'); - ret += !endswith(sv, '"'); - return ret; + mutable_buffer buf{test_buffer}; + printer(buf, printer.string, sv); + return begin(buf) - test_buffer; } };