add utf8.escape_xml and alias - string.escape_xml

This commit is contained in:
MihailRis 2025-11-23 19:52:49 +03:00
parent 91cb5ab7d8
commit 6810f9a03a
4 changed files with 37 additions and 0 deletions

View File

@ -105,6 +105,7 @@ end
string.lower = utf8.lower
string.upper = utf8.upper
string.escape = utf8.escape
string.escape_xml = utf8.escape_xml
local meta = getmetatable("")

View File

@ -88,6 +88,11 @@ static int l_escape(lua::State* L) {
return lua::pushstring(L, util::escape(string));
}
static int l_escape_xml(lua::State* L) {
auto string = lua::require_lstring(L, 1);
return lua::pushstring(L, util::escape_xml(string));
}
const luaL_Reg utf8lib[] = {
{"tobytes", lua::wrap<l_tobytes>},
{"tostring", lua::wrap<l_tostring>},
@ -98,5 +103,6 @@ const luaL_Reg utf8lib[] = {
{"lower", lua::wrap<l_lower>},
{"encode", lua::wrap<l_encode>},
{"escape", lua::wrap<l_escape>},
{"escape_xml", lua::wrap<l_escape_xml>},
{nullptr, nullptr}
};

View File

@ -60,6 +60,33 @@ std::string util::escape(std::string_view s, bool escapeUnicode) {
return ss.str();
}
std::string util::escape_xml(std::string_view s) {
std::stringstream ss;
for (char c : s) {
switch (c) {
case '&':
ss << "&amp;";
break;
case '<':
ss << "&lt;";
break;
case '>':
ss << "&gt;";
break;
case '"':
ss << "&quot;";
break;
case '\'':
ss << "&apos;";
break;
default:
ss << c;
break;
}
}
return ss.str();
}
std::string util::quote(const std::string& s) {
return escape(s, false);
}

View File

@ -10,6 +10,9 @@ namespace util {
/// @brief Function used for string serialization in text formats
std::string escape(std::string_view s, bool escapeUnicode=true);
/// @brief Escape all special XML characters
std::string escape_xml(std::string_view s);
/// @brief Function used for error messages
std::string quote(const std::string& s);