From 5f1ca6b55684c4f27ed96fc4309e7bb9ac515e16 Mon Sep 17 00:00:00 2001 From: Hans Kunkell Date: Thu, 6 Aug 2020 08:32:17 +0900 Subject: [PATCH] new method: makeStringSafeForPropertyName, replaces invalid chars --- simgear/misc/strutils.cxx | 32 ++++++++++++++++++++++++++++++++ simgear/misc/strutils.hxx | 4 +++- simgear/misc/strutils_test.cxx | 8 +++++++- 3 files changed, 42 insertions(+), 2 deletions(-) diff --git a/simgear/misc/strutils.cxx b/simgear/misc/strutils.cxx index 21f0ed47..36d20418 100644 --- a/simgear/misc/strutils.cxx +++ b/simgear/misc/strutils.cxx @@ -267,6 +267,38 @@ namespace simgear { return do_strip( s, BOTHSTRIP ); } + string makeStringSafeForPropertyName(const std::string& str) + { + // This function replaces all characters in 'str' that are not + // alphanumeric or '-'. + // TODO: make the function multibyte safe. + string res = str; + + int index = 0; + for (char& c : res) { + if (!std::isalpha(c) && !std::isdigit(c) && c != '-') { + switch (c) { + case ' ': + case '\t': + case '\n': + case '\r': + case '_': + case '.': + case '/': + case '\\': + res[index] = '-'; + break; + default: + res[index] = '_'; + SG_LOG(SG_GENERAL, SG_WARN, "makeStringSafeForPropertyName: Modified '" << str << "' to '" << res << "'"); + } + } + index++; + } + + return res; + } + void stripTrailingNewlines_inplace(string& s) { diff --git a/simgear/misc/strutils.hxx b/simgear/misc/strutils.hxx index 81e6afd0..6175e2a1 100644 --- a/simgear/misc/strutils.hxx +++ b/simgear/misc/strutils.hxx @@ -75,7 +75,9 @@ namespace simgear { std::string rstrip( const std::string& s ); std::string strip( const std::string& s ); - /** + std::string makeStringSafeForPropertyName(const std::string& str); + + /** * Return a new string with any trailing \\r and \\n characters removed. * Typically useful to clean a CR-terminated line obtained from * std::getline() which, upon reading CRLF (\\r\\n), discards the Line diff --git a/simgear/misc/strutils_test.cxx b/simgear/misc/strutils_test.cxx index d1c6f522..988978aa 100644 --- a/simgear/misc/strutils_test.cxx +++ b/simgear/misc/strutils_test.cxx @@ -737,6 +737,11 @@ void testDecodeHex() SG_VERIFY(decoded == data1); } +void test_makeStringSafeForPropertyName() +{ + SG_CHECK_EQUAL(strutils::makeStringSafeForPropertyName(" ABC/01234\t:\\\"_*$"), "-ABC-01234-_-_-__"); +} + int main(int argc, char* argv[]) { test_strip(); @@ -761,6 +766,7 @@ int main(int argc, char* argv[]) test_formatGeod(); test_iequals(); testDecodeHex(); - + test_makeStringSafeForPropertyName(); + return EXIT_SUCCESS; }