From 6b6dc218133f406c89ca6446dcaa5ba68f464c2a Mon Sep 17 00:00:00 2001 From: Eugene Sandulenko Date: Mon, 9 Dec 2019 21:59:49 +0100 Subject: COMMON: Added helper function to produce printable strings --- common/str.cpp | 37 +++++++++++++++++++++++++++++++++++++ common/str.h | 9 +++++++++ 2 files changed, 46 insertions(+) (limited to 'common') 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 -- cgit v1.2.3