From 6810f9a03a4ab952d05636de14b5dcfcf88f323c Mon Sep 17 00:00:00 2001 From: MihailRis Date: Sun, 23 Nov 2025 19:52:49 +0300 Subject: [PATCH] add utf8.escape_xml and alias - string.escape_xml --- res/modules/internal/extensions/string.lua | 1 + src/logic/scripting/lua/libs/libutf8.cpp | 6 +++++ src/util/stringutil.cpp | 27 ++++++++++++++++++++++ src/util/stringutil.hpp | 3 +++ 4 files changed, 37 insertions(+) diff --git a/res/modules/internal/extensions/string.lua b/res/modules/internal/extensions/string.lua index f76470df..313ae57b 100644 --- a/res/modules/internal/extensions/string.lua +++ b/res/modules/internal/extensions/string.lua @@ -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("") diff --git a/src/logic/scripting/lua/libs/libutf8.cpp b/src/logic/scripting/lua/libs/libutf8.cpp index e6538c2e..eb4c1065 100644 --- a/src/logic/scripting/lua/libs/libutf8.cpp +++ b/src/logic/scripting/lua/libs/libutf8.cpp @@ -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}, {"tostring", lua::wrap}, @@ -98,5 +103,6 @@ const luaL_Reg utf8lib[] = { {"lower", lua::wrap}, {"encode", lua::wrap}, {"escape", lua::wrap}, + {"escape_xml", lua::wrap}, {nullptr, nullptr} }; diff --git a/src/util/stringutil.cpp b/src/util/stringutil.cpp index 63271a13..01a32c9d 100644 --- a/src/util/stringutil.cpp +++ b/src/util/stringutil.cpp @@ -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 << "&"; + break; + case '<': + ss << "<"; + break; + case '>': + ss << ">"; + break; + case '"': + ss << """; + break; + case '\'': + ss << "'"; + break; + default: + ss << c; + break; + } + } + return ss.str(); +} + std::string util::quote(const std::string& s) { return escape(s, false); } diff --git a/src/util/stringutil.hpp b/src/util/stringutil.hpp index 3d8bf16e..b005380a 100644 --- a/src/util/stringutil.hpp +++ b/src/util/stringutil.hpp @@ -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);