COMMON: Add U32String version of toPrintable

This only escapes ASCII control characters, not characters wih
codepoints > 127.
This commit is contained in:
djsrv 2021-07-12 14:54:47 -04:00
parent 0c053d20ba
commit e6a5380989
2 changed files with 49 additions and 0 deletions

View File

@ -267,4 +267,41 @@ char* U32String::itoa(int num, char* str, int base) {
return str;
}
U32String toPrintable(const U32String &in, bool keepNewLines) {
U32String res;
const char *tr = "\x01\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 u32char_type_t *p = in.c_str(); *p; p++) {
if (*p == '\n') {
if (keepNewLines)
res += *p;
else
res += U32String("\\n");
continue;
}
if (*p < 0x20 || *p == '\'' || *p == '\"' || *p == '\\') {
res += '\\';
if (*p < 0x20) {
if (tr[*p] < 0x20)
res += Common::String::format("x%02x", *p);
else
res += tr[*p];
} else {
res += *p; // We will escape it
}
} else
res += *p;
}
return res;
}
} // End of namespace Common

View File

@ -200,6 +200,18 @@ U32String operator+(const U32String &x, const U32String &y);
/** Append the given @p y character to the given @p x string. */
U32String operator+(const U32String &x, U32String::value_type y);
/**
* Converts string with all non-printable characters properly escaped
* with use of C++ escape sequences.
* Unlike the String version, this does not escape characters with
* codepoints > 127.
*
* @param src The source string.
* @param keepNewLines Whether keep newlines or convert them to '\n', default: true.
* @return The converted string.
*/
U32String toPrintable(const U32String &src, bool keepNewLines = true);
/** @} */
} // End of namespace Common