From 47c6bc20f41fb5443fe8ab12dadf8e5c85b955d8 Mon Sep 17 00:00:00 2001 From: antao Date: Mon, 8 Jul 2019 13:49:01 +0800 Subject: [PATCH] Optimize the htmlTranslate method --- examples/simple_example/api_v1_ApiTest.cc | 4 +-- lib/inc/drogon/HttpViewData.h | 35 +++++++++++++++++++++++ lib/src/HttpViewData.cc | 23 +++++++++------ 3 files changed, 51 insertions(+), 11 deletions(-) diff --git a/examples/simple_example/api_v1_ApiTest.cc b/examples/simple_example/api_v1_ApiTest.cc index 1576315e..d875640a 100644 --- a/examples/simple_example/api_v1_ApiTest.cc +++ b/examples/simple_example/api_v1_ApiTest.cc @@ -44,9 +44,9 @@ void ApiTest::your_method_name( std::map para; para["p1"] = std::to_string(p1); para["p2"] = std::to_string(p2); - para["p3"] = HttpViewData::htmlTranslate( + para["p3"] = HttpViewData::htmlTranslate(string_view( ""); + "box.\");")); data.insert("parameters", para); auto res = HttpResponse::newHttpViewResponse("ListParaView", data); callback(res); diff --git a/lib/inc/drogon/HttpViewData.h b/lib/inc/drogon/HttpViewData.h index 1ce71094..6c8db311 100644 --- a/lib/inc/drogon/HttpViewData.h +++ b/lib/inc/drogon/HttpViewData.h @@ -136,6 +136,41 @@ class HttpViewData * > --> > */ static std::string htmlTranslate(const std::string &str); + static std::string htmlTranslate(const string_view &str); + static bool needTranslation(const std::string &str) + { + for (auto const &c : str) + { + switch (c) + { + case '"': + case '&': + case '<': + case '>': + return true; + default: + continue; + } + } + return false; + } + static bool needTranslation(const string_view &str) + { + for (auto const &c : str) + { + switch (c) + { + case '"': + case '&': + case '<': + case '>': + return true; + default: + continue; + } + } + return false; + } protected: typedef std::unordered_map ViewDataMap; diff --git a/lib/src/HttpViewData.cc b/lib/src/HttpViewData.cc index 757ab8aa..ad990130 100644 --- a/lib/src/HttpViewData.cc +++ b/lib/src/HttpViewData.cc @@ -17,24 +17,29 @@ using namespace drogon; std::string HttpViewData::htmlTranslate(const std::string &str) +{ + return htmlTranslate(string_view(str)); +} + +std::string HttpViewData::htmlTranslate(const string_view &str) { std::string ret; - ret.reserve(str.length()); + ret.reserve(str.length() + 64); for (auto &ch : str) { switch (ch) { case '"': - ret.append("""); - break; - case '<': - ret.append("<"); - break; - case '>': - ret.append(">"); + ret.append(""", 6); break; case '&': - ret.append("&"); + ret.append("&", 5); + break; + case '<': + ret.append("<", 4); + break; + case '>': + ret.append(">", 4); break; default: ret.push_back(ch);