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 // GOOGLETEST_CM0001 DO NOT DELETE
99 
100 #ifndef GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
101 #define GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
102 
103 #include <functional>
104 #include <ostream>  // NOLINT
105 #include <sstream>
106 #include <string>
107 #include <tuple>
108 #include <type_traits>
109 #include <utility>
110 #include <vector>
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 FallbackPrinter {
265   template <typename T>
PrintValueFallbackPrinter266   static void PrintValue(const T& value, ::std::ostream* os) {
267     PrintBytesInObjectTo(
268         static_cast<const unsigned char*>(
269             reinterpret_cast<const void*>(std::addressof(value))),
270         sizeof(value), os);
271   }
272 };
273 
274 // Try every printer in order and return the first one that works.
275 template <typename T, typename E, typename Printer, typename... Printers>
276 struct FindFirstPrinter : FindFirstPrinter<T, E, Printers...> {};
277 
278 template <typename T, typename Printer, typename... Printers>
279 struct FindFirstPrinter<
280     T, decltype(Printer::PrintValue(std::declval<const T&>(), nullptr)),
281     Printer, Printers...> {
282   using type = Printer;
283 };
284 
285 // Select the best printer in the following order:
286 //  - Print containers (they have begin/end/etc).
287 //  - Print function pointers.
288 //  - Print object pointers.
289 //  - Use the stream operator, if available.
290 //  - Print protocol buffers.
291 //  - Print types convertible to BiggestInt.
292 //  - Print types convertible to StringView, if available.
293 //  - Fallback to printing the raw bytes of the object.
294 template <typename T>
295 void PrintWithFallback(const T& value, ::std::ostream* os) {
296   using Printer = typename FindFirstPrinter<
297       T, void, ContainerPrinter, FunctionPointerPrinter, PointerPrinter,
298       internal_stream_operator_without_lexical_name_lookup::StreamPrinter,
299       ProtobufPrinter, ConvertibleToIntegerPrinter,
300       ConvertibleToStringViewPrinter, FallbackPrinter>::type;
301   Printer::PrintValue(value, os);
302 }
303 
304 // FormatForComparison<ToPrint, OtherOperand>::Format(value) formats a
305 // value of type ToPrint that is an operand of a comparison assertion
306 // (e.g. ASSERT_EQ).  OtherOperand is the type of the other operand in
307 // the comparison, and is used to help determine the best way to
308 // format the value.  In particular, when the value is a C string
309 // (char pointer) and the other operand is an STL string object, we
310 // want to format the C string as a string, since we know it is
311 // compared by value with the string object.  If the value is a char
312 // pointer but the other operand is not an STL string object, we don't
313 // know whether the pointer is supposed to point to a NUL-terminated
314 // string, and thus want to print it as a pointer to be safe.
315 //
316 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
317 
318 // The default case.
319 template <typename ToPrint, typename OtherOperand>
320 class FormatForComparison {
321  public:
322   static ::std::string Format(const ToPrint& value) {
323     return ::testing::PrintToString(value);
324   }
325 };
326 
327 // Array.
328 template <typename ToPrint, size_t N, typename OtherOperand>
329 class FormatForComparison<ToPrint[N], OtherOperand> {
330  public:
331   static ::std::string Format(const ToPrint* value) {
332     return FormatForComparison<const ToPrint*, OtherOperand>::Format(value);
333   }
334 };
335 
336 // By default, print C string as pointers to be safe, as we don't know
337 // whether they actually point to a NUL-terminated string.
338 
339 #define GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(CharType)                \
340   template <typename OtherOperand>                                      \
341   class FormatForComparison<CharType*, OtherOperand> {                  \
342    public:                                                              \
343     static ::std::string Format(CharType* value) {                      \
344       return ::testing::PrintToString(static_cast<const void*>(value)); \
345     }                                                                   \
346   }
347 
348 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char);
349 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char);
350 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(wchar_t);
351 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const wchar_t);
352 #ifdef __cpp_char8_t
353 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char8_t);
354 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char8_t);
355 #endif
356 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char16_t);
357 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char16_t);
358 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char32_t);
359 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char32_t);
360 
361 #undef GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_
362 
363 // If a C string is compared with an STL string object, we know it's meant
364 // to point to a NUL-terminated string, and thus can print it as a string.
365 
366 #define GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(CharType, OtherStringType) \
367   template <>                                                           \
368   class FormatForComparison<CharType*, OtherStringType> {               \
369    public:                                                              \
370     static ::std::string Format(CharType* value) {                      \
371       return ::testing::PrintToString(value);                           \
372     }                                                                   \
373   }
374 
375 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::std::string);
376 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char, ::std::string);
377 #ifdef __cpp_char8_t
378 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char8_t, ::std::u8string);
379 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char8_t, ::std::u8string);
380 #endif
381 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char16_t, ::std::u16string);
382 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char16_t, ::std::u16string);
383 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char32_t, ::std::u32string);
384 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char32_t, ::std::u32string);
385 
386 #if GTEST_HAS_STD_WSTRING
387 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(wchar_t, ::std::wstring);
388 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const wchar_t, ::std::wstring);
389 #endif
390 
391 #undef GTEST_IMPL_FORMAT_C_STRING_AS_STRING_
392 
393 // Formats a comparison assertion (e.g. ASSERT_EQ, EXPECT_LT, and etc)
394 // operand to be used in a failure message.  The type (but not value)
395 // of the other operand may affect the format.  This allows us to
396 // print a char* as a raw pointer when it is compared against another
397 // char* or void*, and print it as a C string when it is compared
398 // against an std::string object, for example.
399 //
400 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
401 template <typename T1, typename T2>
402 std::string FormatForComparisonFailureMessage(
403     const T1& value, const T2& /* other_operand */) {
404   return FormatForComparison<T1, T2>::Format(value);
405 }
406 
407 // UniversalPrinter<T>::Print(value, ostream_ptr) prints the given
408 // value to the given ostream.  The caller must ensure that
409 // 'ostream_ptr' is not NULL, or the behavior is undefined.
410 //
411 // We define UniversalPrinter as a class template (as opposed to a
412 // function template), as we need to partially specialize it for
413 // reference types, which cannot be done with function templates.
414 template <typename T>
415 class UniversalPrinter;
416 
417 // Prints the given value using the << operator if it has one;
418 // otherwise prints the bytes in it.  This is what
419 // UniversalPrinter<T>::Print() does when PrintTo() is not specialized
420 // or overloaded for type T.
421 //
422 // A user can override this behavior for a class type Foo by defining
423 // an overload of PrintTo() in the namespace where Foo is defined.  We
424 // give the user this option as sometimes defining a << operator for
425 // Foo is not desirable (e.g. the coding style may prevent doing it,
426 // or there is already a << operator but it doesn't do what the user
427 // wants).
428 template <typename T>
429 void PrintTo(const T& value, ::std::ostream* os) {
430   internal::PrintWithFallback(value, os);
431 }
432 
433 // The following list of PrintTo() overloads tells
434 // UniversalPrinter<T>::Print() how to print standard types (built-in
435 // types, strings, plain arrays, and pointers).
436 
437 // Overloads for various char types.
438 GTEST_API_ void PrintTo(unsigned char c, ::std::ostream* os);
439 GTEST_API_ void PrintTo(signed char c, ::std::ostream* os);
440 inline void PrintTo(char c, ::std::ostream* os) {
441   // When printing a plain char, we always treat it as unsigned.  This
442   // way, the output won't be affected by whether the compiler thinks
443   // char is signed or not.
444   PrintTo(static_cast<unsigned char>(c), os);
445 }
446 
447 // Overloads for other simple built-in types.
448 inline void PrintTo(bool x, ::std::ostream* os) {
449   *os << (x ? "true" : "false");
450 }
451 
452 // Overload for wchar_t type.
453 // Prints a wchar_t as a symbol if it is printable or as its internal
454 // code otherwise and also as its decimal code (except for L'\0').
455 // The L'\0' char is printed as "L'\\0'". The decimal code is printed
456 // as signed integer when wchar_t is implemented by the compiler
457 // as a signed type and is printed as an unsigned integer when wchar_t
458 // is implemented as an unsigned type.
459 GTEST_API_ void PrintTo(wchar_t wc, ::std::ostream* os);
460 
461 GTEST_API_ void PrintTo(char32_t c, ::std::ostream* os);
462 inline void PrintTo(char16_t c, ::std::ostream* os) {
463   PrintTo(ImplicitCast_<char32_t>(c), os);
464 }
465 #ifdef __cpp_char8_t
466 inline void PrintTo(char8_t c, ::std::ostream* os) {
467   PrintTo(ImplicitCast_<char32_t>(c), os);
468 }
469 #endif
470 
471 // Overloads for C strings.
472 GTEST_API_ void PrintTo(const char* s, ::std::ostream* os);
473 inline void PrintTo(char* s, ::std::ostream* os) {
474   PrintTo(ImplicitCast_<const char*>(s), os);
475 }
476 
477 // signed/unsigned char is often used for representing binary data, so
478 // we print pointers to it as void* to be safe.
479 inline void PrintTo(const signed char* s, ::std::ostream* os) {
480   PrintTo(ImplicitCast_<const void*>(s), os);
481 }
482 inline void PrintTo(signed char* s, ::std::ostream* os) {
483   PrintTo(ImplicitCast_<const void*>(s), os);
484 }
485 inline void PrintTo(const unsigned char* s, ::std::ostream* os) {
486   PrintTo(ImplicitCast_<const void*>(s), os);
487 }
488 inline void PrintTo(unsigned char* s, ::std::ostream* os) {
489   PrintTo(ImplicitCast_<const void*>(s), os);
490 }
491 #ifdef __cpp_char8_t
492 inline void PrintTo(const char8_t* s, ::std::ostream* os) {
493   PrintTo(ImplicitCast_<const void*>(s), os);
494 }
495 inline void PrintTo(char8_t* s, ::std::ostream* os) {
496   PrintTo(ImplicitCast_<const void*>(s), os);
497 }
498 #endif
499 inline void PrintTo(const char16_t* s, ::std::ostream* os) {
500   PrintTo(ImplicitCast_<const void*>(s), os);
501 }
502 inline void PrintTo(char16_t* s, ::std::ostream* os) {
503   PrintTo(ImplicitCast_<const void*>(s), os);
504 }
505 inline void PrintTo(const char32_t* s, ::std::ostream* os) {
506   PrintTo(ImplicitCast_<const void*>(s), os);
507 }
508 inline void PrintTo(char32_t* s, ::std::ostream* os) {
509   PrintTo(ImplicitCast_<const void*>(s), os);
510 }
511 
512 // MSVC can be configured to define wchar_t as a typedef of unsigned
513 // short.  It defines _NATIVE_WCHAR_T_DEFINED when wchar_t is a native
514 // type.  When wchar_t is a typedef, defining an overload for const
515 // wchar_t* would cause unsigned short* be printed as a wide string,
516 // possibly causing invalid memory accesses.
517 #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
518 // Overloads for wide C strings
519 GTEST_API_ void PrintTo(const wchar_t* s, ::std::ostream* os);
520 inline void PrintTo(wchar_t* s, ::std::ostream* os) {
521   PrintTo(ImplicitCast_<const wchar_t*>(s), os);
522 }
523 #endif
524 
525 // Overload for C arrays.  Multi-dimensional arrays are printed
526 // properly.
527 
528 // Prints the given number of elements in an array, without printing
529 // the curly braces.
530 template <typename T>
531 void PrintRawArrayTo(const T a[], size_t count, ::std::ostream* os) {
532   UniversalPrint(a[0], os);
533   for (size_t i = 1; i != count; i++) {
534     *os << ", ";
535     UniversalPrint(a[i], os);
536   }
537 }
538 
539 // Overloads for ::std::string.
540 GTEST_API_ void PrintStringTo(const ::std::string&s, ::std::ostream* os);
541 inline void PrintTo(const ::std::string& s, ::std::ostream* os) {
542   PrintStringTo(s, os);
543 }
544 
545 // Overloads for ::std::wstring.
546 #if GTEST_HAS_STD_WSTRING
547 GTEST_API_ void PrintWideStringTo(const ::std::wstring&s, ::std::ostream* os);
548 inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) {
549   PrintWideStringTo(s, os);
550 }
551 #endif  // GTEST_HAS_STD_WSTRING
552 
553 #if GTEST_INTERNAL_HAS_STRING_VIEW
554 // Overload for internal::StringView.
555 inline void PrintTo(internal::StringView sp, ::std::ostream* os) {
556   PrintTo(::std::string(sp), os);
557 }
558 #endif  // GTEST_INTERNAL_HAS_STRING_VIEW
559 
560 inline void PrintTo(std::nullptr_t, ::std::ostream* os) { *os << "(nullptr)"; }
561 
562 template <typename T>
563 void PrintTo(std::reference_wrapper<T> ref, ::std::ostream* os) {
564   UniversalPrinter<T&>::Print(ref.get(), os);
565 }
566 
567 // Helper function for printing a tuple.  T must be instantiated with
568 // a tuple type.
569 template <typename T>
570 void PrintTupleTo(const T&, std::integral_constant<size_t, 0>,
571                   ::std::ostream*) {}
572 
573 template <typename T, size_t I>
574 void PrintTupleTo(const T& t, std::integral_constant<size_t, I>,
575                   ::std::ostream* os) {
576   PrintTupleTo(t, std::integral_constant<size_t, I - 1>(), os);
577   GTEST_INTENTIONAL_CONST_COND_PUSH_()
578   if (I > 1) {
579     GTEST_INTENTIONAL_CONST_COND_POP_()
580     *os << ", ";
581   }
582   UniversalPrinter<typename std::tuple_element<I - 1, T>::type>::Print(
583       std::get<I - 1>(t), os);
584 }
585 
586 template <typename... Types>
587 void PrintTo(const ::std::tuple<Types...>& t, ::std::ostream* os) {
588   *os << "(";
589   PrintTupleTo(t, std::integral_constant<size_t, sizeof...(Types)>(), os);
590   *os << ")";
591 }
592 
593 // Overload for std::pair.
594 template <typename T1, typename T2>
595 void PrintTo(const ::std::pair<T1, T2>& value, ::std::ostream* os) {
596   *os << '(';
597   // We cannot use UniversalPrint(value.first, os) here, as T1 may be
598   // a reference type.  The same for printing value.second.
599   UniversalPrinter<T1>::Print(value.first, os);
600   *os << ", ";
601   UniversalPrinter<T2>::Print(value.second, os);
602   *os << ')';
603 }
604 
605 // Implements printing a non-reference type T by letting the compiler
606 // pick the right overload of PrintTo() for T.
607 template <typename T>
608 class UniversalPrinter {
609  public:
610   // MSVC warns about adding const to a function type, so we want to
611   // disable the warning.
612   GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180)
613 
614   // Note: we deliberately don't call this PrintTo(), as that name
615   // conflicts with ::testing::internal::PrintTo in the body of the
616   // function.
617   static void Print(const T& value, ::std::ostream* os) {
618     // By default, ::testing::internal::PrintTo() is used for printing
619     // the value.
620     //
621     // Thanks to Koenig look-up, if T is a class and has its own
622     // PrintTo() function defined in its namespace, that function will
623     // be visible here.  Since it is more specific than the generic ones
624     // in ::testing::internal, it will be picked by the compiler in the
625     // following statement - exactly what we want.
626     PrintTo(value, os);
627   }
628 
629   GTEST_DISABLE_MSC_WARNINGS_POP_()
630 };
631 
632 #if GTEST_INTERNAL_HAS_ANY
633 
634 // Printer for std::any / absl::any
635 
636 template <>
637 class UniversalPrinter<Any> {
638  public:
639   static void Print(const Any& value, ::std::ostream* os) {
640     if (value.has_value()) {
641       *os << "value of type " << GetTypeName(value);
642     } else {
643       *os << "no value";
644     }
645   }
646 
647  private:
648   static std::string GetTypeName(const Any& value) {
649 #if GTEST_HAS_RTTI
650     return internal::GetTypeName(value.type());
651 #else
652     static_cast<void>(value);  // possibly unused
653     return "<unknown_type>";
654 #endif  // GTEST_HAS_RTTI
655   }
656 };
657 
658 #endif  // GTEST_INTERNAL_HAS_ANY
659 
660 #if GTEST_INTERNAL_HAS_OPTIONAL
661 
662 // Printer for std::optional / absl::optional
663 
664 template <typename T>
665 class UniversalPrinter<Optional<T>> {
666  public:
667   static void Print(const Optional<T>& value, ::std::ostream* os) {
668     *os << '(';
669     if (!value) {
670       *os << "nullopt";
671     } else {
672       UniversalPrint(*value, os);
673     }
674     *os << ')';
675   }
676 };
677 
678 #endif  // GTEST_INTERNAL_HAS_OPTIONAL
679 
680 #if GTEST_INTERNAL_HAS_VARIANT
681 
682 // Printer for std::variant / absl::variant
683 
684 template <typename... T>
685 class UniversalPrinter<Variant<T...>> {
686  public:
687   static void Print(const Variant<T...>& value, ::std::ostream* os) {
688     *os << '(';
689 #if GTEST_HAS_ABSL
690     absl::visit(Visitor{os, value.index()}, value);
691 #else
692     std::visit(Visitor{os, value.index()}, value);
693 #endif  // GTEST_HAS_ABSL
694     *os << ')';
695   }
696 
697  private:
698   struct Visitor {
699     template <typename U>
700     void operator()(const U& u) const {
701       *os << "'" << GetTypeName<U>() << "(index = " << index
702           << ")' with value ";
703       UniversalPrint(u, os);
704     }
705     ::std::ostream* os;
706     std::size_t index;
707   };
708 };
709 
710 #endif  // GTEST_INTERNAL_HAS_VARIANT
711 
712 // UniversalPrintArray(begin, len, os) prints an array of 'len'
713 // elements, starting at address 'begin'.
714 template <typename T>
715 void UniversalPrintArray(const T* begin, size_t len, ::std::ostream* os) {
716   if (len == 0) {
717     *os << "{}";
718   } else {
719     *os << "{ ";
720     const size_t kThreshold = 18;
721     const size_t kChunkSize = 8;
722     // If the array has more than kThreshold elements, we'll have to
723     // omit some details by printing only the first and the last
724     // kChunkSize elements.
725     if (len <= kThreshold) {
726       PrintRawArrayTo(begin, len, os);
727     } else {
728       PrintRawArrayTo(begin, kChunkSize, os);
729       *os << ", ..., ";
730       PrintRawArrayTo(begin + len - kChunkSize, kChunkSize, os);
731     }
732     *os << " }";
733   }
734 }
735 // This overload prints a (const) char array compactly.
736 GTEST_API_ void UniversalPrintArray(
737     const char* begin, size_t len, ::std::ostream* os);
738 
739 // This overload prints a (const) wchar_t array compactly.
740 GTEST_API_ void UniversalPrintArray(
741     const wchar_t* begin, size_t len, ::std::ostream* os);
742 
743 // Implements printing an array type T[N].
744 template <typename T, size_t N>
745 class UniversalPrinter<T[N]> {
746  public:
747   // Prints the given array, omitting some elements when there are too
748   // many.
749   static void Print(const T (&a)[N], ::std::ostream* os) {
750     UniversalPrintArray(a, N, os);
751   }
752 };
753 
754 // Implements printing a reference type T&.
755 template <typename T>
756 class UniversalPrinter<T&> {
757  public:
758   // MSVC warns about adding const to a function type, so we want to
759   // disable the warning.
760   GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180)
761 
762   static void Print(const T& value, ::std::ostream* os) {
763     // Prints the address of the value.  We use reinterpret_cast here
764     // as static_cast doesn't compile when T is a function type.
765     *os << "@" << reinterpret_cast<const void*>(&value) << " ";
766 
767     // Then prints the value itself.
768     UniversalPrint(value, os);
769   }
770 
771   GTEST_DISABLE_MSC_WARNINGS_POP_()
772 };
773 
774 // Prints a value tersely: for a reference type, the referenced value
775 // (but not the address) is printed; for a (const) char pointer, the
776 // NUL-terminated string (but not the pointer) is printed.
777 
778 template <typename T>
779 class UniversalTersePrinter {
780  public:
781   static void Print(const T& value, ::std::ostream* os) {
782     UniversalPrint(value, os);
783   }
784 };
785 template <typename T>
786 class UniversalTersePrinter<T&> {
787  public:
788   static void Print(const T& value, ::std::ostream* os) {
789     UniversalPrint(value, os);
790   }
791 };
792 template <typename T, size_t N>
793 class UniversalTersePrinter<T[N]> {
794  public:
795   static void Print(const T (&value)[N], ::std::ostream* os) {
796     UniversalPrinter<T[N]>::Print(value, os);
797   }
798 };
799 template <>
800 class UniversalTersePrinter<const char*> {
801  public:
802   static void Print(const char* str, ::std::ostream* os) {
803     if (str == nullptr) {
804       *os << "NULL";
805     } else {
806       UniversalPrint(std::string(str), os);
807     }
808   }
809 };
810 template <>
811 class UniversalTersePrinter<char*> {
812  public:
813   static void Print(char* str, ::std::ostream* os) {
814     UniversalTersePrinter<const char*>::Print(str, os);
815   }
816 };
817 
818 #if GTEST_HAS_STD_WSTRING
819 template <>
820 class UniversalTersePrinter<const wchar_t*> {
821  public:
822   static void Print(const wchar_t* str, ::std::ostream* os) {
823     if (str == nullptr) {
824       *os << "NULL";
825     } else {
826       UniversalPrint(::std::wstring(str), os);
827     }
828   }
829 };
830 #endif
831 
832 template <>
833 class UniversalTersePrinter<wchar_t*> {
834  public:
835   static void Print(wchar_t* str, ::std::ostream* os) {
836     UniversalTersePrinter<const wchar_t*>::Print(str, os);
837   }
838 };
839 
840 template <typename T>
841 void UniversalTersePrint(const T& value, ::std::ostream* os) {
842   UniversalTersePrinter<T>::Print(value, os);
843 }
844 
845 // Prints a value using the type inferred by the compiler.  The
846 // difference between this and UniversalTersePrint() is that for a
847 // (const) char pointer, this prints both the pointer and the
848 // NUL-terminated string.
849 template <typename T>
850 void UniversalPrint(const T& value, ::std::ostream* os) {
851   // A workarond for the bug in VC++ 7.1 that prevents us from instantiating
852   // UniversalPrinter with T directly.
853   typedef T T1;
854   UniversalPrinter<T1>::Print(value, os);
855 }
856 
857 typedef ::std::vector< ::std::string> Strings;
858 
859   // Tersely prints the first N fields of a tuple to a string vector,
860   // one element for each field.
861 template <typename Tuple>
862 void TersePrintPrefixToStrings(const Tuple&, std::integral_constant<size_t, 0>,
863                                Strings*) {}
864 template <typename Tuple, size_t I>
865 void TersePrintPrefixToStrings(const Tuple& t,
866                                std::integral_constant<size_t, I>,
867                                Strings* strings) {
868   TersePrintPrefixToStrings(t, std::integral_constant<size_t, I - 1>(),
869                             strings);
870   ::std::stringstream ss;
871   UniversalTersePrint(std::get<I - 1>(t), &ss);
872   strings->push_back(ss.str());
873 }
874 
875 // Prints the fields of a tuple tersely to a string vector, one
876 // element for each field.  See the comment before
877 // UniversalTersePrint() for how we define "tersely".
878 template <typename Tuple>
879 Strings UniversalTersePrintTupleFieldsToStrings(const Tuple& value) {
880   Strings result;
881   TersePrintPrefixToStrings(
882       value, std::integral_constant<size_t, std::tuple_size<Tuple>::value>(),
883       &result);
884   return result;
885 }
886 
887 }  // namespace internal
888 
889 template <typename T>
890 ::std::string PrintToString(const T& value) {
891   ::std::stringstream ss;
892   internal::UniversalTersePrinter<T>::Print(value, &ss);
893   return ss.str();
894 }
895 
896 }  // namespace testing
897 
898 // Include any custom printer added by the local installation.
899 // We must include this header at the end to make sure it can use the
900 // declarations from this file.
901 #include "gtest/internal/custom/gtest-printers.h"
902 
903 #endif  // GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
904