1 // Copyright 2007, Google Inc.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
8 //     * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 //     * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
13 // distribution.
14 //     * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
17 //
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 
30 
31 // Google Test - The Google C++ Testing and Mocking Framework
32 //
33 // This file implements a universal value printer that can print a
34 // value of any type T:
35 //
36 //   void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
37 //
38 // A user can teach this function how to print a class type T by
39 // defining either operator<<() or PrintTo() in the namespace that
40 // defines T.  More specifically, the FIRST defined function in the
41 // following list will be used (assuming T is defined in namespace
42 // foo):
43 //
44 //   1. foo::PrintTo(const T&, ostream*)
45 //   2. operator<<(ostream&, const T&) defined in either foo or the
46 //      global namespace.
47 //
48 // However if T is an STL-style container then it is printed element-wise
49 // unless foo::PrintTo(const T&, ostream*) is defined. Note that
50 // operator<<() is ignored for container types.
51 //
52 // If none of the above is defined, it will print the debug string of
53 // the value if it is a protocol buffer, or print the raw bytes in the
54 // value otherwise.
55 //
56 // To aid debugging: when T is a reference type, the address of the
57 // value is also printed; when T is a (const) char pointer, both the
58 // pointer value and the NUL-terminated string it points to are
59 // printed.
60 //
61 // We also provide some convenient wrappers:
62 //
63 //   // Prints a value to a string.  For a (const or not) char
64 //   // pointer, the NUL-terminated string (but not the pointer) is
65 //   // printed.
66 //   std::string ::testing::PrintToString(const T& value);
67 //
68 //   // Prints a value tersely: for a reference type, the referenced
69 //   // value (but not the address) is printed; for a (const or not) char
70 //   // pointer, the NUL-terminated string (but not the pointer) is
71 //   // printed.
72 //   void ::testing::internal::UniversalTersePrint(const T& value, ostream*);
73 //
74 //   // Prints value using the type inferred by the compiler.  The difference
75 //   // from UniversalTersePrint() is that this function prints both the
76 //   // pointer and the NUL-terminated string for a (const or not) char pointer.
77 //   void ::testing::internal::UniversalPrint(const T& value, ostream*);
78 //
79 //   // Prints the fields of a tuple tersely to a string vector, one
80 //   // element for each field. Tuple support must be enabled in
81 //   // gtest-port.h.
82 //   std::vector<string> UniversalTersePrintTupleFieldsToStrings(
83 //       const Tuple& value);
84 //
85 // Known limitation:
86 //
87 // The print primitives print the elements of an STL-style container
88 // using the compiler-inferred type of *iter where iter is a
89 // const_iterator of the container.  When const_iterator is an input
90 // iterator but not a forward iterator, this inferred type may not
91 // match value_type, and the print output may be incorrect.  In
92 // practice, this is rarely a problem as for most containers
93 // const_iterator is a forward iterator.  We'll fix this if there's an
94 // actual need for it.  Note that this fix cannot rely on value_type
95 // being defined as many user-defined container types don't have
96 // value_type.
97 
98 #ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
99 #define GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
100 
101 #include <functional>
102 #include <memory>
103 #include <ostream>  // NOLINT
104 #include <sstream>
105 #include <string>
106 #include <tuple>
107 #include <type_traits>
108 #include <utility>
109 #include <vector>
110 
111 #include "gtest/internal/gtest-internal.h"
112 #include "gtest/internal/gtest-port.h"
113 
114 namespace testing {
115 
116 // Definitions in the internal* namespaces are subject to change without notice.
117 // DO NOT USE THEM IN USER CODE!
118 namespace internal {
119 
120 template <typename T>
121 void UniversalPrint(const T& value, ::std::ostream* os);
122 
123 // Used to print an STL-style container when the user doesn't define
124 // a PrintTo() for it.
125 struct ContainerPrinter {
126   template <typename T,
127             typename = typename std::enable_if<
128                 (sizeof(IsContainerTest<T>(0)) == sizeof(IsContainer)) &&
129                 !IsRecursiveContainer<T>::value>::type>
PrintValueContainerPrinter130   static void PrintValue(const T& container, std::ostream* os) {
131     const size_t kMaxCount = 32;  // The maximum number of elements to print.
132     *os << '{';
133     size_t count = 0;
134     for (auto&& elem : container) {
135       if (count > 0) {
136         *os << ',';
137         if (count == kMaxCount) {  // Enough has been printed.
138           *os << " ...";
139           break;
140         }
141       }
142       *os << ' ';
143       // We cannot call PrintTo(elem, os) here as PrintTo() doesn't
144       // handle `elem` being a native array.
145       internal::UniversalPrint(elem, os);
146       ++count;
147     }
148 
149     if (count > 0) {
150       *os << ' ';
151     }
152     *os << '}';
153   }
154 };
155 
156 // Used to print a pointer that is neither a char pointer nor a member
157 // pointer, when the user doesn't define PrintTo() for it.  (A member
158 // variable pointer or member function pointer doesn't really point to
159 // a location in the address space.  Their representation is
160 // implementation-defined.  Therefore they will be printed as raw
161 // bytes.)
162 struct FunctionPointerPrinter {
163   template <typename T, typename = typename std::enable_if<
164                             std::is_function<T>::value>::type>
PrintValueFunctionPointerPrinter165   static void PrintValue(T* p, ::std::ostream* os) {
166     if (p == nullptr) {
167       *os << "NULL";
168     } else {
169       // T is a function type, so '*os << p' doesn't do what we want
170       // (it just prints p as bool).  We want to print p as a const
171       // void*.
172       *os << reinterpret_cast<const void*>(p);
173     }
174   }
175 };
176 
177 struct PointerPrinter {
178   template <typename T>
PrintValuePointerPrinter179   static void PrintValue(T* p, ::std::ostream* os) {
180     if (p == nullptr) {
181       *os << "NULL";
182     } else {
183       // T is not a function type.  We just call << to print p,
184       // relying on ADL to pick up user-defined << for their pointer
185       // types, if any.
186       *os << p;
187     }
188   }
189 };
190 
191 namespace internal_stream_operator_without_lexical_name_lookup {
192 
193 // The presence of an operator<< here will terminate lexical scope lookup
194 // straight away (even though it cannot be a match because of its argument
195 // types). Thus, the two operator<< calls in StreamPrinter will find only ADL
196 // candidates.
197 struct LookupBlocker {};
198 void operator<<(LookupBlocker, LookupBlocker);
199 
200 struct StreamPrinter {
201   template <typename T,
202             // Don't accept member pointers here. We'd print them via implicit
203             // conversion to bool, which isn't useful.
204             typename = typename std::enable_if<
205                 !std::is_member_pointer<T>::value>::type,
206             // Only accept types for which we can find a streaming operator via
207             // ADL (possibly involving implicit conversions).
208             typename = decltype(std::declval<std::ostream&>()
209                                 << std::declval<const T&>())>
PrintValueStreamPrinter210   static void PrintValue(const T& value, ::std::ostream* os) {
211     // Call streaming operator found by ADL, possibly with implicit conversions
212     // of the arguments.
213     *os << value;
214   }
215 };
216 
217 }  // namespace internal_stream_operator_without_lexical_name_lookup
218 
219 struct ProtobufPrinter {
220   // We print a protobuf using its ShortDebugString() when the string
221   // doesn't exceed this many characters; otherwise we print it using
222   // DebugString() for better readability.
223   static const size_t kProtobufOneLinerMaxLength = 50;
224 
225   template <typename T,
226             typename = typename std::enable_if<
227                 internal::HasDebugStringAndShortDebugString<T>::value>::type>
PrintValueProtobufPrinter228   static void PrintValue(const T& value, ::std::ostream* os) {
229     std::string pretty_str = value.ShortDebugString();
230     if (pretty_str.length() > kProtobufOneLinerMaxLength) {
231       pretty_str = "\n" + value.DebugString();
232     }
233     *os << ("<" + pretty_str + ">");
234   }
235 };
236 
237 struct ConvertibleToIntegerPrinter {
238   // Since T has no << operator or PrintTo() but can be implicitly
239   // converted to BiggestInt, we print it as a BiggestInt.
240   //
241   // Most likely T is an enum type (either named or unnamed), in which
242   // case printing it as an integer is the desired behavior.  In case
243   // T is not an enum, printing it as an integer is the best we can do
244   // given that it has no user-defined printer.
PrintValueConvertibleToIntegerPrinter245   static void PrintValue(internal::BiggestInt value, ::std::ostream* os) {
246     *os << value;
247   }
248 };
249 
250 struct ConvertibleToStringViewPrinter {
251 #if GTEST_INTERNAL_HAS_STRING_VIEW
PrintValueConvertibleToStringViewPrinter252   static void PrintValue(internal::StringView value, ::std::ostream* os) {
253     internal::UniversalPrint(value, os);
254   }
255 #endif
256 };
257 
258 
259 // Prints the given number of bytes in the given object to the given
260 // ostream.
261 GTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes,
262                                      size_t count,
263                                      ::std::ostream* os);
264 struct RawBytesPrinter {
265   // SFINAE on `sizeof` to make sure we have a complete type.
266   template <typename T, size_t = sizeof(T)>
PrintValueRawBytesPrinter267   static void PrintValue(const T& value, ::std::ostream* os) {
268     PrintBytesInObjectTo(
269         static_cast<const unsigned char*>(
270             // Load bearing cast to void* to support iOS
271             reinterpret_cast<const void*>(std::addressof(value))),
272         sizeof(value), os);
273   }
274 };
275 
276 struct FallbackPrinter {
277   template <typename T>
PrintValueFallbackPrinter278   static void PrintValue(const T&, ::std::ostream* os) {
279     *os << "(incomplete type)";
280   }
281 };
282 
283 // Try every printer in order and return the first one that works.
284 template <typename T, typename E, typename Printer, typename... Printers>
285 struct FindFirstPrinter : FindFirstPrinter<T, E, Printers...> {};
286 
287 template <typename T, typename Printer, typename... Printers>
288 struct FindFirstPrinter<
289     T, decltype(Printer::PrintValue(std::declval<const T&>(), nullptr)),
290     Printer, Printers...> {
291   using type = Printer;
292 };
293 
294 // Select the best printer in the following order:
295 //  - Print containers (they have begin/end/etc).
296 //  - Print function pointers.
297 //  - Print object pointers.
298 //  - Use the stream operator, if available.
299 //  - Print protocol buffers.
300 //  - Print types convertible to BiggestInt.
301 //  - Print types convertible to StringView, if available.
302 //  - Fallback to printing the raw bytes of the object.
303 template <typename T>
304 void PrintWithFallback(const T& value, ::std::ostream* os) {
305   using Printer = typename FindFirstPrinter<
306       T, void, ContainerPrinter, FunctionPointerPrinter, PointerPrinter,
307       internal_stream_operator_without_lexical_name_lookup::StreamPrinter,
308       ProtobufPrinter, ConvertibleToIntegerPrinter,
309       ConvertibleToStringViewPrinter, RawBytesPrinter, FallbackPrinter>::type;
310   Printer::PrintValue(value, os);
311 }
312 
313 // FormatForComparison<ToPrint, OtherOperand>::Format(value) formats a
314 // value of type ToPrint that is an operand of a comparison assertion
315 // (e.g. ASSERT_EQ).  OtherOperand is the type of the other operand in
316 // the comparison, and is used to help determine the best way to
317 // format the value.  In particular, when the value is a C string
318 // (char pointer) and the other operand is an STL string object, we
319 // want to format the C string as a string, since we know it is
320 // compared by value with the string object.  If the value is a char
321 // pointer but the other operand is not an STL string object, we don't
322 // know whether the pointer is supposed to point to a NUL-terminated
323 // string, and thus want to print it as a pointer to be safe.
324 //
325 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
326 
327 // The default case.
328 template <typename ToPrint, typename OtherOperand>
329 class FormatForComparison {
330  public:
331   static ::std::string Format(const ToPrint& value) {
332     return ::testing::PrintToString(value);
333   }
334 };
335 
336 // Array.
337 template <typename ToPrint, size_t N, typename OtherOperand>
338 class FormatForComparison<ToPrint[N], OtherOperand> {
339  public:
340   static ::std::string Format(const ToPrint* value) {
341     return FormatForComparison<const ToPrint*, OtherOperand>::Format(value);
342   }
343 };
344 
345 // By default, print C string as pointers to be safe, as we don't know
346 // whether they actually point to a NUL-terminated string.
347 
348 #define GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(CharType)                \
349   template <typename OtherOperand>                                      \
350   class FormatForComparison<CharType*, OtherOperand> {                  \
351    public:                                                              \
352     static ::std::string Format(CharType* value) {                      \
353       return ::testing::PrintToString(static_cast<const void*>(value)); \
354     }                                                                   \
355   }
356 
357 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char);
358 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char);
359 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(wchar_t);
360 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const wchar_t);
361 #ifdef __cpp_lib_char8_t
362 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char8_t);
363 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char8_t);
364 #endif
365 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char16_t);
366 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char16_t);
367 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char32_t);
368 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char32_t);
369 
370 #undef GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_
371 
372 // If a C string is compared with an STL string object, we know it's meant
373 // to point to a NUL-terminated string, and thus can print it as a string.
374 
375 #define GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(CharType, OtherStringType) \
376   template <>                                                           \
377   class FormatForComparison<CharType*, OtherStringType> {               \
378    public:                                                              \
379     static ::std::string Format(CharType* value) {                      \
380       return ::testing::PrintToString(value);                           \
381     }                                                                   \
382   }
383 
384 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::std::string);
385 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char, ::std::string);
386 #ifdef __cpp_char8_t
387 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char8_t, ::std::u8string);
388 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char8_t, ::std::u8string);
389 #endif
390 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char16_t, ::std::u16string);
391 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char16_t, ::std::u16string);
392 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char32_t, ::std::u32string);
393 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char32_t, ::std::u32string);
394 
395 #if GTEST_HAS_STD_WSTRING
396 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(wchar_t, ::std::wstring);
397 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const wchar_t, ::std::wstring);
398 #endif
399 
400 #undef GTEST_IMPL_FORMAT_C_STRING_AS_STRING_
401 
402 // Formats a comparison assertion (e.g. ASSERT_EQ, EXPECT_LT, and etc)
403 // operand to be used in a failure message.  The type (but not value)
404 // of the other operand may affect the format.  This allows us to
405 // print a char* as a raw pointer when it is compared against another
406 // char* or void*, and print it as a C string when it is compared
407 // against an std::string object, for example.
408 //
409 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
410 template <typename T1, typename T2>
411 std::string FormatForComparisonFailureMessage(
412     const T1& value, const T2& /* other_operand */) {
413   return FormatForComparison<T1, T2>::Format(value);
414 }
415 
416 // UniversalPrinter<T>::Print(value, ostream_ptr) prints the given
417 // value to the given ostream.  The caller must ensure that
418 // 'ostream_ptr' is not NULL, or the behavior is undefined.
419 //
420 // We define UniversalPrinter as a class template (as opposed to a
421 // function template), as we need to partially specialize it for
422 // reference types, which cannot be done with function templates.
423 template <typename T>
424 class UniversalPrinter;
425 
426 // Prints the given value using the << operator if it has one;
427 // otherwise prints the bytes in it.  This is what
428 // UniversalPrinter<T>::Print() does when PrintTo() is not specialized
429 // or overloaded for type T.
430 //
431 // A user can override this behavior for a class type Foo by defining
432 // an overload of PrintTo() in the namespace where Foo is defined.  We
433 // give the user this option as sometimes defining a << operator for
434 // Foo is not desirable (e.g. the coding style may prevent doing it,
435 // or there is already a << operator but it doesn't do what the user
436 // wants).
437 template <typename T>
438 void PrintTo(const T& value, ::std::ostream* os) {
439   internal::PrintWithFallback(value, os);
440 }
441 
442 // The following list of PrintTo() overloads tells
443 // UniversalPrinter<T>::Print() how to print standard types (built-in
444 // types, strings, plain arrays, and pointers).
445 
446 // Overloads for various char types.
447 GTEST_API_ void PrintTo(unsigned char c, ::std::ostream* os);
448 GTEST_API_ void PrintTo(signed char c, ::std::ostream* os);
449 inline void PrintTo(char c, ::std::ostream* os) {
450   // When printing a plain char, we always treat it as unsigned.  This
451   // way, the output won't be affected by whether the compiler thinks
452   // char is signed or not.
453   PrintTo(static_cast<unsigned char>(c), os);
454 }
455 
456 // Overloads for other simple built-in types.
457 inline void PrintTo(bool x, ::std::ostream* os) {
458   *os << (x ? "true" : "false");
459 }
460 
461 // Overload for wchar_t type.
462 // Prints a wchar_t as a symbol if it is printable or as its internal
463 // code otherwise and also as its decimal code (except for L'\0').
464 // The L'\0' char is printed as "L'\\0'". The decimal code is printed
465 // as signed integer when wchar_t is implemented by the compiler
466 // as a signed type and is printed as an unsigned integer when wchar_t
467 // is implemented as an unsigned type.
468 GTEST_API_ void PrintTo(wchar_t wc, ::std::ostream* os);
469 
470 GTEST_API_ void PrintTo(char32_t c, ::std::ostream* os);
471 inline void PrintTo(char16_t c, ::std::ostream* os) {
472   PrintTo(ImplicitCast_<char32_t>(c), os);
473 }
474 #ifdef __cpp_char8_t
475 inline void PrintTo(char8_t c, ::std::ostream* os) {
476   PrintTo(ImplicitCast_<char32_t>(c), os);
477 }
478 #endif
479 
480 // Overloads for C strings.
481 GTEST_API_ void PrintTo(const char* s, ::std::ostream* os);
482 inline void PrintTo(char* s, ::std::ostream* os) {
483   PrintTo(ImplicitCast_<const char*>(s), os);
484 }
485 
486 // signed/unsigned char is often used for representing binary data, so
487 // we print pointers to it as void* to be safe.
488 inline void PrintTo(const signed char* s, ::std::ostream* os) {
489   PrintTo(ImplicitCast_<const void*>(s), os);
490 }
491 inline void PrintTo(signed char* s, ::std::ostream* os) {
492   PrintTo(ImplicitCast_<const void*>(s), os);
493 }
494 inline void PrintTo(const unsigned char* s, ::std::ostream* os) {
495   PrintTo(ImplicitCast_<const void*>(s), os);
496 }
497 inline void PrintTo(unsigned char* s, ::std::ostream* os) {
498   PrintTo(ImplicitCast_<const void*>(s), os);
499 }
500 #ifdef __cpp_char8_t
501 // Overloads for u8 strings.
502 GTEST_API_ void PrintTo(const char8_t* s, ::std::ostream* os);
503 inline void PrintTo(char8_t* s, ::std::ostream* os) {
504   PrintTo(ImplicitCast_<const char8_t*>(s), os);
505 }
506 #endif
507 // Overloads for u16 strings.
508 GTEST_API_ void PrintTo(const char16_t* s, ::std::ostream* os);
509 inline void PrintTo(char16_t* s, ::std::ostream* os) {
510   PrintTo(ImplicitCast_<const char16_t*>(s), os);
511 }
512 // Overloads for u32 strings.
513 GTEST_API_ void PrintTo(const char32_t* s, ::std::ostream* os);
514 inline void PrintTo(char32_t* s, ::std::ostream* os) {
515   PrintTo(ImplicitCast_<const char32_t*>(s), os);
516 }
517 
518 // MSVC can be configured to define wchar_t as a typedef of unsigned
519 // short.  It defines _NATIVE_WCHAR_T_DEFINED when wchar_t is a native
520 // type.  When wchar_t is a typedef, defining an overload for const
521 // wchar_t* would cause unsigned short* be printed as a wide string,
522 // possibly causing invalid memory accesses.
523 #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
524 // Overloads for wide C strings
525 GTEST_API_ void PrintTo(const wchar_t* s, ::std::ostream* os);
526 inline void PrintTo(wchar_t* s, ::std::ostream* os) {
527   PrintTo(ImplicitCast_<const wchar_t*>(s), os);
528 }
529 #endif
530 
531 // Overload for C arrays.  Multi-dimensional arrays are printed
532 // properly.
533 
534 // Prints the given number of elements in an array, without printing
535 // the curly braces.
536 template <typename T>
537 void PrintRawArrayTo(const T a[], size_t count, ::std::ostream* os) {
538   UniversalPrint(a[0], os);
539   for (size_t i = 1; i != count; i++) {
540     *os << ", ";
541     UniversalPrint(a[i], os);
542   }
543 }
544 
545 // Overloads for ::std::string.
546 GTEST_API_ void PrintStringTo(const ::std::string&s, ::std::ostream* os);
547 inline void PrintTo(const ::std::string& s, ::std::ostream* os) {
548   PrintStringTo(s, os);
549 }
550 
551 // Overloads for ::std::u8string
552 #ifdef __cpp_char8_t
553 GTEST_API_ void PrintU8StringTo(const ::std::u8string& s, ::std::ostream* os);
554 inline void PrintTo(const ::std::u8string& s, ::std::ostream* os) {
555   PrintU8StringTo(s, os);
556 }
557 #endif
558 
559 // Overloads for ::std::u16string
560 GTEST_API_ void PrintU16StringTo(const ::std::u16string& s, ::std::ostream* os);
561 inline void PrintTo(const ::std::u16string& s, ::std::ostream* os) {
562   PrintU16StringTo(s, os);
563 }
564 
565 // Overloads for ::std::u32string
566 GTEST_API_ void PrintU32StringTo(const ::std::u32string& s, ::std::ostream* os);
567 inline void PrintTo(const ::std::u32string& s, ::std::ostream* os) {
568   PrintU32StringTo(s, os);
569 }
570 
571 // Overloads for ::std::wstring.
572 #if GTEST_HAS_STD_WSTRING
573 GTEST_API_ void PrintWideStringTo(const ::std::wstring&s, ::std::ostream* os);
574 inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) {
575   PrintWideStringTo(s, os);
576 }
577 #endif  // GTEST_HAS_STD_WSTRING
578 
579 #if GTEST_INTERNAL_HAS_STRING_VIEW
580 // Overload for internal::StringView.
581 inline void PrintTo(internal::StringView sp, ::std::ostream* os) {
582   PrintTo(::std::string(sp), os);
583 }
584 #endif  // GTEST_INTERNAL_HAS_STRING_VIEW
585 
586 inline void PrintTo(std::nullptr_t, ::std::ostream* os) { *os << "(nullptr)"; }
587 
588 template <typename T>
589 void PrintTo(std::reference_wrapper<T> ref, ::std::ostream* os) {
590   UniversalPrinter<T&>::Print(ref.get(), os);
591 }
592 
593 inline const void* VoidifyPointer(const void* p) { return p; }
594 inline const void* VoidifyPointer(volatile const void* p) {
595   return const_cast<const void*>(p);
596 }
597 
598 template <typename T, typename Ptr>
599 void PrintSmartPointer(const Ptr& ptr, std::ostream* os, char) {
600   if (ptr == nullptr) {
601     *os << "(nullptr)";
602   } else {
603     // We can't print the value. Just print the pointer..
604     *os << "(" << (VoidifyPointer)(ptr.get()) << ")";
605   }
606 }
607 template <typename T, typename Ptr,
608           typename = typename std::enable_if<!std::is_void<T>::value &&
609                                              !std::is_array<T>::value>::type>
610 void PrintSmartPointer(const Ptr& ptr, std::ostream* os, int) {
611   if (ptr == nullptr) {
612     *os << "(nullptr)";
613   } else {
614     *os << "(ptr = " << (VoidifyPointer)(ptr.get()) << ", value = ";
615     UniversalPrinter<T>::Print(*ptr, os);
616     *os << ")";
617   }
618 }
619 
620 template <typename T, typename D>
621 void PrintTo(const std::unique_ptr<T, D>& ptr, std::ostream* os) {
622   (PrintSmartPointer<T>)(ptr, os, 0);
623 }
624 
625 template <typename T>
626 void PrintTo(const std::shared_ptr<T>& ptr, std::ostream* os) {
627   (PrintSmartPointer<T>)(ptr, os, 0);
628 }
629 
630 // Helper function for printing a tuple.  T must be instantiated with
631 // a tuple type.
632 template <typename T>
633 void PrintTupleTo(const T&, std::integral_constant<size_t, 0>,
634                   ::std::ostream*) {}
635 
636 template <typename T, size_t I>
637 void PrintTupleTo(const T& t, std::integral_constant<size_t, I>,
638                   ::std::ostream* os) {
639   PrintTupleTo(t, std::integral_constant<size_t, I - 1>(), os);
640   GTEST_INTENTIONAL_CONST_COND_PUSH_()
641   if (I > 1) {
642     GTEST_INTENTIONAL_CONST_COND_POP_()
643     *os << ", ";
644   }
645   UniversalPrinter<typename std::tuple_element<I - 1, T>::type>::Print(
646       std::get<I - 1>(t), os);
647 }
648 
649 template <typename... Types>
650 void PrintTo(const ::std::tuple<Types...>& t, ::std::ostream* os) {
651   *os << "(";
652   PrintTupleTo(t, std::integral_constant<size_t, sizeof...(Types)>(), os);
653   *os << ")";
654 }
655 
656 // Overload for std::pair.
657 template <typename T1, typename T2>
658 void PrintTo(const ::std::pair<T1, T2>& value, ::std::ostream* os) {
659   *os << '(';
660   // We cannot use UniversalPrint(value.first, os) here, as T1 may be
661   // a reference type.  The same for printing value.second.
662   UniversalPrinter<T1>::Print(value.first, os);
663   *os << ", ";
664   UniversalPrinter<T2>::Print(value.second, os);
665   *os << ')';
666 }
667 
668 // Implements printing a non-reference type T by letting the compiler
669 // pick the right overload of PrintTo() for T.
670 template <typename T>
671 class UniversalPrinter {
672  public:
673   // MSVC warns about adding const to a function type, so we want to
674   // disable the warning.
675   GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180)
676 
677   // Note: we deliberately don't call this PrintTo(), as that name
678   // conflicts with ::testing::internal::PrintTo in the body of the
679   // function.
680   static void Print(const T& value, ::std::ostream* os) {
681     // By default, ::testing::internal::PrintTo() is used for printing
682     // the value.
683     //
684     // Thanks to Koenig look-up, if T is a class and has its own
685     // PrintTo() function defined in its namespace, that function will
686     // be visible here.  Since it is more specific than the generic ones
687     // in ::testing::internal, it will be picked by the compiler in the
688     // following statement - exactly what we want.
689     PrintTo(value, os);
690   }
691 
692   GTEST_DISABLE_MSC_WARNINGS_POP_()
693 };
694 
695 // Remove any const-qualifiers before passing a type to UniversalPrinter.
696 template <typename T>
697 class UniversalPrinter<const T> : public UniversalPrinter<T> {};
698 
699 #if GTEST_INTERNAL_HAS_ANY
700 
701 // Printer for std::any / absl::any
702 
703 template <>
704 class UniversalPrinter<Any> {
705  public:
706   static void Print(const Any& value, ::std::ostream* os) {
707     if (value.has_value()) {
708       *os << "value of type " << GetTypeName(value);
709     } else {
710       *os << "no value";
711     }
712   }
713 
714  private:
715   static std::string GetTypeName(const Any& value) {
716 #if GTEST_HAS_RTTI
717     return internal::GetTypeName(value.type());
718 #else
719     static_cast<void>(value);  // possibly unused
720     return "<unknown_type>";
721 #endif  // GTEST_HAS_RTTI
722   }
723 };
724 
725 #endif  // GTEST_INTERNAL_HAS_ANY
726 
727 #if GTEST_INTERNAL_HAS_OPTIONAL
728 
729 // Printer for std::optional / absl::optional
730 
731 template <typename T>
732 class UniversalPrinter<Optional<T>> {
733  public:
734   static void Print(const Optional<T>& value, ::std::ostream* os) {
735     *os << '(';
736     if (!value) {
737       *os << "nullopt";
738     } else {
739       UniversalPrint(*value, os);
740     }
741     *os << ')';
742   }
743 };
744 
745 template <>
746 class UniversalPrinter<decltype(Nullopt())> {
747  public:
748   static void Print(decltype(Nullopt()), ::std::ostream* os) {
749     *os << "(nullopt)";
750   }
751 };
752 
753 #endif  // GTEST_INTERNAL_HAS_OPTIONAL
754 
755 #if GTEST_INTERNAL_HAS_VARIANT
756 
757 // Printer for std::variant / absl::variant
758 
759 template <typename... T>
760 class UniversalPrinter<Variant<T...>> {
761  public:
762   static void Print(const Variant<T...>& value, ::std::ostream* os) {
763     *os << '(';
764 #if GTEST_HAS_ABSL
765     absl::visit(Visitor{os, value.index()}, value);
766 #else
767     std::visit(Visitor{os, value.index()}, value);
768 #endif  // GTEST_HAS_ABSL
769     *os << ')';
770   }
771 
772  private:
773   struct Visitor {
774     template <typename U>
775     void operator()(const U& u) const {
776       *os << "'" << GetTypeName<U>() << "(index = " << index
777           << ")' with value ";
778       UniversalPrint(u, os);
779     }
780     ::std::ostream* os;
781     std::size_t index;
782   };
783 };
784 
785 #endif  // GTEST_INTERNAL_HAS_VARIANT
786 
787 // UniversalPrintArray(begin, len, os) prints an array of 'len'
788 // elements, starting at address 'begin'.
789 template <typename T>
790 void UniversalPrintArray(const T* begin, size_t len, ::std::ostream* os) {
791   if (len == 0) {
792     *os << "{}";
793   } else {
794     *os << "{ ";
795     const size_t kThreshold = 18;
796     const size_t kChunkSize = 8;
797     // If the array has more than kThreshold elements, we'll have to
798     // omit some details by printing only the first and the last
799     // kChunkSize elements.
800     if (len <= kThreshold) {
801       PrintRawArrayTo(begin, len, os);
802     } else {
803       PrintRawArrayTo(begin, kChunkSize, os);
804       *os << ", ..., ";
805       PrintRawArrayTo(begin + len - kChunkSize, kChunkSize, os);
806     }
807     *os << " }";
808   }
809 }
810 // This overload prints a (const) char array compactly.
811 GTEST_API_ void UniversalPrintArray(
812     const char* begin, size_t len, ::std::ostream* os);
813 
814 #ifdef __cpp_char8_t
815 // This overload prints a (const) char8_t array compactly.
816 GTEST_API_ void UniversalPrintArray(const char8_t* begin, size_t len,
817                                     ::std::ostream* os);
818 #endif
819 
820 // This overload prints a (const) char16_t array compactly.
821 GTEST_API_ void UniversalPrintArray(const char16_t* begin, size_t len,
822                                     ::std::ostream* os);
823 
824 // This overload prints a (const) char32_t array compactly.
825 GTEST_API_ void UniversalPrintArray(const char32_t* begin, size_t len,
826                                     ::std::ostream* os);
827 
828 // This overload prints a (const) wchar_t array compactly.
829 GTEST_API_ void UniversalPrintArray(
830     const wchar_t* begin, size_t len, ::std::ostream* os);
831 
832 // Implements printing an array type T[N].
833 template <typename T, size_t N>
834 class UniversalPrinter<T[N]> {
835  public:
836   // Prints the given array, omitting some elements when there are too
837   // many.
838   static void Print(const T (&a)[N], ::std::ostream* os) {
839     UniversalPrintArray(a, N, os);
840   }
841 };
842 
843 // Implements printing a reference type T&.
844 template <typename T>
845 class UniversalPrinter<T&> {
846  public:
847   // MSVC warns about adding const to a function type, so we want to
848   // disable the warning.
849   GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180)
850 
851   static void Print(const T& value, ::std::ostream* os) {
852     // Prints the address of the value.  We use reinterpret_cast here
853     // as static_cast doesn't compile when T is a function type.
854     *os << "@" << reinterpret_cast<const void*>(&value) << " ";
855 
856     // Then prints the value itself.
857     UniversalPrint(value, os);
858   }
859 
860   GTEST_DISABLE_MSC_WARNINGS_POP_()
861 };
862 
863 // Prints a value tersely: for a reference type, the referenced value
864 // (but not the address) is printed; for a (const) char pointer, the
865 // NUL-terminated string (but not the pointer) is printed.
866 
867 template <typename T>
868 class UniversalTersePrinter {
869  public:
870   static void Print(const T& value, ::std::ostream* os) {
871     UniversalPrint(value, os);
872   }
873 };
874 template <typename T>
875 class UniversalTersePrinter<T&> {
876  public:
877   static void Print(const T& value, ::std::ostream* os) {
878     UniversalPrint(value, os);
879   }
880 };
881 template <typename T, size_t N>
882 class UniversalTersePrinter<T[N]> {
883  public:
884   static void Print(const T (&value)[N], ::std::ostream* os) {
885     UniversalPrinter<T[N]>::Print(value, os);
886   }
887 };
888 template <>
889 class UniversalTersePrinter<const char*> {
890  public:
891   static void Print(const char* str, ::std::ostream* os) {
892     if (str == nullptr) {
893       *os << "NULL";
894     } else {
895       UniversalPrint(std::string(str), os);
896     }
897   }
898 };
899 template <>
900 class UniversalTersePrinter<char*> : public UniversalTersePrinter<const char*> {
901 };
902 
903 #ifdef __cpp_char8_t
904 template <>
905 class UniversalTersePrinter<const char8_t*> {
906  public:
907   static void Print(const char8_t* str, ::std::ostream* os) {
908     if (str == nullptr) {
909       *os << "NULL";
910     } else {
911       UniversalPrint(::std::u8string(str), os);
912     }
913   }
914 };
915 template <>
916 class UniversalTersePrinter<char8_t*>
917     : public UniversalTersePrinter<const char8_t*> {};
918 #endif
919 
920 template <>
921 class UniversalTersePrinter<const char16_t*> {
922  public:
923   static void Print(const char16_t* str, ::std::ostream* os) {
924     if (str == nullptr) {
925       *os << "NULL";
926     } else {
927       UniversalPrint(::std::u16string(str), os);
928     }
929   }
930 };
931 template <>
932 class UniversalTersePrinter<char16_t*>
933     : public UniversalTersePrinter<const char16_t*> {};
934 
935 template <>
936 class UniversalTersePrinter<const char32_t*> {
937  public:
938   static void Print(const char32_t* str, ::std::ostream* os) {
939     if (str == nullptr) {
940       *os << "NULL";
941     } else {
942       UniversalPrint(::std::u32string(str), os);
943     }
944   }
945 };
946 template <>
947 class UniversalTersePrinter<char32_t*>
948     : public UniversalTersePrinter<const char32_t*> {};
949 
950 #if GTEST_HAS_STD_WSTRING
951 template <>
952 class UniversalTersePrinter<const wchar_t*> {
953  public:
954   static void Print(const wchar_t* str, ::std::ostream* os) {
955     if (str == nullptr) {
956       *os << "NULL";
957     } else {
958       UniversalPrint(::std::wstring(str), os);
959     }
960   }
961 };
962 #endif
963 
964 template <>
965 class UniversalTersePrinter<wchar_t*> {
966  public:
967   static void Print(wchar_t* str, ::std::ostream* os) {
968     UniversalTersePrinter<const wchar_t*>::Print(str, os);
969   }
970 };
971 
972 template <typename T>
973 void UniversalTersePrint(const T& value, ::std::ostream* os) {
974   UniversalTersePrinter<T>::Print(value, os);
975 }
976 
977 // Prints a value using the type inferred by the compiler.  The
978 // difference between this and UniversalTersePrint() is that for a
979 // (const) char pointer, this prints both the pointer and the
980 // NUL-terminated string.
981 template <typename T>
982 void UniversalPrint(const T& value, ::std::ostream* os) {
983   // A workarond for the bug in VC++ 7.1 that prevents us from instantiating
984   // UniversalPrinter with T directly.
985   typedef T T1;
986   UniversalPrinter<T1>::Print(value, os);
987 }
988 
989 typedef ::std::vector< ::std::string> Strings;
990 
991   // Tersely prints the first N fields of a tuple to a string vector,
992   // one element for each field.
993 template <typename Tuple>
994 void TersePrintPrefixToStrings(const Tuple&, std::integral_constant<size_t, 0>,
995                                Strings*) {}
996 template <typename Tuple, size_t I>
997 void TersePrintPrefixToStrings(const Tuple& t,
998                                std::integral_constant<size_t, I>,
999                                Strings* strings) {
1000   TersePrintPrefixToStrings(t, std::integral_constant<size_t, I - 1>(),
1001                             strings);
1002   ::std::stringstream ss;
1003   UniversalTersePrint(std::get<I - 1>(t), &ss);
1004   strings->push_back(ss.str());
1005 }
1006 
1007 // Prints the fields of a tuple tersely to a string vector, one
1008 // element for each field.  See the comment before
1009 // UniversalTersePrint() for how we define "tersely".
1010 template <typename Tuple>
1011 Strings UniversalTersePrintTupleFieldsToStrings(const Tuple& value) {
1012   Strings result;
1013   TersePrintPrefixToStrings(
1014       value, std::integral_constant<size_t, std::tuple_size<Tuple>::value>(),
1015       &result);
1016   return result;
1017 }
1018 
1019 }  // namespace internal
1020 
1021 template <typename T>
1022 ::std::string PrintToString(const T& value) {
1023   ::std::stringstream ss;
1024   internal::UniversalTersePrinter<T>::Print(value, &ss);
1025   return ss.str();
1026 }
1027 
1028 }  // namespace testing
1029 
1030 // Include any custom printer added by the local installation.
1031 // We must include this header at the end to make sure it can use the
1032 // declarations from this file.
1033 #include "gtest/internal/custom/gtest-printers.h"
1034 
1035 #endif  // GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
1036