From eb0c4427635b51108b681e55542506187dded24d Mon Sep 17 00:00:00 2001 From: nautaa <870284156@qq.com> Date: Tue, 1 Dec 2020 16:32:09 +0800 Subject: [PATCH] add function to escape charaters for HTML --- src/IO/WriteHelpers.h | 53 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/src/IO/WriteHelpers.h b/src/IO/WriteHelpers.h index 201dbb30a86..b0c894d046e 100644 --- a/src/IO/WriteHelpers.h +++ b/src/IO/WriteHelpers.h @@ -581,6 +581,59 @@ void writeCSVString(const StringRef & s, WriteBuffer & buf) writeCSVString(s.data, s.data + s.size, buf); } +inline void writeHTMLString(const char * begin, const char * end, WriteBuffer & buf) +{ + const char * pos = begin; + while (true) + { + const char * next_pos = find_first_symbols<'<', '&', '>', '"', '\''>(pos, end); + + if (next_pos == end) + { + buf.write(pos, end - pos); + break; + } + else if (*next_pos == '<') + { + buf.write(pos, next_pos - pos); + ++next_pos; + writeCString("<", buf); + } + else if (*next_pos == '&') + { + buf.write(pos, next_pos - pos); + ++next_pos; + writeCString("&", buf); + }else if (*next_pos == '>') + { + buf.write(pos, next_pos - pos); + ++next_pos; + writeCString(">", buf); + }else if (*next_pos == '"') + { + buf.write(pos, next_pos - pos); + ++next_pos; + writeCString(""", buf); + }else if (*next_pos == '\'') + { + buf.write(pos, next_pos - pos); + ++next_pos; + writeCString("'", buf); + } + + pos = next_pos; + } +} + +inline void writeHTMLString(const String & s, WriteBuffer & buf) +{ + writeHTMLString(s.data(), s.data() + s.size(), buf); +} + +inline void writeHTMLString(const StringRef & s, WriteBuffer & buf) +{ + writeHTMLString(s.data, s.data + s.size, buf); +} /// Writing a string to a text node in XML (not into an attribute - otherwise you need more escaping). inline void writeXMLString(const char * begin, const char * end, WriteBuffer & buf)