gtest-printers.h 35.1 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
// 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.
Gennadiy Civil's avatar
 
Gennadiy Civil committed
29

30

Gennadiy Civil's avatar
Gennadiy Civil committed
31
// Google Test - The Google C++ Testing and Mocking Framework
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
//
// 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);
//
// A user can teach this function how to print a class type T by
// defining either operator<<() or PrintTo() in the namespace that
// defines T.  More specifically, the FIRST defined function in the
// following list will be used (assuming T is defined in namespace
// foo):
//
//   1. foo::PrintTo(const T&, ostream*)
//   2. operator<<(ostream&, const T&) defined in either foo or the
//      global namespace.
//
48
49
50
51
// However if T is an STL-style container then it is printed element-wise
// unless foo::PrintTo(const T&, ostream*) is defined. Note that
// operator<<() is ignored for container types.
//
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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
// If none of the above is defined, it will print the debug string of
// the value if it is a protocol buffer, or print the raw bytes in the
// value otherwise.
//
// To aid debugging: when T is a reference type, the address of the
// value is also printed; when T is a (const) char pointer, both the
// pointer value and the NUL-terminated string it points to are
// printed.
//
// We also provide some convenient wrappers:
//
//   // Prints a value to a string.  For a (const or not) char
//   // pointer, the NUL-terminated string (but not the pointer) is
//   // printed.
//   std::string ::testing::PrintToString(const T& value);
//
//   // Prints a value tersely: for a reference type, the referenced
//   // value (but not the address) is printed; for a (const or not) char
//   // pointer, the NUL-terminated string (but not the pointer) is
//   // printed.
//   void ::testing::internal::UniversalTersePrint(const T& value, ostream*);
//
//   // Prints value using the type inferred by the compiler.  The difference
//   // from UniversalTersePrint() is that this function prints both the
//   // pointer and the NUL-terminated string for a (const or not) char pointer.
//   void ::testing::internal::UniversalPrint(const T& value, ostream*);
//
//   // Prints the fields of a tuple tersely to a string vector, one
//   // element for each field. Tuple support must be enabled in
//   // gtest-port.h.
//   std::vector<string> UniversalTersePrintTupleFieldsToStrings(
//       const Tuple& value);
//
// Known limitation:
//
// The print primitives print the elements of an STL-style container
// using the compiler-inferred type of *iter where iter is a
// const_iterator of the container.  When const_iterator is an input
// iterator but not a forward iterator, this inferred type may not
// match value_type, and the print output may be incorrect.  In
// practice, this is rarely a problem as for most containers
// const_iterator is a forward iterator.  We'll fix this if there's an
// actual need for it.  Note that this fix cannot rely on value_type
// being defined as many user-defined container types don't have
// value_type.

Gennadiy Civil's avatar
 
Gennadiy Civil committed
98
99
// GOOGLETEST_CM0001 DO NOT DELETE

Abseil Team's avatar
Abseil Team committed
100
101
#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
#define GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
102

misterg's avatar
misterg committed
103
#include <functional>
Abseil Team's avatar
Abseil Team committed
104
#include <memory>
105
106
107
#include <ostream>  // NOLINT
#include <sstream>
#include <string>
Abseil Team's avatar
Abseil Team committed
108
109
#include <tuple>
#include <type_traits>
110
111
#include <utility>
#include <vector>
Abseil Team's avatar
Abseil Team committed
112

113
#include "gtest/internal/gtest-internal.h"
Abseil Team's avatar
Abseil Team committed
114
#include "gtest/internal/gtest-port.h"
115

116
117
namespace testing {

Abseil Team's avatar
Abseil Team committed
118
119
120
// Definitions in the internal* namespaces are subject to change without notice.
// DO NOT USE THEM IN USER CODE!
namespace internal {
121

Abseil Team's avatar
Abseil Team committed
122
123
template <typename T>
void UniversalPrint(const T& value, ::std::ostream* os);
124

Abseil Team's avatar
Abseil Team committed
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
// Used to print an STL-style container when the user doesn't define
// a PrintTo() for it.
struct ContainerPrinter {
  template <typename T,
            typename = typename std::enable_if<
                (sizeof(IsContainerTest<T>(0)) == sizeof(IsContainer)) &&
                !IsRecursiveContainer<T>::value>::type>
  static void PrintValue(const T& container, std::ostream* os) {
    const size_t kMaxCount = 32;  // The maximum number of elements to print.
    *os << '{';
    size_t count = 0;
    for (auto&& elem : container) {
      if (count > 0) {
        *os << ',';
        if (count == kMaxCount) {  // Enough has been printed.
          *os << " ...";
          break;
        }
      }
      *os << ' ';
      // We cannot call PrintTo(elem, os) here as PrintTo() doesn't
      // handle `elem` being a native array.
      internal::UniversalPrint(elem, os);
      ++count;
    }

    if (count > 0) {
      *os << ' ';
    }
    *os << '}';
  }
156
157
};

Abseil Team's avatar
Abseil Team committed
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
// Used to print a pointer that is neither a char pointer nor a member
// pointer, when the user doesn't define PrintTo() for it.  (A member
// variable pointer or member function pointer doesn't really point to
// a location in the address space.  Their representation is
// implementation-defined.  Therefore they will be printed as raw
// bytes.)
struct FunctionPointerPrinter {
  template <typename T, typename = typename std::enable_if<
                            std::is_function<T>::value>::type>
  static void PrintValue(T* p, ::std::ostream* os) {
    if (p == nullptr) {
      *os << "NULL";
    } else {
      // T is a function type, so '*os << p' doesn't do what we want
      // (it just prints p as bool).  We want to print p as a const
      // void*.
      *os << reinterpret_cast<const void*>(p);
    }
176
177
178
  }
};

Abseil Team's avatar
Abseil Team committed
179
180
181
182
183
184
185
186
187
188
189
190
191
struct PointerPrinter {
  template <typename T>
  static void PrintValue(T* p, ::std::ostream* os) {
    if (p == nullptr) {
      *os << "NULL";
    } else {
      // T is not a function type.  We just call << to print p,
      // relying on ADL to pick up user-defined << for their pointer
      // types, if any.
      *os << p;
    }
  }
};
192

Abseil Team's avatar
Abseil Team committed
193
namespace internal_stream_operator_without_lexical_name_lookup {
Abseil Team's avatar
Abseil Team committed
194

Abseil Team's avatar
Abseil Team committed
195
196
197
198
199
200
// The presence of an operator<< here will terminate lexical scope lookup
// straight away (even though it cannot be a match because of its argument
// types). Thus, the two operator<< calls in StreamPrinter will find only ADL
// candidates.
struct LookupBlocker {};
void operator<<(LookupBlocker, LookupBlocker);
Abseil Team's avatar
Abseil Team committed
201
202

struct StreamPrinter {
Abseil Team's avatar
Abseil Team committed
203
204
205
206
207
208
209
210
211
  template <typename T,
            // Don't accept member pointers here. We'd print them via implicit
            // conversion to bool, which isn't useful.
            typename = typename std::enable_if<
                !std::is_member_pointer<T>::value>::type,
            // Only accept types for which we can find a streaming operator via
            // ADL (possibly involving implicit conversions).
            typename = decltype(std::declval<std::ostream&>()
                                << std::declval<const T&>())>
Abseil Team's avatar
Abseil Team committed
212
  static void PrintValue(const T& value, ::std::ostream* os) {
Abseil Team's avatar
Abseil Team committed
213
214
    // Call streaming operator found by ADL, possibly with implicit conversions
    // of the arguments.
Abseil Team's avatar
Abseil Team committed
215
216
217
218
    *os << value;
  }
};

Abseil Team's avatar
Abseil Team committed
219
220
}  // namespace internal_stream_operator_without_lexical_name_lookup

Abseil Team's avatar
Abseil Team committed
221
222
223
224
225
226
struct ProtobufPrinter {
  // We print a protobuf using its ShortDebugString() when the string
  // doesn't exceed this many characters; otherwise we print it using
  // DebugString() for better readability.
  static const size_t kProtobufOneLinerMaxLength = 50;

227
228
229
  template <typename T,
            typename = typename std::enable_if<
                internal::HasDebugStringAndShortDebugString<T>::value>::type>
230
  static void PrintValue(const T& value, ::std::ostream* os) {
231
232
233
234
    std::string pretty_str = value.ShortDebugString();
    if (pretty_str.length() > kProtobufOneLinerMaxLength) {
      pretty_str = "\n" + value.DebugString();
    }
235
236
237
238
    *os << ("<" + pretty_str + ">");
  }
};

Abseil Team's avatar
Abseil Team committed
239
struct ConvertibleToIntegerPrinter {
240
  // Since T has no << operator or PrintTo() but can be implicitly
241
  // converted to BiggestInt, we print it as a BiggestInt.
242
243
  //
  // Most likely T is an enum type (either named or unnamed), in which
244
  // case printing it as an integer is the desired behavior.  In case
245
246
  // T is not an enum, printing it as an integer is the best we can do
  // given that it has no user-defined printer.
Abseil Team's avatar
Abseil Team committed
247
248
  static void PrintValue(internal::BiggestInt value, ::std::ostream* os) {
    *os << value;
249
250
251
  }
};

Abseil Team's avatar
Abseil Team committed
252
struct ConvertibleToStringViewPrinter {
Abseil Team's avatar
Abseil Team committed
253
#if GTEST_INTERNAL_HAS_STRING_VIEW
Abseil Team's avatar
Abseil Team committed
254
255
256
  static void PrintValue(internal::StringView value, ::std::ostream* os) {
    internal::UniversalPrint(value, os);
  }
Gennadiy Civil's avatar
Gennadiy Civil committed
257
#endif
Abseil Team's avatar
Abseil Team committed
258
};
Gennadiy Civil's avatar
Gennadiy Civil committed
259

260

Abseil Team's avatar
Abseil Team committed
261
262
263
264
265
// Prints the given number of bytes in the given object to the given
// ostream.
GTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes,
                                     size_t count,
                                     ::std::ostream* os);
Abseil Team's avatar
Abseil Team committed
266
267
268
struct RawBytesPrinter {
  // SFINAE on `sizeof` to make sure we have a complete type.
  template <typename T, size_t = sizeof(T)>
Abseil Team's avatar
Abseil Team committed
269
270
  static void PrintValue(const T& value, ::std::ostream* os) {
    PrintBytesInObjectTo(
Abseil Team's avatar
Abseil Team committed
271
272
273
        static_cast<const unsigned char*>(
            // Load bearing cast to void* to support iOS
            reinterpret_cast<const void*>(std::addressof(value))),
Abseil Team's avatar
Abseil Team committed
274
275
276
277
        sizeof(value), os);
  }
};

Abseil Team's avatar
Abseil Team committed
278
279
280
281
282
283
284
struct FallbackPrinter {
  template <typename T>
  static void PrintValue(const T&, ::std::ostream* os) {
    *os << "(incomplete type)";
  }
};

Abseil Team's avatar
Abseil Team committed
285
286
287
// Try every printer in order and return the first one that works.
template <typename T, typename E, typename Printer, typename... Printers>
struct FindFirstPrinter : FindFirstPrinter<T, E, Printers...> {};
288

Abseil Team's avatar
Abseil Team committed
289
290
291
292
293
294
template <typename T, typename Printer, typename... Printers>
struct FindFirstPrinter<
    T, decltype(Printer::PrintValue(std::declval<const T&>(), nullptr)),
    Printer, Printers...> {
  using type = Printer;
};
295

Abseil Team's avatar
Abseil Team committed
296
297
298
299
300
301
302
303
304
// Select the best printer in the following order:
//  - Print containers (they have begin/end/etc).
//  - Print function pointers.
//  - Print object pointers.
//  - Use the stream operator, if available.
//  - Print protocol buffers.
//  - Print types convertible to BiggestInt.
//  - Print types convertible to StringView, if available.
//  - Fallback to printing the raw bytes of the object.
305
template <typename T>
Abseil Team's avatar
Abseil Team committed
306
307
308
void PrintWithFallback(const T& value, ::std::ostream* os) {
  using Printer = typename FindFirstPrinter<
      T, void, ContainerPrinter, FunctionPointerPrinter, PointerPrinter,
Abseil Team's avatar
Abseil Team committed
309
310
      internal_stream_operator_without_lexical_name_lookup::StreamPrinter,
      ProtobufPrinter, ConvertibleToIntegerPrinter,
Abseil Team's avatar
Abseil Team committed
311
      ConvertibleToStringViewPrinter, RawBytesPrinter, FallbackPrinter>::type;
Abseil Team's avatar
Abseil Team committed
312
  Printer::PrintValue(value, os);
313
314
}

315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
// FormatForComparison<ToPrint, OtherOperand>::Format(value) formats a
// value of type ToPrint that is an operand of a comparison assertion
// (e.g. ASSERT_EQ).  OtherOperand is the type of the other operand in
// the comparison, and is used to help determine the best way to
// format the value.  In particular, when the value is a C string
// (char pointer) and the other operand is an STL string object, we
// want to format the C string as a string, since we know it is
// compared by value with the string object.  If the value is a char
// pointer but the other operand is not an STL string object, we don't
// know whether the pointer is supposed to point to a NUL-terminated
// string, and thus want to print it as a pointer to be safe.
//
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.

// The default case.
template <typename ToPrint, typename OtherOperand>
class FormatForComparison {
 public:
  static ::std::string Format(const ToPrint& value) {
    return ::testing::PrintToString(value);
  }
};

// Array.
template <typename ToPrint, size_t N, typename OtherOperand>
class FormatForComparison<ToPrint[N], OtherOperand> {
 public:
  static ::std::string Format(const ToPrint* value) {
    return FormatForComparison<const ToPrint*, OtherOperand>::Format(value);
  }
};

// By default, print C string as pointers to be safe, as we don't know
// whether they actually point to a NUL-terminated string.

#define GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(CharType)                \
  template <typename OtherOperand>                                      \
  class FormatForComparison<CharType*, OtherOperand> {                  \
   public:                                                              \
    static ::std::string Format(CharType* value) {                      \
      return ::testing::PrintToString(static_cast<const void*>(value)); \
    }                                                                   \
  }

GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char);
GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char);
GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(wchar_t);
GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const wchar_t);
363
#ifdef __cpp_lib_char8_t
dmauro's avatar
dmauro committed
364
365
366
367
368
369
370
GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char8_t);
GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char8_t);
#endif
GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char16_t);
GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char16_t);
GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char32_t);
GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char32_t);
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387

#undef GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_

// If a C string is compared with an STL string object, we know it's meant
// to point to a NUL-terminated string, and thus can print it as a string.

#define GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(CharType, OtherStringType) \
  template <>                                                           \
  class FormatForComparison<CharType*, OtherStringType> {               \
   public:                                                              \
    static ::std::string Format(CharType* value) {                      \
      return ::testing::PrintToString(value);                           \
    }                                                                   \
  }

GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::std::string);
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char, ::std::string);
dmauro's avatar
dmauro committed
388
389
390
391
392
393
394
395
#ifdef __cpp_char8_t
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char8_t, ::std::u8string);
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char8_t, ::std::u8string);
#endif
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char16_t, ::std::u16string);
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char16_t, ::std::u16string);
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char32_t, ::std::u32string);
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char32_t, ::std::u32string);
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417

#if GTEST_HAS_STD_WSTRING
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(wchar_t, ::std::wstring);
GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const wchar_t, ::std::wstring);
#endif

#undef GTEST_IMPL_FORMAT_C_STRING_AS_STRING_

// Formats a comparison assertion (e.g. ASSERT_EQ, EXPECT_LT, and etc)
// operand to be used in a failure message.  The type (but not value)
// of the other operand may affect the format.  This allows us to
// print a char* as a raw pointer when it is compared against another
// char* or void*, and print it as a C string when it is compared
// against an std::string object, for example.
//
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
template <typename T1, typename T2>
std::string FormatForComparisonFailureMessage(
    const T1& value, const T2& /* other_operand */) {
  return FormatForComparison<T1, T2>::Format(value);
}

418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
// UniversalPrinter<T>::Print(value, ostream_ptr) prints the given
// value to the given ostream.  The caller must ensure that
// 'ostream_ptr' is not NULL, or the behavior is undefined.
//
// We define UniversalPrinter as a class template (as opposed to a
// function template), as we need to partially specialize it for
// reference types, which cannot be done with function templates.
template <typename T>
class UniversalPrinter;

// Prints the given value using the << operator if it has one;
// otherwise prints the bytes in it.  This is what
// UniversalPrinter<T>::Print() does when PrintTo() is not specialized
// or overloaded for type T.
//
// A user can override this behavior for a class type Foo by defining
// an overload of PrintTo() in the namespace where Foo is defined.  We
// give the user this option as sometimes defining a << operator for
// Foo is not desirable (e.g. the coding style may prevent doing it,
// or there is already a << operator but it doesn't do what the user
// wants).
template <typename T>
void PrintTo(const T& value, ::std::ostream* os) {
Abseil Team's avatar
Abseil Team committed
441
  internal::PrintWithFallback(value, os);
442
443
444
445
446
447
448
}

// The following list of PrintTo() overloads tells
// UniversalPrinter<T>::Print() how to print standard types (built-in
// types, strings, plain arrays, and pointers).

// Overloads for various char types.
449
450
GTEST_API_ void PrintTo(unsigned char c, ::std::ostream* os);
GTEST_API_ void PrintTo(signed char c, ::std::ostream* os);
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
inline void PrintTo(char c, ::std::ostream* os) {
  // When printing a plain char, we always treat it as unsigned.  This
  // way, the output won't be affected by whether the compiler thinks
  // char is signed or not.
  PrintTo(static_cast<unsigned char>(c), os);
}

// Overloads for other simple built-in types.
inline void PrintTo(bool x, ::std::ostream* os) {
  *os << (x ? "true" : "false");
}

// Overload for wchar_t type.
// Prints a wchar_t as a symbol if it is printable or as its internal
// code otherwise and also as its decimal code (except for L'\0').
// The L'\0' char is printed as "L'\\0'". The decimal code is printed
// as signed integer when wchar_t is implemented by the compiler
// as a signed type and is printed as an unsigned integer when wchar_t
// is implemented as an unsigned type.
GTEST_API_ void PrintTo(wchar_t wc, ::std::ostream* os);

dmauro's avatar
dmauro committed
472
473
474
475
476
477
478
479
480
481
GTEST_API_ void PrintTo(char32_t c, ::std::ostream* os);
inline void PrintTo(char16_t c, ::std::ostream* os) {
  PrintTo(ImplicitCast_<char32_t>(c), os);
}
#ifdef __cpp_char8_t
inline void PrintTo(char8_t c, ::std::ostream* os) {
  PrintTo(ImplicitCast_<char32_t>(c), os);
}
#endif

482
483
484
// Overloads for C strings.
GTEST_API_ void PrintTo(const char* s, ::std::ostream* os);
inline void PrintTo(char* s, ::std::ostream* os) {
485
  PrintTo(ImplicitCast_<const char*>(s), os);
486
487
}

488
489
490
// signed/unsigned char is often used for representing binary data, so
// we print pointers to it as void* to be safe.
inline void PrintTo(const signed char* s, ::std::ostream* os) {
491
  PrintTo(ImplicitCast_<const void*>(s), os);
492
493
}
inline void PrintTo(signed char* s, ::std::ostream* os) {
494
  PrintTo(ImplicitCast_<const void*>(s), os);
495
496
}
inline void PrintTo(const unsigned char* s, ::std::ostream* os) {
497
  PrintTo(ImplicitCast_<const void*>(s), os);
498
499
}
inline void PrintTo(unsigned char* s, ::std::ostream* os) {
500
  PrintTo(ImplicitCast_<const void*>(s), os);
501
}
dmauro's avatar
dmauro committed
502
#ifdef __cpp_char8_t
Abseil Team's avatar
Abseil Team committed
503
// Overloads for u8 strings.
504
GTEST_API_ void PrintTo(const char8_t* s, ::std::ostream* os);
dmauro's avatar
dmauro committed
505
inline void PrintTo(char8_t* s, ::std::ostream* os) {
Abseil Team's avatar
Abseil Team committed
506
  PrintTo(ImplicitCast_<const char8_t*>(s), os);
dmauro's avatar
dmauro committed
507
508
}
#endif
Abseil Team's avatar
Abseil Team committed
509
// Overloads for u16 strings.
510
GTEST_API_ void PrintTo(const char16_t* s, ::std::ostream* os);
dmauro's avatar
dmauro committed
511
inline void PrintTo(char16_t* s, ::std::ostream* os) {
Abseil Team's avatar
Abseil Team committed
512
  PrintTo(ImplicitCast_<const char16_t*>(s), os);
dmauro's avatar
dmauro committed
513
}
Abseil Team's avatar
Abseil Team committed
514
// Overloads for u32 strings.
515
GTEST_API_ void PrintTo(const char32_t* s, ::std::ostream* os);
dmauro's avatar
dmauro committed
516
inline void PrintTo(char32_t* s, ::std::ostream* os) {
Abseil Team's avatar
Abseil Team committed
517
  PrintTo(ImplicitCast_<const char32_t*>(s), os);
dmauro's avatar
dmauro committed
518
}
519

520
521
522
523
524
525
526
527
528
// MSVC can be configured to define wchar_t as a typedef of unsigned
// short.  It defines _NATIVE_WCHAR_T_DEFINED when wchar_t is a native
// type.  When wchar_t is a typedef, defining an overload for const
// wchar_t* would cause unsigned short* be printed as a wide string,
// possibly causing invalid memory accesses.
#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
// Overloads for wide C strings
GTEST_API_ void PrintTo(const wchar_t* s, ::std::ostream* os);
inline void PrintTo(wchar_t* s, ::std::ostream* os) {
529
  PrintTo(ImplicitCast_<const wchar_t*>(s), os);
530
531
532
533
534
535
536
537
538
539
}
#endif

// Overload for C arrays.  Multi-dimensional arrays are printed
// properly.

// Prints the given number of elements in an array, without printing
// the curly braces.
template <typename T>
void PrintRawArrayTo(const T a[], size_t count, ::std::ostream* os) {
540
  UniversalPrint(a[0], os);
541
542
  for (size_t i = 1; i != count; i++) {
    *os << ", ";
543
    UniversalPrint(a[i], os);
544
545
546
  }
}

Abseil Team's avatar
Abseil Team committed
547
// Overloads for ::std::string.
548
549
550
551
552
GTEST_API_ void PrintStringTo(const ::std::string&s, ::std::ostream* os);
inline void PrintTo(const ::std::string& s, ::std::ostream* os) {
  PrintStringTo(s, os);
}

Abseil Team's avatar
Abseil Team committed
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
// Overloads for ::std::u8string
#ifdef __cpp_char8_t
GTEST_API_ void PrintU8StringTo(const ::std::u8string& s, ::std::ostream* os);
inline void PrintTo(const ::std::u8string& s, ::std::ostream* os) {
  PrintU8StringTo(s, os);
}
#endif

// Overloads for ::std::u16string
GTEST_API_ void PrintU16StringTo(const ::std::u16string& s, ::std::ostream* os);
inline void PrintTo(const ::std::u16string& s, ::std::ostream* os) {
  PrintU16StringTo(s, os);
}

// Overloads for ::std::u32string
GTEST_API_ void PrintU32StringTo(const ::std::u32string& s, ::std::ostream* os);
inline void PrintTo(const ::std::u32string& s, ::std::ostream* os) {
  PrintU32StringTo(s, os);
}

Abseil Team's avatar
Abseil Team committed
573
// Overloads for ::std::wstring.
574
575
576
577
578
579
580
#if GTEST_HAS_STD_WSTRING
GTEST_API_ void PrintWideStringTo(const ::std::wstring&s, ::std::ostream* os);
inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) {
  PrintWideStringTo(s, os);
}
#endif  // GTEST_HAS_STD_WSTRING

Abseil Team's avatar
Abseil Team committed
581
582
583
#if GTEST_INTERNAL_HAS_STRING_VIEW
// Overload for internal::StringView.
inline void PrintTo(internal::StringView sp, ::std::ostream* os) {
584
  PrintTo(::std::string(sp), os);
Gennadiy Civil's avatar
Gennadiy Civil committed
585
}
Abseil Team's avatar
Abseil Team committed
586
#endif  // GTEST_INTERNAL_HAS_STRING_VIEW
Gennadiy Civil's avatar
Gennadiy Civil committed
587

Gennadiy Civil's avatar
Gennadiy Civil committed
588
inline void PrintTo(std::nullptr_t, ::std::ostream* os) { *os << "(nullptr)"; }
Abseil Team's avatar
Abseil Team committed
589
590
591

template <typename T>
void PrintTo(std::reference_wrapper<T> ref, ::std::ostream* os) {
Abseil Team's avatar
Abseil Team committed
592
  UniversalPrinter<T&>::Print(ref.get(), os);
Abseil Team's avatar
Abseil Team committed
593
594
}

Abseil Team's avatar
Abseil Team committed
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
inline const void* VoidifyPointer(const void* p) { return p; }
inline const void* VoidifyPointer(volatile const void* p) {
  return const_cast<const void*>(p);
}

template <typename T, typename Ptr>
void PrintSmartPointer(const Ptr& ptr, std::ostream* os, char) {
  if (ptr == nullptr) {
    *os << "(nullptr)";
  } else {
    // We can't print the value. Just print the pointer..
    *os << "(" << (VoidifyPointer)(ptr.get()) << ")";
  }
}
template <typename T, typename Ptr,
          typename = typename std::enable_if<!std::is_void<T>::value &&
                                             !std::is_array<T>::value>::type>
void PrintSmartPointer(const Ptr& ptr, std::ostream* os, int) {
  if (ptr == nullptr) {
    *os << "(nullptr)";
  } else {
    *os << "(ptr = " << (VoidifyPointer)(ptr.get()) << ", value = ";
    UniversalPrinter<T>::Print(*ptr, os);
    *os << ")";
  }
}

template <typename T, typename D>
void PrintTo(const std::unique_ptr<T, D>& ptr, std::ostream* os) {
  (PrintSmartPointer<T>)(ptr, os, 0);
}

template <typename T>
void PrintTo(const std::shared_ptr<T>& ptr, std::ostream* os) {
  (PrintSmartPointer<T>)(ptr, os, 0);
}

632
633
634
// Helper function for printing a tuple.  T must be instantiated with
// a tuple type.
template <typename T>
Abseil Team's avatar
Abseil Team committed
635
636
637
638
639
640
641
642
643
644
645
646
647
648
void PrintTupleTo(const T&, std::integral_constant<size_t, 0>,
                  ::std::ostream*) {}

template <typename T, size_t I>
void PrintTupleTo(const T& t, std::integral_constant<size_t, I>,
                  ::std::ostream* os) {
  PrintTupleTo(t, std::integral_constant<size_t, I - 1>(), os);
  GTEST_INTENTIONAL_CONST_COND_PUSH_()
  if (I > 1) {
    GTEST_INTENTIONAL_CONST_COND_POP_()
    *os << ", ";
  }
  UniversalPrinter<typename std::tuple_element<I - 1, T>::type>::Print(
      std::get<I - 1>(t), os);
649
650
}

651
652
template <typename... Types>
void PrintTo(const ::std::tuple<Types...>& t, ::std::ostream* os) {
Abseil Team's avatar
Abseil Team committed
653
654
655
  *os << "(";
  PrintTupleTo(t, std::integral_constant<size_t, sizeof...(Types)>(), os);
  *os << ")";
656
657
}

658
659
660
661
// Overload for std::pair.
template <typename T1, typename T2>
void PrintTo(const ::std::pair<T1, T2>& value, ::std::ostream* os) {
  *os << '(';
662
663
  // We cannot use UniversalPrint(value.first, os) here, as T1 may be
  // a reference type.  The same for printing value.second.
664
665
666
667
668
669
670
671
672
673
674
675
676
  UniversalPrinter<T1>::Print(value.first, os);
  *os << ", ";
  UniversalPrinter<T2>::Print(value.second, os);
  *os << ')';
}

// Implements printing a non-reference type T by letting the compiler
// pick the right overload of PrintTo() for T.
template <typename T>
class UniversalPrinter {
 public:
  // MSVC warns about adding const to a function type, so we want to
  // disable the warning.
billydonahue's avatar
billydonahue committed
677
  GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180)
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693

  // Note: we deliberately don't call this PrintTo(), as that name
  // conflicts with ::testing::internal::PrintTo in the body of the
  // function.
  static void Print(const T& value, ::std::ostream* os) {
    // By default, ::testing::internal::PrintTo() is used for printing
    // the value.
    //
    // Thanks to Koenig look-up, if T is a class and has its own
    // PrintTo() function defined in its namespace, that function will
    // be visible here.  Since it is more specific than the generic ones
    // in ::testing::internal, it will be picked by the compiler in the
    // following statement - exactly what we want.
    PrintTo(value, os);
  }

billydonahue's avatar
billydonahue committed
694
  GTEST_DISABLE_MSC_WARNINGS_POP_()
695
696
};

Abseil Team's avatar
Abseil Team committed
697
698
699
700
// Remove any const-qualifiers before passing a type to UniversalPrinter.
template <typename T>
class UniversalPrinter<const T> : public UniversalPrinter<T> {};

701
702
703
704
705
706
707
708
#if GTEST_INTERNAL_HAS_ANY

// Printer for std::any / absl::any

template <>
class UniversalPrinter<Any> {
 public:
  static void Print(const Any& value, ::std::ostream* os) {
709
710
711
712
713
    if (value.has_value()) {
      *os << "value of type " << GetTypeName(value);
    } else {
      *os << "no value";
    }
714
715
716
  }

 private:
717
718
719
720
  static std::string GetTypeName(const Any& value) {
#if GTEST_HAS_RTTI
    return internal::GetTypeName(value.type());
#else
721
722
    static_cast<void>(value);  // possibly unused
    return "<unknown_type>";
723
724
#endif  // GTEST_HAS_RTTI
  }
725
726
727
};

#endif  // GTEST_INTERNAL_HAS_ANY
728

729
#if GTEST_INTERNAL_HAS_OPTIONAL
730

731
// Printer for std::optional / absl::optional
732
733

template <typename T>
734
class UniversalPrinter<Optional<T>> {
735
 public:
736
  static void Print(const Optional<T>& value, ::std::ostream* os) {
737
738
739
740
741
742
743
744
745
746
    *os << '(';
    if (!value) {
      *os << "nullopt";
    } else {
      UniversalPrint(*value, os);
    }
    *os << ')';
  }
};

747
#endif  // GTEST_INTERNAL_HAS_OPTIONAL
748
749
750
751

#if GTEST_INTERNAL_HAS_VARIANT

// Printer for std::variant / absl::variant
752
753

template <typename... T>
754
class UniversalPrinter<Variant<T...>> {
755
 public:
756
  static void Print(const Variant<T...>& value, ::std::ostream* os) {
757
    *os << '(';
758
759
760
761
762
#if GTEST_HAS_ABSL
    absl::visit(Visitor{os, value.index()}, value);
#else
    std::visit(Visitor{os, value.index()}, value);
#endif  // GTEST_HAS_ABSL
763
764
765
766
767
768
769
    *os << ')';
  }

 private:
  struct Visitor {
    template <typename U>
    void operator()(const U& u) const {
770
771
      *os << "'" << GetTypeName<U>() << "(index = " << index
          << ")' with value ";
772
773
774
      UniversalPrint(u, os);
    }
    ::std::ostream* os;
775
    std::size_t index;
776
777
778
  };
};

779
#endif  // GTEST_INTERNAL_HAS_VARIANT
780

781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
// UniversalPrintArray(begin, len, os) prints an array of 'len'
// elements, starting at address 'begin'.
template <typename T>
void UniversalPrintArray(const T* begin, size_t len, ::std::ostream* os) {
  if (len == 0) {
    *os << "{}";
  } else {
    *os << "{ ";
    const size_t kThreshold = 18;
    const size_t kChunkSize = 8;
    // If the array has more than kThreshold elements, we'll have to
    // omit some details by printing only the first and the last
    // kChunkSize elements.
    if (len <= kThreshold) {
      PrintRawArrayTo(begin, len, os);
    } else {
      PrintRawArrayTo(begin, kChunkSize, os);
      *os << ", ..., ";
      PrintRawArrayTo(begin + len - kChunkSize, kChunkSize, os);
    }
    *os << " }";
  }
}
// This overload prints a (const) char array compactly.
805
806
807
GTEST_API_ void UniversalPrintArray(
    const char* begin, size_t len, ::std::ostream* os);

Abseil Team's avatar
Abseil Team committed
808
809
810
811
812
813
814
815
816
817
818
819
820
821
#ifdef __cpp_char8_t
// This overload prints a (const) char8_t array compactly.
GTEST_API_ void UniversalPrintArray(const char8_t* begin, size_t len,
                                    ::std::ostream* os);
#endif

// This overload prints a (const) char16_t array compactly.
GTEST_API_ void UniversalPrintArray(const char16_t* begin, size_t len,
                                    ::std::ostream* os);

// This overload prints a (const) char32_t array compactly.
GTEST_API_ void UniversalPrintArray(const char32_t* begin, size_t len,
                                    ::std::ostream* os);

822
823
824
// This overload prints a (const) wchar_t array compactly.
GTEST_API_ void UniversalPrintArray(
    const wchar_t* begin, size_t len, ::std::ostream* os);
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842

// Implements printing an array type T[N].
template <typename T, size_t N>
class UniversalPrinter<T[N]> {
 public:
  // Prints the given array, omitting some elements when there are too
  // many.
  static void Print(const T (&a)[N], ::std::ostream* os) {
    UniversalPrintArray(a, N, os);
  }
};

// Implements printing a reference type T&.
template <typename T>
class UniversalPrinter<T&> {
 public:
  // MSVC warns about adding const to a function type, so we want to
  // disable the warning.
billydonahue's avatar
billydonahue committed
843
  GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180)
844
845
846
847
848
849
850

  static void Print(const T& value, ::std::ostream* os) {
    // Prints the address of the value.  We use reinterpret_cast here
    // as static_cast doesn't compile when T is a function type.
    *os << "@" << reinterpret_cast<const void*>(&value) << " ";

    // Then prints the value itself.
851
    UniversalPrint(value, os);
852
853
  }

billydonahue's avatar
billydonahue committed
854
  GTEST_DISABLE_MSC_WARNINGS_POP_()
855
856
857
858
859
};

// Prints a value tersely: for a reference type, the referenced value
// (but not the address) is printed; for a (const) char pointer, the
// NUL-terminated string (but not the pointer) is printed.
860

861
template <typename T>
862
863
864
865
class UniversalTersePrinter {
 public:
  static void Print(const T& value, ::std::ostream* os) {
    UniversalPrint(value, os);
866
  }
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
};
template <typename T>
class UniversalTersePrinter<T&> {
 public:
  static void Print(const T& value, ::std::ostream* os) {
    UniversalPrint(value, os);
  }
};
template <typename T, size_t N>
class UniversalTersePrinter<T[N]> {
 public:
  static void Print(const T (&value)[N], ::std::ostream* os) {
    UniversalPrinter<T[N]>::Print(value, os);
  }
};
template <>
class UniversalTersePrinter<const char*> {
 public:
  static void Print(const char* str, ::std::ostream* os) {
886
    if (str == nullptr) {
887
888
      *os << "NULL";
    } else {
889
      UniversalPrint(std::string(str), os);
890
891
892
893
    }
  }
};
template <>
Abseil Team's avatar
Abseil Team committed
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
class UniversalTersePrinter<char*> : public UniversalTersePrinter<const char*> {
};

#ifdef __cpp_char8_t
template <>
class UniversalTersePrinter<const char8_t*> {
 public:
  static void Print(const char8_t* str, ::std::ostream* os) {
    if (str == nullptr) {
      *os << "NULL";
    } else {
      UniversalPrint(::std::u8string(str), os);
    }
  }
};
template <>
class UniversalTersePrinter<char8_t*>
    : public UniversalTersePrinter<const char8_t*> {};
#endif

template <>
class UniversalTersePrinter<const char16_t*> {
 public:
  static void Print(const char16_t* str, ::std::ostream* os) {
    if (str == nullptr) {
      *os << "NULL";
    } else {
      UniversalPrint(::std::u16string(str), os);
    }
  }
};
template <>
class UniversalTersePrinter<char16_t*>
    : public UniversalTersePrinter<const char16_t*> {};

template <>
class UniversalTersePrinter<const char32_t*> {
931
 public:
Abseil Team's avatar
Abseil Team committed
932
933
934
935
936
937
  static void Print(const char32_t* str, ::std::ostream* os) {
    if (str == nullptr) {
      *os << "NULL";
    } else {
      UniversalPrint(::std::u32string(str), os);
    }
938
939
  }
};
Abseil Team's avatar
Abseil Team committed
940
941
942
template <>
class UniversalTersePrinter<char32_t*>
    : public UniversalTersePrinter<const char32_t*> {};
943
944
945
946
947
948

#if GTEST_HAS_STD_WSTRING
template <>
class UniversalTersePrinter<const wchar_t*> {
 public:
  static void Print(const wchar_t* str, ::std::ostream* os) {
949
    if (str == nullptr) {
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
      *os << "NULL";
    } else {
      UniversalPrint(::std::wstring(str), os);
    }
  }
};
#endif

template <>
class UniversalTersePrinter<wchar_t*> {
 public:
  static void Print(wchar_t* str, ::std::ostream* os) {
    UniversalTersePrinter<const wchar_t*>::Print(str, os);
  }
};

template <typename T>
void UniversalTersePrint(const T& value, ::std::ostream* os) {
  UniversalTersePrinter<T>::Print(value, os);
969
970
971
972
973
974
975
976
}

// Prints a value using the type inferred by the compiler.  The
// difference between this and UniversalTersePrint() is that for a
// (const) char pointer, this prints both the pointer and the
// NUL-terminated string.
template <typename T>
void UniversalPrint(const T& value, ::std::ostream* os) {
vladlosev's avatar
vladlosev committed
977
978
979
980
  // A workarond for the bug in VC++ 7.1 that prevents us from instantiating
  // UniversalPrinter with T directly.
  typedef T T1;
  UniversalPrinter<T1>::Print(value, os);
981
982
}

Gennadiy Civil's avatar
Gennadiy Civil committed
983
typedef ::std::vector< ::std::string> Strings;
984
985
986

  // Tersely prints the first N fields of a tuple to a string vector,
  // one element for each field.
987
template <typename Tuple>
Abseil Team's avatar
Abseil Team committed
988
989
990
991
992
993
994
995
996
997
998
void TersePrintPrefixToStrings(const Tuple&, std::integral_constant<size_t, 0>,
                               Strings*) {}
template <typename Tuple, size_t I>
void TersePrintPrefixToStrings(const Tuple& t,
                               std::integral_constant<size_t, I>,
                               Strings* strings) {
  TersePrintPrefixToStrings(t, std::integral_constant<size_t, I - 1>(),
                            strings);
  ::std::stringstream ss;
  UniversalTersePrint(std::get<I - 1>(t), &ss);
  strings->push_back(ss.str());
999
1000
1001
1002
1003
1004
1005
1006
}

// Prints the fields of a tuple tersely to a string vector, one
// element for each field.  See the comment before
// UniversalTersePrint() for how we define "tersely".
template <typename Tuple>
Strings UniversalTersePrintTupleFieldsToStrings(const Tuple& value) {
  Strings result;
Abseil Team's avatar
Abseil Team committed
1007
1008
1009
  TersePrintPrefixToStrings(
      value, std::integral_constant<size_t, std::tuple_size<Tuple>::value>(),
      &result);
1010
1011
1012
1013
1014
1015
1016
1017
  return result;
}

}  // namespace internal

template <typename T>
::std::string PrintToString(const T& value) {
  ::std::stringstream ss;
1018
  internal::UniversalTersePrinter<T>::Print(value, &ss);
1019
1020
1021
1022
1023
  return ss.str();
}

}  // namespace testing

kosak's avatar
kosak committed
1024
1025
1026
1027
1028
// Include any custom printer added by the local installation.
// We must include this header at the end to make sure it can use the
// declarations from this file.
#include "gtest/internal/custom/gtest-printers.h"

Abseil Team's avatar
Abseil Team committed
1029
#endif  // GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_