QTest: Extract Method writePrettyUnicodeChar from toPrettyUnicode

Easier to reason about by separating the concerns into separate
functions.

Pick-to: 6.6 6.5
Change-Id: I34666766ac2879577faea17bbd2b700bcb803f51
Reviewed-by: Jason McDonald <macadder1@gmail.com>
This commit is contained in:
Marc Mutz 2023-12-06 02:41:24 +01:00
parent 0a86a77e5f
commit f395934419

View File

@ -1697,37 +1697,24 @@ char *toPrettyCString(const char *p, qsizetype length)
*/ */
constexpr qsizetype PrettyUnicodeMaxOutputSize = 256; constexpr qsizetype PrettyUnicodeMaxOutputSize = 256;
// escape sequence, closing quote, the three dots and NUL
constexpr qsizetype PrettyUnicodeMaxIncrement = sizeof(R"(\uXXXX"...)"); // includes NUL
char *toPrettyUnicode(QStringView string) static char *writePrettyUnicodeChar(char16_t ch, char * const buffer)
{ {
auto p = string.utf16(); auto dst = buffer;
auto length = string.size(); auto first = [&](int n) { Q_ASSERT(dst - buffer == n); return dst; };
// keep it simple for the vast majority of cases if (ch < 0x7f && ch >= 0x20 && ch != '\\' && ch != '"') {
bool trimmed = false; *dst++ = ch;
auto buffer = std::make_unique<char[]>(PrettyUnicodeMaxOutputSize); return first(1);
const auto end = p + length;
char *dst = buffer.get();
*dst++ = '"';
for ( ; p != end; ++p) {
// escape sequence, closing quote, the three dots and NUL
constexpr qsizetype MaxIncrement = sizeof(R"(\uXXXX"...)"); // includes NUL
if (dst - buffer.get() > PrettyUnicodeMaxOutputSize - MaxIncrement) {
trimmed = true;
break;
}
if (*p < 0x7f && *p >= 0x20 && *p != '\\' && *p != '"') {
*dst++ = *p;
continue;
} }
// write as an escape sequence // write as an escape sequence
*dst++ = '\\'; *dst++ = '\\';
switch (*p) { switch (ch) {
case 0x22: case 0x22:
case 0x5c: case 0x5c:
*dst++ = uchar(*p); *dst++ = uchar(ch);
break; break;
case 0x8: case 0x8:
*dst++ = 'b'; *dst++ = 'b';
@ -1746,11 +1733,32 @@ char *toPrettyUnicode(QStringView string)
break; break;
default: default:
*dst++ = 'u'; *dst++ = 'u';
*dst++ = toHexUpper(*p >> 12); *dst++ = toHexUpper(ch >> 12);
*dst++ = toHexUpper(*p >> 8); *dst++ = toHexUpper(ch >> 8);
*dst++ = toHexUpper(*p >> 4); *dst++ = toHexUpper(ch >> 4);
*dst++ = toHexUpper(*p); *dst++ = toHexUpper(ch);
return first(6);
} }
return first(2);
}
char *toPrettyUnicode(QStringView string)
{
auto p = string.utf16();
auto length = string.size();
// keep it simple for the vast majority of cases
bool trimmed = false;
auto buffer = std::make_unique<char[]>(PrettyUnicodeMaxOutputSize);
const auto end = p + length;
char *dst = buffer.get();
*dst++ = '"';
for ( ; p != end; ++p) {
if (dst - buffer.get() > PrettyUnicodeMaxOutputSize - PrettyUnicodeMaxIncrement) {
trimmed = true;
break;
}
dst = writePrettyUnicodeChar(*p, dst);
} }
*dst++ = '"'; *dst++ = '"';