gtest-printers.cc 16.9 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// Copyright 2007, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

30
31

// Google Test - The Google C++ Testing and Mocking Framework
32
33
34
35
36
37
38
39
40
41
42
43
44
//
// This file implements a universal value printer that can print a
// value of any type T:
//
//   void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
//
// It uses the << operator when possible, and prints the bytes in the
// object otherwise.  A user can override its behavior for a class
// type Foo by defining either operator<<(::std::ostream&, const Foo&)
// or void PrintTo(const Foo&, ::std::ostream*) in the namespace that
// defines Foo.

#include "gtest/gtest-printers.h"
Akash Patel's avatar
Akash Patel committed
45

46
#include <stdio.h>
Akash Patel's avatar
Akash Patel committed
47

48
#include <cctype>
Akash Patel's avatar
Akash Patel committed
49
#include <cstdint>
50
#include <cwchar>
51
52
#include <ostream>  // NOLINT
#include <string>
Akash Patel's avatar
Akash Patel committed
53
54
#include <type_traits>

55
#include "gtest/internal/gtest-port.h"
56
#include "src/gtest-internal-inl.h"
57
58
59
60
61
62
63
64

namespace testing {

namespace {

using ::std::ostream;

// Prints a segment of bytes in the given object.
65
66
GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
67
GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
68
GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start,
                                size_t count, ostream* os) {
  char text[5] = "";
  for (size_t i = 0; i != count; i++) {
    const size_t j = start + i;
    if (i != 0) {
      // Organizes the bytes into groups of 2 for easy parsing by
      // human.
      if ((j % 2) == 0)
        *os << ' ';
      else
        *os << '-';
    }
    GTEST_SNPRINTF_(text, sizeof(text), "%02X", obj_bytes[j]);
    *os << text;
  }
}

// Prints the bytes in the given value to the given ostream.
void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,
                              ostream* os) {
  // Tells the user how big the object is.
  *os << count << "-byte object <";

  const size_t kThreshold = 132;
  const size_t kChunkSize = 64;
  // If the object size is bigger than kThreshold, we'll have to omit
  // some details by printing only the first and the last kChunkSize
  // bytes.
  if (count < kThreshold) {
    PrintByteSegmentInObjectTo(obj_bytes, 0, count, os);
  } else {
    PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
    *os << " ... ";
    // Rounds up to 2-byte boundary.
    const size_t resume_pos = (count - kChunkSize + 1)/2*2;
    PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);
  }
  *os << ">";
}

Akash Patel's avatar
Akash Patel committed
110
111
112
113
114
115
116
117
118
119
// Helpers for widening a character to char32_t. Since the standard does not
// specify if char / wchar_t is signed or unsigned, it is important to first
// convert it to the unsigned type of the same width before widening it to
// char32_t.
template <typename CharType>
char32_t ToChar32(CharType in) {
  return static_cast<char32_t>(
      static_cast<typename std::make_unsigned<CharType>::type>(in));
}

120
121
}  // namespace

Akash Patel's avatar
Akash Patel committed
122
namespace internal {
123
124
125
126
127
128
129
130
131
132
133
134
135
136

// Delegates to PrintBytesInObjectToImpl() to print the bytes in the
// given object.  The delegation simplifies the implementation, which
// uses the << operator and thus is easier done outside of the
// ::testing::internal namespace, which contains a << operator that
// sometimes conflicts with the one in STL.
void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,
                          ostream* os) {
  PrintBytesInObjectToImpl(obj_bytes, count, os);
}

// Depending on the value of a char (or wchar_t), we print it in one
// of three formats:
//   - as is if it's a printable ASCII (e.g. 'a', '2', ' '),
137
//   - as a hexadecimal escape sequence (e.g. '\x7F'), or
138
139
140
141
142
143
144
145
146
147
//   - as a special escape sequence (e.g. '\r', '\n').
enum CharFormat {
  kAsIs,
  kHexEscape,
  kSpecialEscape
};

// Returns true if c is a printable ASCII character.  We test the
// value of c directly instead of calling isprint(), which is buggy on
// Windows Mobile.
Akash Patel's avatar
Akash Patel committed
148
inline bool IsPrintableAscii(char32_t c) { return 0x20 <= c && c <= 0x7E; }
149

Akash Patel's avatar
Akash Patel committed
150
151
152
153
// Prints c (of type char, char8_t, char16_t, char32_t, or wchar_t) as a
// character literal without the quotes, escaping it when necessary; returns how
// c was formatted.
template <typename Char>
154
static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
Akash Patel's avatar
Akash Patel committed
155
156
  const char32_t u_c = ToChar32(c);
  switch (u_c) {
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
    case L'\0':
      *os << "\\0";
      break;
    case L'\'':
      *os << "\\'";
      break;
    case L'\\':
      *os << "\\\\";
      break;
    case L'\a':
      *os << "\\a";
      break;
    case L'\b':
      *os << "\\b";
      break;
    case L'\f':
      *os << "\\f";
      break;
    case L'\n':
      *os << "\\n";
      break;
    case L'\r':
      *os << "\\r";
      break;
    case L'\t':
      *os << "\\t";
      break;
    case L'\v':
      *os << "\\v";
      break;
    default:
Akash Patel's avatar
Akash Patel committed
188
      if (IsPrintableAscii(u_c)) {
189
190
191
        *os << static_cast<char>(c);
        return kAsIs;
      } else {
192
        ostream::fmtflags flags = os->flags();
Akash Patel's avatar
Akash Patel committed
193
        *os << "\\x" << std::hex << std::uppercase << static_cast<int>(u_c);
194
        os->flags(flags);
195
196
197
198
199
200
        return kHexEscape;
      }
  }
  return kSpecialEscape;
}

Akash Patel's avatar
Akash Patel committed
201
// Prints a char32_t c as if it's part of a string literal, escaping it when
202
// necessary; returns how c was formatted.
Akash Patel's avatar
Akash Patel committed
203
static CharFormat PrintAsStringLiteralTo(char32_t c, ostream* os) {
204
205
206
207
208
209
210
211
  switch (c) {
    case L'\'':
      *os << "'";
      return kAsIs;
    case L'"':
      *os << "\\\"";
      return kSpecialEscape;
    default:
Akash Patel's avatar
Akash Patel committed
212
      return PrintAsCharLiteralTo(c, os);
213
214
215
  }
}

Akash Patel's avatar
Akash Patel committed
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
static const char* GetCharWidthPrefix(char) {
  return "";
}

static const char* GetCharWidthPrefix(signed char) {
  return "";
}

static const char* GetCharWidthPrefix(unsigned char) {
  return "";
}

#ifdef __cpp_char8_t
static const char* GetCharWidthPrefix(char8_t) {
  return "u8";
}
#endif

static const char* GetCharWidthPrefix(char16_t) {
  return "u";
}

static const char* GetCharWidthPrefix(char32_t) {
  return "U";
}

static const char* GetCharWidthPrefix(wchar_t) {
  return "L";
}

246
247
248
// Prints a char c as if it's part of a string literal, escaping it when
// necessary; returns how c was formatted.
static CharFormat PrintAsStringLiteralTo(char c, ostream* os) {
Akash Patel's avatar
Akash Patel committed
249
250
251
252
253
254
255
256
257
258
259
  return PrintAsStringLiteralTo(ToChar32(c), os);
}

#ifdef __cpp_char8_t
static CharFormat PrintAsStringLiteralTo(char8_t c, ostream* os) {
  return PrintAsStringLiteralTo(ToChar32(c), os);
}
#endif

static CharFormat PrintAsStringLiteralTo(char16_t c, ostream* os) {
  return PrintAsStringLiteralTo(ToChar32(c), os);
260
261
}

Akash Patel's avatar
Akash Patel committed
262
263
264
265
266
267
268
269
static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) {
  return PrintAsStringLiteralTo(ToChar32(c), os);
}

// Prints a character c (of type char, char8_t, char16_t, char32_t, or wchar_t)
// and its code. '\0' is printed as "'\\0'", other unprintable characters are
// also properly escaped using the standard C++ escape sequence.
template <typename Char>
270
271
void PrintCharAndCodeTo(Char c, ostream* os) {
  // First, print c as a literal in the most readable form we can find.
Akash Patel's avatar
Akash Patel committed
272
273
  *os << GetCharWidthPrefix(c) << "'";
  const CharFormat format = PrintAsCharLiteralTo(c, os);
274
275
276
277
278
279
280
281
282
  *os << "'";

  // To aid user debugging, we also print c's code in decimal, unless
  // it's 0 (in which case c was printed as '\\0', making the code
  // obvious).
  if (c == 0)
    return;
  *os << " (" << static_cast<int>(c);

283
  // For more convenience, we print c's code again in hexadecimal,
284
285
286
287
288
  // unless c was already printed in the form '\x##' or the code is in
  // [1, 9].
  if (format == kHexEscape || (1 <= c && c <= 9)) {
    // Do nothing.
  } else {
289
    *os << ", 0x" << String::FormatHexInt(static_cast<int>(c));
290
291
292
293
  }
  *os << ")";
}

Akash Patel's avatar
Akash Patel committed
294
295
void PrintTo(unsigned char c, ::std::ostream* os) { PrintCharAndCodeTo(c, os); }
void PrintTo(signed char c, ::std::ostream* os) { PrintCharAndCodeTo(c, os); }
296
297
298

// Prints a wchar_t as a symbol if it is printable or as its internal
// code otherwise and also as its code.  L'\0' is printed as "L'\\0'".
Akash Patel's avatar
Akash Patel committed
299
300
301
302
303
304
void PrintTo(wchar_t wc, ostream* os) { PrintCharAndCodeTo(wc, os); }

// TODO(dcheng): Consider making this delegate to PrintCharAndCodeTo() as well.
void PrintTo(char32_t c, ::std::ostream* os) {
  *os << std::hex << "U+" << std::uppercase << std::setfill('0') << std::setw(4)
      << static_cast<uint32_t>(c);
305
306
307
}

// Prints the given array of characters to the ostream.  CharType must be either
Akash Patel's avatar
Akash Patel committed
308
// char, char8_t, char16_t, char32_t, or wchar_t.
309
310
311
// The array starts at begin, the length is len, it may include '\0' characters
// and may not be NUL-terminated.
template <typename CharType>
312
313
GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
314
GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
315
GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
316
static CharFormat PrintCharsAsStringTo(
317
    const CharType* begin, size_t len, ostream* os) {
Akash Patel's avatar
Akash Patel committed
318
319
  const char* const quote_prefix = GetCharWidthPrefix(*begin);
  *os << quote_prefix << "\"";
320
  bool is_previous_hex = false;
321
  CharFormat print_format = kAsIs;
322
323
324
325
326
327
  for (size_t index = 0; index < len; ++index) {
    const CharType cur = begin[index];
    if (is_previous_hex && IsXDigit(cur)) {
      // Previous character is of '\x..' form and this character can be
      // interpreted as another hexadecimal digit in its number. Break string to
      // disambiguate.
Akash Patel's avatar
Akash Patel committed
328
      *os << "\" " << quote_prefix << "\"";
329
330
    }
    is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape;
331
332
333
334
    // Remember if any characters required hex escaping.
    if (is_previous_hex) {
      print_format = kHexEscape;
    }
335
336
  }
  *os << "\"";
337
  return print_format;
338
339
340
341
342
}

// Prints a (const) char/wchar_t array of 'len' elements, starting at address
// 'begin'.  CharType must be either char or wchar_t.
template <typename CharType>
343
344
GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
345
GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
346
GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
static void UniversalPrintCharArray(
    const CharType* begin, size_t len, ostream* os) {
  // The code
  //   const char kFoo[] = "foo";
  // generates an array of 4, not 3, elements, with the last one being '\0'.
  //
  // Therefore when printing a char array, we don't print the last element if
  // it's '\0', such that the output matches the string literal as it's
  // written in the source code.
  if (len > 0 && begin[len - 1] == '\0') {
    PrintCharsAsStringTo(begin, len - 1, os);
    return;
  }

  // If, however, the last element in the array is not '\0', e.g.
  //    const char kFoo[] = { 'f', 'o', 'o' };
  // we must print the entire array.  We also print a message to indicate
  // that the array is not NUL-terminated.
  PrintCharsAsStringTo(begin, len, os);
  *os << " (no terminating NUL)";
}

// Prints a (const) char array of 'len' elements, starting at address 'begin'.
void UniversalPrintArray(const char* begin, size_t len, ostream* os) {
  UniversalPrintCharArray(begin, len, os);
}

Akash Patel's avatar
Akash Patel committed
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
#ifdef __cpp_char8_t
// Prints a (const) char8_t array of 'len' elements, starting at address
// 'begin'.
void UniversalPrintArray(const char8_t* begin, size_t len, ostream* os) {
  UniversalPrintCharArray(begin, len, os);
}
#endif

// Prints a (const) char16_t array of 'len' elements, starting at address
// 'begin'.
void UniversalPrintArray(const char16_t* begin, size_t len, ostream* os) {
  UniversalPrintCharArray(begin, len, os);
}

// Prints a (const) char32_t array of 'len' elements, starting at address
// 'begin'.
void UniversalPrintArray(const char32_t* begin, size_t len, ostream* os) {
  UniversalPrintCharArray(begin, len, os);
}

394
395
396
397
398
399
// Prints a (const) wchar_t array of 'len' elements, starting at address
// 'begin'.
void UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) {
  UniversalPrintCharArray(begin, len, os);
}

Akash Patel's avatar
Akash Patel committed
400
401
402
403
404
namespace {

// Prints a null-terminated C-style string to the ostream.
template <typename Char>
void PrintCStringTo(const Char* s, ostream* os) {
405
  if (s == nullptr) {
406
407
408
    *os << "NULL";
  } else {
    *os << ImplicitCast_<const void*>(s) << " pointing to ";
Akash Patel's avatar
Akash Patel committed
409
    PrintCharsAsStringTo(s, std::char_traits<Char>::length(s), os);
410
411
412
  }
}

Akash Patel's avatar
Akash Patel committed
413
414
415
416
417
418
419
420
421
422
423
424
}  // anonymous namespace

void PrintTo(const char* s, ostream* os) { PrintCStringTo(s, os); }

#ifdef __cpp_char8_t
void PrintTo(const char8_t* s, ostream* os) { PrintCStringTo(s, os); }
#endif

void PrintTo(const char16_t* s, ostream* os) { PrintCStringTo(s, os); }

void PrintTo(const char32_t* s, ostream* os) { PrintCStringTo(s, os); }

425
426
427
428
429
430
431
432
// MSVC compiler can be configured to define whar_t as a typedef
// of unsigned short. Defining an overload for const wchar_t* in that case
// would cause pointers to unsigned shorts be printed as wide strings,
// possibly accessing more memory than intended and causing invalid
// memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
// wchar_t is implemented as a native type.
#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
// Prints the given wide C string to the ostream.
Akash Patel's avatar
Akash Patel committed
433
void PrintTo(const wchar_t* s, ostream* os) { PrintCStringTo(s, os); }
434
435
#endif  // wchar_t is native

436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
namespace {

bool ContainsUnprintableControlCodes(const char* str, size_t length) {
  const unsigned char *s = reinterpret_cast<const unsigned char *>(str);

  for (size_t i = 0; i < length; i++) {
    unsigned char ch = *s++;
    if (std::iscntrl(ch)) {
        switch (ch) {
        case '\t':
        case '\n':
        case '\r':
          break;
        default:
          return true;
        }
      }
  }
  return false;
455
456
}

457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
bool IsUTF8TrailByte(unsigned char t) { return 0x80 <= t && t<= 0xbf; }

bool IsValidUTF8(const char* str, size_t length) {
  const unsigned char *s = reinterpret_cast<const unsigned char *>(str);

  for (size_t i = 0; i < length;) {
    unsigned char lead = s[i++];

    if (lead <= 0x7f) {
      continue;  // single-byte character (ASCII) 0..7F
    }
    if (lead < 0xc2) {
      return false;  // trail byte or non-shortest form
    } else if (lead <= 0xdf && (i + 1) <= length && IsUTF8TrailByte(s[i])) {
      ++i;  // 2-byte character
    } else if (0xe0 <= lead && lead <= 0xef && (i + 2) <= length &&
               IsUTF8TrailByte(s[i]) &&
               IsUTF8TrailByte(s[i + 1]) &&
               // check for non-shortest form and surrogate
               (lead != 0xe0 || s[i] >= 0xa0) &&
               (lead != 0xed || s[i] < 0xa0)) {
      i += 2;  // 3-byte character
    } else if (0xf0 <= lead && lead <= 0xf4 && (i + 3) <= length &&
               IsUTF8TrailByte(s[i]) &&
               IsUTF8TrailByte(s[i + 1]) &&
               IsUTF8TrailByte(s[i + 2]) &&
               // check for non-shortest form
               (lead != 0xf0 || s[i] >= 0x90) &&
               (lead != 0xf4 || s[i] < 0x90)) {
      i += 3;  // 4-byte character
    } else {
      return false;
    }
  }
  return true;
492
493
}

494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
void ConditionalPrintAsText(const char* str, size_t length, ostream* os) {
  if (!ContainsUnprintableControlCodes(str, length) &&
      IsValidUTF8(str, length)) {
    *os << "\n    As Text: \"" << str << "\"";
  }
}

}  // anonymous namespace

void PrintStringTo(const ::std::string& s, ostream* os) {
  if (PrintCharsAsStringTo(s.data(), s.size(), os) == kHexEscape) {
    if (GTEST_FLAG(print_utf8)) {
      ConditionalPrintAsText(s.data(), s.size(), os);
    }
  }
509
510
}

Akash Patel's avatar
Akash Patel committed
511
512
513
514
515
516
517
518
519
520
521
522
523
524
#ifdef __cpp_char8_t
void PrintU8StringTo(const ::std::u8string& s, ostream* os) {
  PrintCharsAsStringTo(s.data(), s.size(), os);
}
#endif

void PrintU16StringTo(const ::std::u16string& s, ostream* os) {
  PrintCharsAsStringTo(s.data(), s.size(), os);
}

void PrintU32StringTo(const ::std::u32string& s, ostream* os) {
  PrintCharsAsStringTo(s.data(), s.size(), os);
}

525
526
527
528
529
530
531
532
533
#if GTEST_HAS_STD_WSTRING
void PrintWideStringTo(const ::std::wstring& s, ostream* os) {
  PrintCharsAsStringTo(s.data(), s.size(), os);
}
#endif  // GTEST_HAS_STD_WSTRING

}  // namespace internal

}  // namespace testing