1// Copyright (C) 2016 The Qt Company Ltd.
2// Copyright (C) 2016 Intel Corporation.
3// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
4
5#ifdef QT_NO_DEBUG
6#undef QT_NO_DEBUG
7#endif
8#ifdef qDebug
9#undef qDebug
10#endif
11
12#include "qdebug.h"
13#include "private/qdebug_p.h"
14#include "qmetaobject.h"
15#include <private/qtextstream_p.h>
16#include <private/qtools_p.h>
17
18#include <q20chrono.h>
19
20QT_BEGIN_NAMESPACE
21
22using namespace QtMiscUtils;
23
24/*
25 Returns a human readable representation of the first \a maxSize
26 characters in \a data. The size, \a len, is a 64-bit quantity to
27 avoid truncation due to implicit conversions in callers.
28*/
29QByteArray QtDebugUtils::toPrintable(const char *data, qint64 len, qsizetype maxSize)
30{
31 if (!data)
32 return "(null)";
33
34 QByteArray out;
35 for (qsizetype i = 0; i < qMin(a: len, b: maxSize); ++i) {
36 char c = data[i];
37 if (isAsciiPrintable(ch: c)) {
38 out += c;
39 } else {
40 switch (c) {
41 case '\n':
42 out += "\\n";
43 break;
44 case '\r':
45 out += "\\r";
46 break;
47 case '\t':
48 out += "\\t";
49 break;
50 default: {
51 const char buf[] = {
52 '\\',
53 'x',
54 toHexLower(value: uchar(c) / 16),
55 toHexLower(value: uchar(c) % 16),
56 0
57 };
58 out += buf;
59 }
60 }
61 }
62 }
63
64 if (maxSize < len)
65 out += "...";
66
67 return out;
68}
69
70// This file is needed to force compilation of QDebug into the kernel library.
71
72/*!
73 \class QDebug
74 \inmodule QtCore
75 \ingroup shared
76
77 \brief The QDebug class provides an output stream for debugging information.
78
79 QDebug is used whenever the developer needs to write out debugging or tracing
80 information to a device, file, string or console.
81
82 \section1 Basic Use
83
84 In the common case, it is useful to call the qDebug() function to obtain a
85 default QDebug object to use for writing debugging information.
86
87 \snippet qdebug/qdebugsnippet.cpp 1
88
89 This constructs a QDebug object using the constructor that accepts a QtMsgType
90 value of QtDebugMsg. Similarly, the qWarning(), qCritical() and qFatal()
91 functions also return QDebug objects for the corresponding message types.
92
93 The class also provides several constructors for other situations, including
94 a constructor that accepts a QFile or any other QIODevice subclass that is
95 used to write debugging information to files and other devices. The constructor
96 that accepts a QString is used to write to a string for display or serialization.
97
98 \section1 Formatting Options
99
100 QDebug formats output so that it's easily readable. It automatically adds spaces
101 between arguments, and adds quotes around QString, QByteArray, QChar arguments.
102
103 You can tweak these options through the space(), nospace() and quote(), noquote()
104 methods. Furthermore, \l{QTextStream manipulators} can be piped into a QDebug
105 stream.
106
107 QDebugStateSaver limits changes to the formatting to the current scope.
108 resetFormat() resets the options to the default ones.
109
110 \section1 Writing Custom Types to a Stream
111
112 Many standard types can be written to QDebug objects, and Qt provides support for
113 most Qt value types. To add support for custom types, you need to implement a
114 streaming operator, as in the following example:
115
116 \snippet qdebug/qdebugsnippet.cpp 0
117
118 This is described in the \l{Debugging Techniques} and
119 \l{Creating Custom Qt Types#Making the Type Printable}{Creating Custom Qt Types}
120 documents.
121*/
122
123/*!
124 \fn QDebug::QDebug(QIODevice *device)
125
126 Constructs a debug stream that writes to the given \a device.
127*/
128
129/*!
130 \fn QDebug::QDebug(QString *string)
131
132 Constructs a debug stream that writes to the given \a string.
133*/
134
135/*!
136 \fn QDebug::QDebug(QtMsgType t)
137
138 Constructs a debug stream that writes to the handler for the message type \a t.
139*/
140
141/*!
142 \fn QDebug::QDebug(const QDebug &o)
143
144 Constructs a copy of the other debug stream \a o.
145*/
146
147/*!
148 \fn QDebug &QDebug::operator=(const QDebug &other)
149
150 Assigns the \a other debug stream to this stream and returns a reference to
151 this stream.
152*/
153
154/*!
155 \fn QDebug::~QDebug()
156
157 Flushes any pending data to be written and destroys the debug stream.
158*/
159// Has been defined in the header / inlined before Qt 5.4
160QDebug::~QDebug()
161{
162 if (stream && !--stream->ref) {
163 if (stream->space && stream->buffer.endsWith(c: u' '))
164 stream->buffer.chop(n: 1);
165 if (stream->message_output) {
166 qt_message_output(stream->type,
167 context: stream->context,
168 message: stream->buffer);
169 }
170 delete stream;
171 }
172}
173
174/*!
175 \internal
176*/
177void QDebug::putUcs4(uint ucs4)
178{
179 maybeQuote(c: '\'');
180 if (ucs4 < 0x20) {
181 stream->ts << "\\x" << Qt::hex << ucs4 << Qt::reset;
182 } else if (ucs4 < 0x80) {
183 stream->ts << char(ucs4);
184 } else {
185 if (ucs4 < 0x10000)
186 stream->ts << "\\u" << qSetFieldWidth(width: 4);
187 else
188 stream->ts << "\\U" << qSetFieldWidth(width: 8);
189 stream->ts << Qt::hex << qSetPadChar(ch: u'0') << ucs4 << Qt::reset;
190 }
191 maybeQuote(c: '\'');
192}
193
194// These two functions return true if the character should be printed by QDebug.
195// For QByteArray, this is technically identical to US-ASCII isprint();
196// for QString, we use QChar::isPrint, which requires a full UCS-4 decode.
197static inline bool isPrintable(char32_t ucs4) { return QChar::isPrint(ucs4); }
198static inline bool isPrintable(char16_t uc) { return QChar::isPrint(ucs4: uc); }
199static inline bool isPrintable(uchar c)
200{ return isAsciiPrintable(ch: c); }
201
202template <typename Char>
203static inline void putEscapedString(QTextStreamPrivate *d, const Char *begin, size_t length, bool isUnicode = true)
204{
205 QChar quote(u'"');
206 d->write(data: &quote, len: 1);
207
208 bool lastWasHexEscape = false;
209 const Char *end = begin + length;
210 for (const Char *p = begin; p != end; ++p) {
211 // check if we need to insert "" to break an hex escape sequence
212 if (Q_UNLIKELY(lastWasHexEscape)) {
213 if (fromHex(*p) != -1) {
214 // yes, insert it
215 QChar quotes[] = { quote, quote };
216 d->write(data: quotes, len: 2);
217 }
218 lastWasHexEscape = false;
219 }
220
221 if (sizeof(Char) == sizeof(QChar)) {
222 // Surrogate characters are category Cs (Other_Surrogate), so isPrintable = false for them
223 qsizetype runLength = 0;
224 while (p + runLength != end &&
225 isPrintable(p[runLength]) && p[runLength] != '\\' && p[runLength] != '"')
226 ++runLength;
227 if (runLength) {
228 d->write(data: reinterpret_cast<const QChar *>(p), len: runLength);
229 p += runLength - 1;
230 continue;
231 }
232 } else if (isPrintable(*p) && *p != '\\' && *p != '"') {
233 QChar c = QLatin1Char(*p);
234 d->write(data: &c, len: 1);
235 continue;
236 }
237
238 // print as an escape sequence (maybe, see below for surrogate pairs)
239 qsizetype buflen = 2;
240 char16_t buf[std::char_traits<char>::length(s: "\\U12345678")];
241 buf[0] = '\\';
242
243 switch (*p) {
244 case '"':
245 case '\\':
246 buf[1] = *p;
247 break;
248 case '\b':
249 buf[1] = 'b';
250 break;
251 case '\f':
252 buf[1] = 'f';
253 break;
254 case '\n':
255 buf[1] = 'n';
256 break;
257 case '\r':
258 buf[1] = 'r';
259 break;
260 case '\t':
261 buf[1] = 't';
262 break;
263 default:
264 if (!isUnicode) {
265 // print as hex escape
266 buf[1] = 'x';
267 buf[2] = toHexUpper(value: uchar(*p) >> 4);
268 buf[3] = toHexUpper(value: uchar(*p));
269 buflen = 4;
270 lastWasHexEscape = true;
271 break;
272 }
273 if (QChar::isHighSurrogate(*p)) {
274 if ((p + 1) != end && QChar::isLowSurrogate(p[1])) {
275 // properly-paired surrogates
276 char32_t ucs4 = QChar::surrogateToUcs4(*p, p[1]);
277 if (isPrintable(ucs4)) {
278 buf[0] = *p;
279 buf[1] = p[1];
280 buflen = 2;
281 } else {
282 buf[1] = 'U';
283 buf[2] = '0'; // toHexUpper(ucs4 >> 32);
284 buf[3] = '0'; // toHexUpper(ucs4 >> 28);
285 buf[4] = toHexUpper(value: ucs4 >> 20);
286 buf[5] = toHexUpper(value: ucs4 >> 16);
287 buf[6] = toHexUpper(value: ucs4 >> 12);
288 buf[7] = toHexUpper(value: ucs4 >> 8);
289 buf[8] = toHexUpper(value: ucs4 >> 4);
290 buf[9] = toHexUpper(value: ucs4);
291 buflen = 10;
292 }
293 ++p;
294 break;
295 }
296 // improperly-paired surrogates, fall through
297 }
298 buf[1] = 'u';
299 buf[2] = toHexUpper(value: char16_t(*p) >> 12);
300 buf[3] = toHexUpper(value: char16_t(*p) >> 8);
301 buf[4] = toHexUpper(*p >> 4);
302 buf[5] = toHexUpper(*p);
303 buflen = 6;
304 }
305 d->write(data: reinterpret_cast<QChar *>(buf), len: buflen);
306 }
307
308 d->write(data: &quote, len: 1);
309}
310
311/*!
312 \internal
313 Duplicated from QtTest::toPrettyUnicode().
314*/
315void QDebug::putString(const QChar *begin, size_t length)
316{
317 if (stream->noQuotes) {
318 // no quotes, write the string directly too (no pretty-printing)
319 // this respects the QTextStream state, though
320 stream->ts.d_ptr->putString(data: begin, len: qsizetype(length));
321 } else {
322 // we'll reset the QTextStream formatting mechanisms, so save the state
323 QDebugStateSaver saver(*this);
324 stream->ts.d_ptr->params.reset();
325 putEscapedString(d: stream->ts.d_ptr.data(), begin: reinterpret_cast<const char16_t *>(begin), length);
326 }
327}
328
329/*!
330 \internal
331 Duplicated from QtTest::toPrettyCString().
332*/
333void QDebug::putByteArray(const char *begin, size_t length, Latin1Content content)
334{
335 if (stream->noQuotes) {
336 // no quotes, write the string directly too (no pretty-printing)
337 // this respects the QTextStream state, though
338 QString string = content == ContainsLatin1 ? QString::fromLatin1(str: begin, size: qsizetype(length))
339 : QString::fromUtf8(utf8: begin, size: qsizetype(length));
340 stream->ts.d_ptr->putString(string);
341 } else {
342 // we'll reset the QTextStream formatting mechanisms, so save the state
343 QDebugStateSaver saver(*this);
344 stream->ts.d_ptr->params.reset();
345 putEscapedString(d: stream->ts.d_ptr.data(), begin: reinterpret_cast<const uchar *>(begin),
346 length, isUnicode: content == ContainsLatin1);
347 }
348}
349
350static QByteArray timeUnit(qint64 num, qint64 den)
351{
352 using namespace std::chrono;
353 using namespace q20::chrono;
354
355 if (num == 1 && den > 1) {
356 // sub-multiple of seconds
357 char prefix = '\0';
358 auto tryprefix = [&](auto d, char c) {
359 static_assert(decltype(d)::num == 1, "not an SI prefix");
360 if (den == decltype(d)::den)
361 prefix = c;
362 };
363
364 // "u" should be "µ", but debugging output is not always UTF-8-safe
365 tryprefix(std::milli{}, 'm');
366 tryprefix(std::micro{}, 'u');
367 tryprefix(std::nano{}, 'n');
368 tryprefix(std::pico{}, 'p');
369 tryprefix(std::femto{}, 'f');
370 tryprefix(std::atto{}, 'a');
371 // uncommon ones later
372 tryprefix(std::centi{}, 'c');
373 tryprefix(std::deci{}, 'd');
374 if (prefix) {
375 char unit[3] = { prefix, 's' };
376 return QByteArray(unit, sizeof(unit) - 1);
377 }
378 }
379
380 const char *unit = nullptr;
381 if (num > 1 && den == 1) {
382 // multiple of seconds - but we don't use SI prefixes
383 auto tryunit = [&](auto d, const char *name) {
384 static_assert(decltype(d)::period::den == 1, "not a multiple of a second");
385 if (unit || num % decltype(d)::period::num)
386 return;
387 unit = name;
388 num /= decltype(d)::period::num;
389 };
390 tryunit(years{}, "yr");
391 tryunit(weeks{}, "wk");
392 tryunit(days{}, "d");
393 tryunit(hours{}, "h");
394 tryunit(minutes{}, "min");
395 }
396 if (!unit)
397 unit = "s";
398
399 if (num == 1 && den == 1)
400 return unit;
401 if (Q_UNLIKELY(num < 1 || den < 1))
402 return QString::asprintf(format: "<invalid time unit %lld/%lld>", num, den).toLatin1();
403
404 // uncommon units: will return something like "[2/3]s"
405 // strlen("[/]min") = 6
406 char buf[2 * (std::numeric_limits<qint64>::digits10 + 2) + 10];
407 size_t len = 0;
408 auto appendChar = [&](char c) {
409 Q_ASSERT(len < sizeof(buf));
410 buf[len++] = c;
411 };
412 auto appendNumber = [&](qint64 value) {
413 if (value >= 10'000 && (value % 1000) == 0)
414 len += qsnprintf(str: buf + len, n: sizeof(buf) - len, fmt: "%.6g", double(value)); // "1e+06"
415 else
416 len += qsnprintf(str: buf + len, n: sizeof(buf) - len, fmt: "%lld", value);
417 };
418 appendChar('[');
419 appendNumber(num);
420 if (den != 1) {
421 appendChar('/');
422 appendNumber(den);
423 }
424 appendChar(']');
425 memcpy(dest: buf + len, src: unit, n: strlen(s: unit));
426 return QByteArray(buf, len + strlen(s: unit));
427}
428
429/*!
430 \since 6.6
431 \internal
432 Helper to the std::chrono::duration debug streaming output.
433 */
434void QDebug::putTimeUnit(qint64 num, qint64 den)
435{
436 stream->ts << timeUnit(num, den); // ### optimize
437}
438
439/*!
440 \fn QDebug::swap(QDebug &other)
441 \since 5.0
442
443 Swaps this debug stream instance with \a other. This function is
444 very fast and never fails.
445*/
446
447/*!
448 Resets the stream formatting options, bringing it back to its original constructed state.
449
450 \sa space(), quote()
451 \since 5.4
452*/
453QDebug &QDebug::resetFormat()
454{
455 stream->ts.reset();
456 stream->space = true;
457 stream->noQuotes = false;
458 stream->verbosity = DefaultVerbosity;
459 return *this;
460}
461
462/*!
463 \fn QDebug &QDebug::space()
464
465 Writes a space character to the debug stream and returns a reference to
466 the stream.
467
468 The stream remembers that automatic insertion of spaces is
469 enabled for future writes.
470
471 \sa nospace(), maybeSpace()
472*/
473
474/*!
475 \fn QDebug &QDebug::nospace()
476
477 Disables automatic insertion of spaces and returns a reference to the stream.
478
479 \sa space(), maybeSpace()
480*/
481
482/*!
483 \fn QDebug &QDebug::maybeSpace()
484
485 Writes a space character to the debug stream, depending on the current
486 setting for automatic insertion of spaces, and returns a reference to the stream.
487
488 \sa space(), nospace()
489*/
490
491/*!
492 \fn bool QDebug::autoInsertSpaces() const
493
494 Returns \c true if this QDebug instance will automatically insert spaces
495 between writes.
496
497 \since 5.0
498
499 \sa QDebugStateSaver
500*/
501
502/*!
503 \fn void QDebug::setAutoInsertSpaces(bool b)
504
505 Enables automatic insertion of spaces between writes if \a b is true; otherwise
506 automatic insertion of spaces is disabled.
507
508 \since 5.0
509
510 \sa QDebugStateSaver
511*/
512
513
514/*!
515 \fn QDebug &QDebug::quote()
516 \since 5.4
517
518 Enables automatic insertion of quotation characters around QChar, QString and QByteArray
519 contents and returns a reference to the stream.
520
521 Quoting is enabled by default.
522
523 \sa noquote(), maybeQuote()
524*/
525
526/*!
527 \fn QDebug &QDebug::noquote()
528 \since 5.4
529
530 Disables automatic insertion of quotation characters around QChar, QString and QByteArray
531 contents and returns a reference to the stream.
532
533 When quoting is disabled, these types are printed without quotation
534 characters and without escaping of non-printable characters.
535
536 \sa quote(), maybeQuote()
537*/
538
539/*!
540 \fn QDebug &QDebug::maybeQuote(char c)
541 \since 5.4
542
543 Writes a character \a c to the debug stream, depending on the
544 current setting for automatic insertion of quotes, and returns a reference to the stream.
545
546 The default character is a double quote \c{"}.
547
548 \sa quote(), noquote()
549*/
550
551/*!
552 \fn int QDebug::verbosity() const
553 \since 5.6
554
555 Returns the verbosity of the debug stream.
556
557 Streaming operators can check the value to decide whether
558 verbose output is desired and print more information depending on the
559 level. Higher values indicate that more information is desired.
560
561 The allowed range is from 0 to 7. The default value is 2.
562
563 \sa setVerbosity(), VerbosityLevel
564*/
565
566/*!
567 \fn void QDebug::setVerbosity(int verbosityLevel)
568 \since 5.6
569
570 Sets the verbosity of the stream to \a verbosityLevel.
571
572 The allowed range is from 0 to 7. The default value is 2.
573
574 \sa verbosity(), VerbosityLevel
575*/
576
577/*!
578 \fn QDebug &QDebug::verbosity(int verbosityLevel)
579 \since 5.13
580
581 Sets the verbosity of the stream to \a verbosityLevel and returns a reference to the stream.
582
583 The allowed range is from 0 to 7. The default value is 2.
584
585 \sa verbosity(), setVerbosity(), VerbosityLevel
586*/
587
588/*!
589 \enum QDebug::VerbosityLevel
590 \since 5.13
591
592 This enum describes the range of verbosity levels.
593
594 \value MinimumVerbosity
595 \value DefaultVerbosity
596 \value MaximumVerbosity
597
598 \sa verbosity(), setVerbosity()
599*/
600
601/*!
602 \fn QDebug &QDebug::operator<<(QChar t)
603
604 Writes the character, \a t, to the stream and returns a reference to the
605 stream. Normally, QDebug prints control characters and non-US-ASCII
606 characters as their C escape sequences or their Unicode value (\\u1234). To
607 print non-printable characters without transformation, enable the noquote()
608 functionality, but note that some QDebug backends may not be 8-bit clean
609 and may not be able to represent \c t.
610*/
611
612/*!
613 \fn QDebug &QDebug::operator<<(bool t)
614
615 Writes the boolean value, \a t, to the stream and returns a reference to the
616 stream.
617*/
618
619/*!
620 \fn QDebug &QDebug::operator<<(char t)
621
622 Writes the character, \a t, to the stream and returns a reference to the
623 stream.
624*/
625
626/*!
627 \fn QDebug &QDebug::operator<<(signed short t)
628
629 Writes the signed short integer, \a t, to the stream and returns a reference
630 to the stream.
631*/
632
633/*!
634 \fn QDebug &QDebug::operator<<(unsigned short t)
635
636 Writes then unsigned short integer, \a t, to the stream and returns a
637 reference to the stream.
638*/
639
640/*!
641 \fn QDebug &QDebug::operator<<(signed int t)
642
643 Writes the signed integer, \a t, to the stream and returns a reference
644 to the stream.
645*/
646
647/*!
648 \fn QDebug &QDebug::operator<<(unsigned int t)
649
650 Writes then unsigned integer, \a t, to the stream and returns a reference to
651 the stream.
652*/
653
654/*!
655 \fn QDebug &QDebug::operator<<(signed long t)
656
657 Writes the signed long integer, \a t, to the stream and returns a reference
658 to the stream.
659*/
660
661/*!
662 \fn QDebug &QDebug::operator<<(unsigned long t)
663
664 Writes then unsigned long integer, \a t, to the stream and returns a reference
665 to the stream.
666*/
667
668/*!
669 \fn QDebug &QDebug::operator<<(qint64 t)
670
671 Writes the signed 64-bit integer, \a t, to the stream and returns a reference
672 to the stream.
673*/
674
675/*!
676 \fn QDebug &QDebug::operator<<(quint64 t)
677
678 Writes then unsigned 64-bit integer, \a t, to the stream and returns a
679 reference to the stream.
680*/
681
682/*!
683 \fn QDebug &QDebug::operator<<(float t)
684
685 Writes the 32-bit floating point number, \a t, to the stream and returns a
686 reference to the stream.
687*/
688
689/*!
690 \fn QDebug &QDebug::operator<<(double t)
691
692 Writes the 64-bit floating point number, \a t, to the stream and returns a
693 reference to the stream.
694*/
695
696/*!
697 \fn QDebug &QDebug::operator<<(const char *t)
698
699 Writes the '\\0'-terminated UTF-8 string, \a t, to the stream and returns a
700 reference to the stream. The string is never quoted or escaped for the
701 output. Note that QDebug buffers internally as UTF-16 and may need to
702 transform to 8-bit using the locale's codec in order to use some backends,
703 which may cause garbled output (mojibake). Restricting to US-ASCII strings
704 is recommended.
705*/
706
707/*!
708 \fn QDebug &QDebug::operator<<(const char16_t *t)
709 \since 6.0
710
711 Writes the u'\\0'-terminated UTF-16 string, \a t, to the stream and returns
712 a reference to the stream. The string is never quoted or escaped for the
713 output. Note that QDebug buffers internally as UTF-16 and may need to
714 transform to 8-bit using the locale's codec in order to use some backends,
715 which may cause garbled output (mojibake). Restricting to US-ASCII strings
716 is recommended.
717*/
718
719/*!
720 \fn QDebug &QDebug::operator<<(char16_t t)
721 \since 5.5
722
723 Writes the UTF-16 character, \a t, to the stream and returns a reference
724 to the stream.
725*/
726
727/*!
728 \fn QDebug &QDebug::operator<<(char32_t t)
729 \since 5.5
730
731 Writes the UTF-32 character, \a t, to the stream and returns a reference
732 to the stream.
733*/
734
735/*!
736 \fn QDebug &QDebug::operator<<(const QString &t)
737
738 Writes the string, \a t, to the stream and returns a reference to the
739 stream. Normally, QDebug prints the string inside quotes and transforms
740 non-printable characters to their Unicode values (\\u1234).
741
742 To print non-printable characters without transformation, enable the
743 noquote() functionality. Note that some QDebug backends might not be 8-bit
744 clean.
745
746 Output examples:
747 \snippet code/src_corelib_io_qdebug.cpp 0
748*/
749
750/*!
751 \since 5.10
752 \fn QDebug &QDebug::operator<<(QStringView s)
753
754 Writes the string view, \a s, to the stream and returns a reference to the
755 stream. Normally, QDebug prints the string inside quotes and transforms
756 non-printable characters to their Unicode values (\\u1234).
757
758 To print non-printable characters without transformation, enable the
759 noquote() functionality. Note that some QDebug backends might not be 8-bit
760 clean.
761
762 See the QString overload for examples.
763*/
764
765/*!
766 \since 6.0
767 \fn QDebug &QDebug::operator<<(QUtf8StringView s)
768
769 Writes the string view, \a s, to the stream and returns a reference to the
770 stream.
771
772 Normally, QDebug prints the data inside quotes and transforms control or
773 non-US-ASCII characters to their C escape sequences (\\xAB). This way, the
774 output is always 7-bit clean and the string can be copied from the output
775 and pasted back into C++ sources, if necessary.
776
777 To print non-printable characters without transformation, enable the
778 noquote() functionality. Note that some QDebug backends might not be 8-bit
779 clean.
780*/
781
782/*!
783 \fn QDebug &QDebug::operator<<(QLatin1StringView t)
784
785 Writes the string, \a t, to the stream and returns a reference to the
786 stream. Normally, QDebug prints the string inside quotes and transforms
787 non-printable characters to their Unicode values (\\u1234).
788
789 To print non-printable characters without transformation, enable the
790 noquote() functionality. Note that some QDebug backends might not be 8-bit
791 clean.
792
793 See the QString overload for examples.
794*/
795
796/*!
797 \fn QDebug &QDebug::operator<<(const QByteArray &t)
798
799 Writes the byte array, \a t, to the stream and returns a reference to the
800 stream. Normally, QDebug prints the array inside quotes and transforms
801 control or non-US-ASCII characters to their C escape sequences (\\xAB). This
802 way, the output is always 7-bit clean and the string can be copied from the
803 output and pasted back into C++ sources, if necessary.
804
805 To print non-printable characters without transformation, enable the
806 noquote() functionality. Note that some QDebug backends might not be 8-bit
807 clean.
808
809 Output examples:
810 \snippet code/src_corelib_io_qdebug.cpp 1
811
812 Note how QDebug needed to close and reopen the string in the way C and C++
813 languages concatenate string literals so that the letter 'b' is not
814 interpreted as part of the previous hexadecimal escape sequence.
815*/
816
817/*!
818 \since 6.0
819 \fn QDebug &QDebug::operator<<(QByteArrayView t)
820
821 Writes the data of the observed byte array, \a t, to the stream and returns
822 a reference to the stream.
823
824 Normally, QDebug prints the data inside quotes and transforms control or
825 non-US-ASCII characters to their C escape sequences (\\xAB). This way, the
826 output is always 7-bit clean and the string can be copied from the output
827 and pasted back into C++ sources, if necessary.
828
829 To print non-printable characters without transformation, enable the
830 noquote() functionality. Note that some QDebug backends might not be 8-bit
831 clean.
832
833 See the QByteArray overload for examples.
834*/
835
836/*!
837 \fn QDebug &QDebug::operator<<(const void *t)
838
839 Writes a pointer, \a t, to the stream and returns a reference to the stream.
840*/
841
842/*!
843 \fn QDebug &QDebug::operator<<(QTextStreamFunction f)
844 \internal
845*/
846
847/*!
848 \fn QDebug &QDebug::operator<<(QTextStreamManipulator m)
849 \internal
850*/
851
852/*!
853 \since 6.5
854 \fn template <typename Char, typename...Args> QDebug &QDebug::operator<<(const std::basic_string<Char, Args...> &s)
855 \fn template <typename Char, typename...Args> QDebug &QDebug::operator<<(std::basic_string_view<Char, Args...> s)
856
857 Writes the string or string-view \a s to the stream and returns a reference
858 to the stream.
859
860 These operators only participate in overload resolution if \c Char is one of
861 \list
862 \li char
863 \li char8_t (C++20 only)
864 \li char16_t
865 \li char32_t
866 \li wchar_t
867 \endlist
868*/
869
870/*!
871 \since 6.6
872 \fn template <typename Rep, typename Period> QDebug &QDebug::operator<<(std::chrono::duration<Rep, Period> duration)
873
874 Prints the time duration \a duration to the stream and returns a reference
875 to the stream. The printed string is the numeric representation of the
876 period followed by the time unit, similar to what the C++ Standard Library
877 would produce with \c{std::ostream}.
878
879 The unit is not localized.
880*/
881
882/*!
883 \fn template <class T> QString QDebug::toString(T &&object)
884 \since 6.0
885
886 \include qdebug-toString.qdocinc
887*/
888
889/*!
890 \fn template <class T> QDebug operator<<(QDebug debug, const QList<T> &list)
891 \relates QDebug
892
893 Writes the contents of \a list to \a debug. \c T needs to
894 support streaming into QDebug.
895*/
896
897/*!
898 \fn template <class T, qsizetype P> QDebug operator<<(QDebug debug, const QVarLengthArray<T,P> &array)
899 \relates QDebug
900 \since 6.3
901
902 Writes the contents of \a array to \a debug. \c T needs to
903 support streaming into QDebug.
904*/
905
906/*!
907 \fn template <typename T, typename Alloc> QDebug operator<<(QDebug debug, const std::list<T, Alloc> &vec)
908 \relates QDebug
909 \since 5.7
910
911 Writes the contents of list \a vec to \a debug. \c T needs to
912 support streaming into QDebug.
913*/
914
915/*!
916 \fn template <typename T, typename Alloc> QDebug operator<<(QDebug debug, const std::vector<T, Alloc> &vec)
917 \relates QDebug
918 \since 5.7
919
920 Writes the contents of vector \a vec to \a debug. \c T needs to
921 support streaming into QDebug.
922*/
923
924/*!
925 \fn template <typename T> QDebug operator<<(QDebug debug, const QSet<T> &set)
926 \relates QDebug
927
928 Writes the contents of \a set to \a debug. \c T needs to
929 support streaming into QDebug.
930*/
931
932/*!
933 \fn template <class Key, class T> QDebug operator<<(QDebug debug, const QMap<Key, T> &map)
934 \relates QDebug
935
936 Writes the contents of \a map to \a debug. Both \c Key and
937 \c T need to support streaming into QDebug.
938*/
939
940/*!
941 \fn template <class Key, class T> QDebug operator<<(QDebug debug, const QMultiMap<Key, T> &map)
942 \relates QDebug
943
944 Writes the contents of \a map to \a debug. Both \c Key and
945 \c T need to support streaming into QDebug.
946*/
947
948/*!
949 \fn template <typename Key, typename T, typename Compare, typename Alloc> QDebug operator<<(QDebug debug, const std::map<Key, T, Compare, Alloc> &map)
950 \relates QDebug
951 \since 5.7
952
953 Writes the contents of \a map to \a debug. Both \c Key and
954 \c T need to support streaming into QDebug.
955*/
956
957/*!
958 \fn template <typename Key, typename T, typename Compare, typename Alloc> QDebug operator<<(QDebug debug, const std::multimap<Key, T, Compare, Alloc> &map)
959 \relates QDebug
960 \since 5.7
961
962 Writes the contents of \a map to \a debug. Both \c Key and
963 \c T need to support streaming into QDebug.
964*/
965
966/*!
967 \fn template <class Key, class T> QDebug operator<<(QDebug debug, const QHash<Key, T> &hash)
968 \relates QDebug
969
970 Writes the contents of \a hash to \a debug. Both \c Key and
971 \c T need to support streaming into QDebug.
972*/
973
974/*!
975 \fn template <class Key, class T> QDebug operator<<(QDebug debug, const QMultiHash<Key, T> &hash)
976 \relates QDebug
977
978 Writes the contents of \a hash to \a debug. Both \c Key and
979 \c T need to support streaming into QDebug.
980*/
981
982/*!
983 \fn template <class T1, class T2> QDebug operator<<(QDebug debug, const QPair<T1, T2> &pair)
984 \relates QDebug
985
986 Writes the contents of \a pair to \a debug. Both \c T1 and
987 \c T2 need to support streaming into QDebug.
988*/
989
990/*!
991 \fn template <class T1, class T2> QDebug operator<<(QDebug debug, const std::pair<T1, T2> &pair)
992 \relates QDebug
993
994 Writes the contents of \a pair to \a debug. Both \c T1 and
995 \c T2 need to support streaming into QDebug.
996*/
997
998/*!
999 \fn template <typename T> QDebug operator<<(QDebug debug, const QContiguousCache<T> &cache)
1000 \relates QDebug
1001
1002 Writes the contents of \a cache to \a debug. \c T needs to
1003 support streaming into QDebug.
1004*/
1005
1006/*!
1007 \fn template<typename T> QDebug operator<<(QDebug debug, const QFlags<T> &flags)
1008 \relates QDebug
1009 \since 4.7
1010
1011 Writes \a flags to \a debug.
1012*/
1013
1014/*!
1015 \fn template<typename T> QDebug operator<<(QDebug debug, const QSharedPointer<T> &ptr)
1016 \relates QSharedPointer
1017 \since 5.7
1018
1019 Writes the pointer tracked by \a ptr into the debug object \a debug for
1020 debugging purposes.
1021
1022 \sa {Debugging Techniques}
1023*/
1024
1025/*!
1026 \fn QDebug &QDebug::operator<<(std::nullptr_t)
1027 \internal
1028 */
1029
1030/*!
1031 \class QDebugStateSaver
1032 \inmodule QtCore
1033 \brief Convenience class for custom QDebug operators.
1034
1035 Saves the settings used by QDebug, and restores them upon destruction,
1036 then calls \l {QDebug::maybeSpace()}{maybeSpace()}, to separate arguments with a space if
1037 \l {QDebug::autoInsertSpaces()}{autoInsertSpaces()} was true at the time of constructing the QDebugStateSaver.
1038
1039 The automatic insertion of spaces between writes is one of the settings
1040 that QDebugStateSaver stores for the duration of the current block.
1041
1042 The settings of the internal QTextStream are also saved and restored,
1043 so that using << Qt::hex in a QDebug operator doesn't affect other QDebug
1044 operators.
1045
1046 QDebugStateSaver is typically used in the implementation of an operator<<() for debugging:
1047
1048 \snippet tools/customtype/message.cpp custom type streaming operator
1049
1050 \since 5.1
1051*/
1052
1053class QDebugStateSaverPrivate
1054{
1055public:
1056 QDebugStateSaverPrivate(QDebug::Stream *stream)
1057 : m_stream(stream),
1058 m_spaces(stream->space),
1059 m_noQuotes(stream->noQuotes),
1060 m_verbosity(stream->verbosity),
1061 m_streamParams(stream->ts.d_ptr->params)
1062 {
1063 }
1064 void restoreState()
1065 {
1066 const bool currentSpaces = m_stream->space;
1067 if (currentSpaces && !m_spaces)
1068 if (m_stream->buffer.endsWith(c: u' '))
1069 m_stream->buffer.chop(n: 1);
1070
1071 m_stream->space = m_spaces;
1072 m_stream->noQuotes = m_noQuotes;
1073 m_stream->ts.d_ptr->params = m_streamParams;
1074 m_stream->verbosity = m_verbosity;
1075
1076 if (!currentSpaces && m_spaces)
1077 m_stream->ts << ' ';
1078 }
1079
1080 QDebug::Stream *m_stream;
1081
1082 // QDebug state
1083 const bool m_spaces;
1084 const bool m_noQuotes;
1085 const int m_verbosity;
1086
1087 // QTextStream state
1088 const QTextStreamPrivate::Params m_streamParams;
1089};
1090
1091
1092/*!
1093 Creates a QDebugStateSaver instance, which saves the settings
1094 currently used by \a dbg.
1095
1096 \sa QDebug::setAutoInsertSpaces(), QDebug::autoInsertSpaces()
1097*/
1098QDebugStateSaver::QDebugStateSaver(QDebug &dbg)
1099 : d(new QDebugStateSaverPrivate(dbg.stream))
1100{
1101}
1102
1103/*!
1104 Destroys a QDebugStateSaver instance, which restores the settings
1105 used when the QDebugStateSaver instance was created.
1106
1107 \sa QDebug::setAutoInsertSpaces(), QDebug::autoInsertSpaces()
1108*/
1109QDebugStateSaver::~QDebugStateSaver()
1110{
1111 d->restoreState();
1112}
1113
1114/*!
1115 \internal
1116
1117 Specialization of the primary template in qdebug.h to out-of-line
1118 the common case of QFlags<T>::Int being int.
1119
1120 Just call the generic version so the two don't get out of sync.
1121*/
1122void qt_QMetaEnum_flagDebugOperator(QDebug &debug, size_t sizeofT, int value)
1123{
1124 qt_QMetaEnum_flagDebugOperator<int>(debug, sizeofT, value);
1125}
1126
1127#ifndef QT_NO_QOBJECT
1128/*!
1129 \internal
1130
1131 Formats the given enum \a value for debug output.
1132
1133 The supported verbosity are:
1134
1135 0: Just the key, or value with enum name if no key is found:
1136
1137 MyEnum2
1138 MyEnum(123)
1139 MyScopedEnum::Enum3
1140 MyScopedEnum(456)
1141
1142 1: Same as 0, but treating all enums as scoped:
1143
1144 MyEnum::MyEnum2
1145 MyEnum(123)
1146 MyScopedEnum::Enum3
1147 MyScopedEnum(456)
1148
1149 2: The QDebug default. Same as 0, and includes class/namespace scope:
1150
1151 MyNamespace::MyClass::MyEnum2
1152 MyNamespace::MyClass::MyEnum(123)
1153 MyNamespace::MyClass::MyScopedEnum::Enum3
1154 MyNamespace::MyClass::MyScopedEnum(456)
1155
1156 3: Same as 2, but treating all enums as scoped:
1157
1158 MyNamespace::MyClass::MyEnum::MyEnum2
1159 MyNamespace::MyClass::MyEnum(123)
1160 MyNamespace::MyClass::MyScopedEnum::Enum3
1161 MyNamespace::MyClass::MyScopedEnum(456)
1162 */
1163QDebug qt_QMetaEnum_debugOperator(QDebug &dbg, qint64 value, const QMetaObject *meta, const char *name)
1164{
1165 QDebugStateSaver saver(dbg);
1166 dbg.nospace();
1167 QMetaEnum me = meta->enumerator(index: meta->indexOfEnumerator(name));
1168
1169 const int verbosity = dbg.verbosity();
1170 if (verbosity >= QDebug::DefaultVerbosity) {
1171 if (const char *scope = me.scope())
1172 dbg << scope << u"::";
1173 }
1174
1175 const char *key = me.valueToKey(value: static_cast<int>(value));
1176 const bool scoped = me.isScoped() || verbosity & 1;
1177 if (scoped || !key)
1178 dbg << me.enumName() << (!key ? u"(" : u"::");
1179
1180 if (key)
1181 dbg << key;
1182 else
1183 dbg << value << ')';
1184
1185 return dbg;
1186}
1187
1188/*!
1189 \fn QDebug qt_QMetaEnum_flagDebugOperator(QDebug &, quint64 value, const QMetaObject *, const char *name)
1190 \internal
1191
1192 Formats the given flag \a value for debug output.
1193
1194 The supported verbosity are:
1195
1196 0: Just the key(s):
1197
1198 MyFlag1
1199 MyFlag2|MyFlag3
1200 MyScopedFlag(MyFlag2)
1201 MyScopedFlag(MyFlag2|MyFlag3)
1202
1203 1: Same as 0, but treating all flags as scoped:
1204
1205 MyFlag(MyFlag1)
1206 MyFlag(MyFlag2|MyFlag3)
1207 MyScopedFlag(MyFlag2)
1208 MyScopedFlag(MyFlag2|MyFlag3)
1209
1210 2: The QDebug default. Same as 1, and includes class/namespace scope:
1211
1212 QFlags<MyNamespace::MyClass::MyFlag>(MyFlag1)
1213 QFlags<MyNamespace::MyClass::MyFlag>(MyFlag2|MyFlag3)
1214 QFlags<MyNamespace::MyClass::MyScopedFlag>(MyFlag2)
1215 QFlags<MyNamespace::MyClass::MyScopedFlag>(MyFlag2|MyFlag3)
1216 */
1217QDebug qt_QMetaEnum_flagDebugOperator(QDebug &debug, quint64 value, const QMetaObject *meta, const char *name)
1218{
1219 const int verbosity = debug.verbosity();
1220
1221 QDebugStateSaver saver(debug);
1222 debug.resetFormat();
1223 debug.noquote();
1224 debug.nospace();
1225
1226 const QMetaEnum me = meta->enumerator(index: meta->indexOfEnumerator(name));
1227
1228 const bool classScope = verbosity >= QDebug::DefaultVerbosity;
1229 if (classScope) {
1230 debug << u"QFlags<";
1231
1232 if (const char *scope = me.scope())
1233 debug << scope << u"::";
1234 }
1235
1236 const bool enumScope = me.isScoped() || verbosity > QDebug::MinimumVerbosity;
1237 if (enumScope) {
1238 debug << me.enumName();
1239 if (classScope)
1240 debug << '>';
1241 debug << '(';
1242 }
1243
1244 debug << me.valueToKeys(value: static_cast<int>(value));
1245
1246 if (enumScope)
1247 debug << ')';
1248
1249 return debug;
1250}
1251#endif // !QT_NO_QOBJECT
1252
1253QT_END_NAMESPACE
1254

source code of qtbase/src/corelib/io/qdebug.cpp