From b2da75ca3304e377c7da3c3ee287f393ad90dc07 Mon Sep 17 00:00:00 2001 From: Nils Maier Date: Sat, 24 Aug 2013 21:54:56 +0200 Subject: [PATCH] Optimize htmlEscape implementation a bit --- src/util.cc | 41 ++++++++++++++++++++++++----------------- 1 file changed, 24 insertions(+), 17 deletions(-) diff --git a/src/util.cc b/src/util.cc index 4f5cbd92..3633fbd3 100644 --- a/src/util.cc +++ b/src/util.cc @@ -1533,25 +1533,32 @@ getNumericNameInfo(const struct sockaddr* sockaddr, socklen_t len) std::string htmlEscape(const std::string& src) { - std::string dest; - for(std::string::const_iterator i = src.begin(), eoi = src.end(); - i != eoi; ++i) { - char ch = *i; - if(ch == '<') { - dest += "<"; - } else if(ch == '>') { - dest += ">"; - } else if(ch == '&') { - dest += "&"; - } else if(ch == '\'') { - dest += "'"; - } else if(ch == '"') { - dest += """; - } else { - dest += ch; + std::string rv(src); + std::string::size_type pos = 0; + while ((pos = rv.find_first_of("<>&\"'", pos)) != std::string::npos) { + auto ch = rv[pos]; + if (ch == '<') { + rv.replace(pos, 1, "<"); + pos += 4; + } + else if (ch == '>') { + rv.replace(pos, 1, ">"); + pos += 4; + } + else if (ch == '&') { + rv.replace(pos, 1, "&"); + pos += 5; + } + else if (ch == '"') { + rv.replace(pos, 1, """); + pos += 6; + } + else { // '\'' + rv.replace(pos, 1, "'"); + pos += 5; } } - return dest; + return rv; } std::pair