diff options
Diffstat (limited to 'common')
-rw-r--r-- | common/str.cpp | 37 | ||||
-rw-r--r-- | common/str.h | 9 |
2 files changed, 46 insertions, 0 deletions
diff --git a/common/str.cpp b/common/str.cpp index 383a61a687..95b13be2aa 100644 --- a/common/str.cpp +++ b/common/str.cpp @@ -1094,6 +1094,43 @@ size_t strnlen(const char *src, size_t maxSize) { return counter; } +String toPrintable(const String &in, bool keepNewLines) { + Common::String res; + + const char *tr = "\x01\x02\x03\x04\x05\x06" "a" + //"\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f"; + "b" "t" "n" "v" "f" "r\x0e\x0f" + "\x10\x11\x12\x13\x14\x15\x16\x17" + "\x18\x19\x1a" "e\x1c\x1d\x1e\x1f"; + + for (const char *p = in.c_str(); *p; p++) { + if (*p == '\n') { + if (keepNewLines) + res += *p; + else + res += "\\n"; + + continue; + } + + if (*p < 0x20 || *p == '\'' || *p == '\"' || *p == '\\') { + res += '\\'; + + if (*p < 0x20) { + if (tr[*p + 1] < 0x20) + res += Common::String::format("x%02x", *p); + else + res += tr[*p + 1]; + } else { + res += *p; // We will escape it + } + } else + res += *p; + } + + return res; +} + } // End of namespace Common // Portable implementation of stricmp / strcasecmp / strcmpi. diff --git a/common/str.h b/common/str.h index 2c6c142a73..811214bac6 100644 --- a/common/str.h +++ b/common/str.h @@ -491,6 +491,15 @@ size_t strnlen(const char *src, size_t maxSize); */ #define tag2str(x) Common::tag2string(x).c_str() +/** + * Converts string with all non-printable characters properly escaped + * with use of C++ escape sequences + * + * @param src The source string. + * @param keepNewLines Whether keep newlines or convert them to '\n', default: true. + * @return The converted string. + */ +String toPrintable(const String &src, bool keepNewLines = true); } // End of namespace Common |