Skip to content

Commit e2db48d

Browse files
vvishflexferrum
authored andcommitted
Reduced overhead of escaping special characters in json serializer (#142) (#191)
1 parent 0cb13c8 commit e2db48d

File tree

1 file changed

+23
-8
lines changed

1 file changed

+23
-8
lines changed

src/serialize_filters.cpp

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,6 @@
66
#include "value_helpers.h"
77
#include "value_visitors.h"
88

9-
#include <boost/algorithm/string/replace.hpp>
10-
119
#include <algorithm>
1210
#include <numeric>
1311
#include <random>
@@ -143,13 +141,30 @@ InternalValue Serialize::Filter(const InternalValue& value, RenderContext& conte
143141
const auto indent = ConvertToInt(this->GetArgumentValue("indent", context));
144142
jinja2::rapidjson_serializer::DocumentWrapper jsonDoc;
145143
const auto jsonValue = jsonDoc.CreateValue(value);
146-
auto jsonString = jsonValue.AsString(static_cast<uint8_t>(indent));
147-
boost::algorithm::replace_all(jsonString, "'", "\\u0027");
148-
boost::algorithm::replace_all(jsonString, "<", "\\u003c");
149-
boost::algorithm::replace_all(jsonString, ">", "\\u003e");
150-
boost::algorithm::replace_all(jsonString, "&", "\\u0026");
144+
const auto jsonString = jsonValue.AsString(static_cast<uint8_t>(indent));
145+
const auto result = std::accumulate(jsonString.begin(), jsonString.end(), ""s, [](const auto &str, const auto &c)
146+
{
147+
switch (c)
148+
{
149+
case '<':
150+
return str + "\\u003c";
151+
break;
152+
case '>':
153+
return str +"\\u003e";
154+
break;
155+
case '&':
156+
return str +"\\u0026";
157+
break;
158+
case '\'':
159+
return str +"\\u0027";
160+
break;
161+
default:
162+
return str + c;
163+
break;
164+
}
165+
});
151166

152-
return jsonString;
167+
return result;
153168
}
154169

155170
return InternalValue();

0 commit comments

Comments
 (0)