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 #if GTEST_HAS_ABSL
115 #include "absl/strings/string_view.h"
116 #include "absl/types/optional.h"
117 #include "absl/types/variant.h"
118 #endif  // GTEST_HAS_ABSL
119 
120 namespace testing {
121 
122 // Definitions in the 'internal' and 'internal2' name spaces are
123 // subject to change without notice.  DO NOT USE THEM IN USER CODE!
124 namespace internal2 {
125 
126 // Prints the given number of bytes in the given object to the given
127 // ostream.
128 GTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes,
129                                      size_t count,
130                                      ::std::ostream* os);
131 
132 // For selecting which printer to use when a given type has neither <<
133 // nor PrintTo().
134 enum TypeKind {
135   kProtobuf,              // a protobuf type
136   kConvertibleToInteger,  // a type implicitly convertible to BiggestInt
137                           // (e.g. a named or unnamed enum type)
138 #if GTEST_HAS_ABSL
139   kConvertibleToStringView,  // a type implicitly convertible to
140                              // absl::string_view
141 #endif
142   kOtherType  // anything else
143 };
144 
145 // TypeWithoutFormatter<T, kTypeKind>::PrintValue(value, os) is called
146 // by the universal printer to print a value of type T when neither
147 // operator<< nor PrintTo() is defined for T, where kTypeKind is the
148 // "kind" of T as defined by enum TypeKind.
149 template <typename T, TypeKind kTypeKind>
150 class TypeWithoutFormatter {
151  public:
152   // This default version is called when kTypeKind is kOtherType.
PrintValue(const T & value,::std::ostream * os)153   static void PrintValue(const T& value, ::std::ostream* os) {
154     PrintBytesInObjectTo(
155         static_cast<const unsigned char*>(
156             reinterpret_cast<const void*>(std::addressof(value))),
157         sizeof(value), os);
158   }
159 };
160 
161 // We print a protobuf using its ShortDebugString() when the string
162 // doesn't exceed this many characters; otherwise we print it using
163 // DebugString() for better readability.
164 const size_t kProtobufOneLinerMaxLength = 50;
165 
166 template <typename T>
167 class TypeWithoutFormatter<T, kProtobuf> {
168  public:
PrintValue(const T & value,::std::ostream * os)169   static void PrintValue(const T& value, ::std::ostream* os) {
170     std::string pretty_str = value.ShortDebugString();
171     if (pretty_str.length() > kProtobufOneLinerMaxLength) {
172       pretty_str = "\n" + value.DebugString();
173     }
174     *os << ("<" + pretty_str + ">");
175   }
176 };
177 
178 template <typename T>
179 class TypeWithoutFormatter<T, kConvertibleToInteger> {
180  public:
181   // Since T has no << operator or PrintTo() but can be implicitly
182   // converted to BiggestInt, we print it as a BiggestInt.
183   //
184   // Most likely T is an enum type (either named or unnamed), in which
185   // case printing it as an integer is the desired behavior.  In case
186   // T is not an enum, printing it as an integer is the best we can do
187   // given that it has no user-defined printer.
PrintValue(const T & value,::std::ostream * os)188   static void PrintValue(const T& value, ::std::ostream* os) {
189     const internal::BiggestInt kBigInt = value;
190     *os << kBigInt;
191   }
192 };
193 
194 #if GTEST_HAS_ABSL
195 template <typename T>
196 class TypeWithoutFormatter<T, kConvertibleToStringView> {
197  public:
198   // Since T has neither operator<< nor PrintTo() but can be implicitly
199   // converted to absl::string_view, we print it as a absl::string_view.
200   //
201   // Note: the implementation is further below, as it depends on
202   // internal::PrintTo symbol which is defined later in the file.
203   static void PrintValue(const T& value, ::std::ostream* os);
204 };
205 #endif
206 
207 // Prints the given value to the given ostream.  If the value is a
208 // protocol message, its debug string is printed; if it's an enum or
209 // of a type implicitly convertible to BiggestInt, it's printed as an
210 // integer; otherwise the bytes in the value are printed.  This is
211 // what UniversalPrinter<T>::Print() does when it knows nothing about
212 // type T and T has neither << operator nor PrintTo().
213 //
214 // A user can override this behavior for a class type Foo by defining
215 // a << operator in the namespace where Foo is defined.
216 //
217 // We put this operator in namespace 'internal2' instead of 'internal'
218 // to simplify the implementation, as much code in 'internal' needs to
219 // use << in STL, which would conflict with our own << were it defined
220 // in 'internal'.
221 //
222 // Note that this operator<< takes a generic std::basic_ostream<Char,
223 // CharTraits> type instead of the more restricted std::ostream.  If
224 // we define it to take an std::ostream instead, we'll get an
225 // "ambiguous overloads" compiler error when trying to print a type
226 // Foo that supports streaming to std::basic_ostream<Char,
227 // CharTraits>, as the compiler cannot tell whether
228 // operator<<(std::ostream&, const T&) or
229 // operator<<(std::basic_stream<Char, CharTraits>, const Foo&) is more
230 // specific.
231 template <typename Char, typename CharTraits, typename T>
232 ::std::basic_ostream<Char, CharTraits>& operator<<(
233     ::std::basic_ostream<Char, CharTraits>& os, const T& x) {
234   TypeWithoutFormatter<T, (internal::IsAProtocolMessage<T>::value
235                                ? kProtobuf
236                                : std::is_convertible<
237                                      const T&, internal::BiggestInt>::value
238                                      ? kConvertibleToInteger
239                                      :
240 #if GTEST_HAS_ABSL
241                                      std::is_convertible<
242                                          const T&, absl::string_view>::value
243                                          ? kConvertibleToStringView
244                                          :
245 #endif
246                                          kOtherType)>::PrintValue(x, &os);
247   return os;
248 }
249 
250 }  // namespace internal2
251 }  // namespace testing
252 
253 // This namespace MUST NOT BE NESTED IN ::testing, or the name look-up
254 // magic needed for implementing UniversalPrinter won't work.
255 namespace testing_internal {
256 
257 // Used to print a value that is not an STL-style container when the
258 // user doesn't define PrintTo() for it.
259 template <typename T>
DefaultPrintNonContainerTo(const T & value,::std::ostream * os)260 void DefaultPrintNonContainerTo(const T& value, ::std::ostream* os) {
261   // With the following statement, during unqualified name lookup,
262   // testing::internal2::operator<< appears as if it was declared in
263   // the nearest enclosing namespace that contains both
264   // ::testing_internal and ::testing::internal2, i.e. the global
265   // namespace.  For more details, refer to the C++ Standard section
266   // 7.3.4-1 [namespace.udir].  This allows us to fall back onto
267   // testing::internal2::operator<< in case T doesn't come with a <<
268   // operator.
269 
270   using ::testing::internal2::operator<<;
271 
272   // Assuming T is defined in namespace foo, in the next statement,
273   // the compiler will consider all of:
274   //
275   //   1. foo::operator<< (thanks to Koenig look-up),
276   //   2. ::operator<< (as the current namespace is enclosed in ::),
277   //   3. testing::internal2::operator<< (thanks to the using statement above).
278   //
279   // The operator<< whose type matches T best will be picked.
280   //
281   // We deliberately allow #2 to be a candidate, as sometimes it's
282   // impossible to define #1 (e.g. when foo is ::std, defining
283   // anything in it is undefined behavior unless you are a compiler
284   // vendor.).
285   *os << value;
286 }
287 
288 }  // namespace testing_internal
289 
290 namespace testing {
291 namespace internal {
292 
293 // FormatForComparison<ToPrint, OtherOperand>::Format(value) formats a
294 // value of type ToPrint that is an operand of a comparison assertion
295 // (e.g. ASSERT_EQ).  OtherOperand is the type of the other operand in
296 // the comparison, and is used to help determine the best way to
297 // format the value.  In particular, when the value is a C string
298 // (char pointer) and the other operand is an STL string object, we
299 // want to format the C string as a string, since we know it is
300 // compared by value with the string object.  If the value is a char
301 // pointer but the other operand is not an STL string object, we don't
302 // know whether the pointer is supposed to point to a NUL-terminated
303 // string, and thus want to print it as a pointer to be safe.
304 //
305 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
306 
307 // The default case.
308 template <typename ToPrint, typename OtherOperand>
309 class FormatForComparison {
310  public:
Format(const ToPrint & value)311   static ::std::string Format(const ToPrint& value) {
312     return ::testing::PrintToString(value);
313   }
314 };
315 
316 // Array.
317 template <typename ToPrint, size_t N, typename OtherOperand>
318 class FormatForComparison<ToPrint[N], OtherOperand> {
319  public:
Format(const ToPrint * value)320   static ::std::string Format(const ToPrint* value) {
321     return FormatForComparison<const ToPrint*, OtherOperand>::Format(value);
322   }
323 };
324 
325 // By default, print C string as pointers to be safe, as we don't know
326 // whether they actually point to a NUL-terminated string.
327 
328 #define GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(CharType)                \
329   template <typename OtherOperand>                                      \
330   class FormatForComparison<CharType*, OtherOperand> {                  \
331    public:                                                              \
332     static ::std::string Format(CharType* value) {                      \
333       return ::testing::PrintToString(static_cast<const void*>(value)); \
334     }                                                                   \
335   }
336 
337 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char);
338 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char);
339 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(wchar_t);
340 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const wchar_t);
341 
342 #undef GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_
343 
344 // If a C string is compared with an STL string object, we know it's meant
345 // to point to a NUL-terminated string, and thus can print it as a string.
346 
347 #define GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(CharType, OtherStringType) \
348   template <>                                                           \
349   class FormatForComparison<CharType*, OtherStringType> {               \
350    public:                                                              \
351     static ::std::string Format(CharType* value) {                      \
352       return ::testing::PrintToString(value);                           \
353     }                                                                   \
354   }
355 
356 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::std::string);
357 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char, ::std::string);
358 
359 #if GTEST_HAS_STD_WSTRING
360 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(wchar_t, ::std::wstring);
361 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const wchar_t, ::std::wstring);
362 #endif
363 
364 #undef GTEST_IMPL_FORMAT_C_STRING_AS_STRING_
365 
366 // Formats a comparison assertion (e.g. ASSERT_EQ, EXPECT_LT, and etc)
367 // operand to be used in a failure message.  The type (but not value)
368 // of the other operand may affect the format.  This allows us to
369 // print a char* as a raw pointer when it is compared against another
370 // char* or void*, and print it as a C string when it is compared
371 // against an std::string object, for example.
372 //
373 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
374 template <typename T1, typename T2>
FormatForComparisonFailureMessage(const T1 & value,const T2 &)375 std::string FormatForComparisonFailureMessage(
376     const T1& value, const T2& /* other_operand */) {
377   return FormatForComparison<T1, T2>::Format(value);
378 }
379 
380 // UniversalPrinter<T>::Print(value, ostream_ptr) prints the given
381 // value to the given ostream.  The caller must ensure that
382 // 'ostream_ptr' is not NULL, or the behavior is undefined.
383 //
384 // We define UniversalPrinter as a class template (as opposed to a
385 // function template), as we need to partially specialize it for
386 // reference types, which cannot be done with function templates.
387 template <typename T>
388 class UniversalPrinter;
389 
390 template <typename T>
391 void UniversalPrint(const T& value, ::std::ostream* os);
392 
393 enum DefaultPrinterType {
394   kPrintContainer,
395   kPrintPointer,
396   kPrintFunctionPointer,
397   kPrintOther,
398 };
399 template <DefaultPrinterType type> struct WrapPrinterType {};
400 
401 // Used to print an STL-style container when the user doesn't define
402 // a PrintTo() for it.
403 template <typename C>
DefaultPrintTo(WrapPrinterType<kPrintContainer>,const C & container,::std::ostream * os)404 void DefaultPrintTo(WrapPrinterType<kPrintContainer> /* dummy */,
405                     const C& container, ::std::ostream* os) {
406   const size_t kMaxCount = 32;  // The maximum number of elements to print.
407   *os << '{';
408   size_t count = 0;
409   for (typename C::const_iterator it = container.begin();
410        it != container.end(); ++it, ++count) {
411     if (count > 0) {
412       *os << ',';
413       if (count == kMaxCount) {  // Enough has been printed.
414         *os << " ...";
415         break;
416       }
417     }
418     *os << ' ';
419     // We cannot call PrintTo(*it, os) here as PrintTo() doesn't
420     // handle *it being a native array.
421     internal::UniversalPrint(*it, os);
422   }
423 
424   if (count > 0) {
425     *os << ' ';
426   }
427   *os << '}';
428 }
429 
430 // Used to print a pointer that is neither a char pointer nor a member
431 // pointer, when the user doesn't define PrintTo() for it.  (A member
432 // variable pointer or member function pointer doesn't really point to
433 // a location in the address space.  Their representation is
434 // implementation-defined.  Therefore they will be printed as raw
435 // bytes.)
436 template <typename T>
DefaultPrintTo(WrapPrinterType<kPrintPointer>,T * p,::std::ostream * os)437 void DefaultPrintTo(WrapPrinterType<kPrintPointer> /* dummy */,
438                     T* p, ::std::ostream* os) {
439   if (p == nullptr) {
440     *os << "NULL";
441   } else {
442     // T is not a function type.  We just call << to print p,
443     // relying on ADL to pick up user-defined << for their pointer
444     // types, if any.
445     *os << p;
446   }
447 }
448 template <typename T>
DefaultPrintTo(WrapPrinterType<kPrintFunctionPointer>,T * p,::std::ostream * os)449 void DefaultPrintTo(WrapPrinterType<kPrintFunctionPointer> /* dummy */,
450                     T* p, ::std::ostream* os) {
451   if (p == nullptr) {
452     *os << "NULL";
453   } else {
454     // T is a function type, so '*os << p' doesn't do what we want
455     // (it just prints p as bool).  We want to print p as a const
456     // void*.
457     *os << reinterpret_cast<const void*>(p);
458   }
459 }
460 
461 // Used to print a non-container, non-pointer value when the user
462 // doesn't define PrintTo() for it.
463 template <typename T>
DefaultPrintTo(WrapPrinterType<kPrintOther>,const T & value,::std::ostream * os)464 void DefaultPrintTo(WrapPrinterType<kPrintOther> /* dummy */,
465                     const T& value, ::std::ostream* os) {
466   ::testing_internal::DefaultPrintNonContainerTo(value, os);
467 }
468 
469 // Prints the given value using the << operator if it has one;
470 // otherwise prints the bytes in it.  This is what
471 // UniversalPrinter<T>::Print() does when PrintTo() is not specialized
472 // or overloaded for type T.
473 //
474 // A user can override this behavior for a class type Foo by defining
475 // an overload of PrintTo() in the namespace where Foo is defined.  We
476 // give the user this option as sometimes defining a << operator for
477 // Foo is not desirable (e.g. the coding style may prevent doing it,
478 // or there is already a << operator but it doesn't do what the user
479 // wants).
480 template <typename T>
PrintTo(const T & value,::std::ostream * os)481 void PrintTo(const T& value, ::std::ostream* os) {
482   // DefaultPrintTo() is overloaded.  The type of its first argument
483   // determines which version will be picked.
484   //
485   // Note that we check for container types here, prior to we check
486   // for protocol message types in our operator<<.  The rationale is:
487   //
488   // For protocol messages, we want to give people a chance to
489   // override Google Mock's format by defining a PrintTo() or
490   // operator<<.  For STL containers, other formats can be
491   // incompatible with Google Mock's format for the container
492   // elements; therefore we check for container types here to ensure
493   // that our format is used.
494   //
495   // Note that MSVC and clang-cl do allow an implicit conversion from
496   // pointer-to-function to pointer-to-object, but clang-cl warns on it.
497   // So don't use ImplicitlyConvertible if it can be helped since it will
498   // cause this warning, and use a separate overload of DefaultPrintTo for
499   // function pointers so that the `*os << p` in the object pointer overload
500   // doesn't cause that warning either.
501   DefaultPrintTo(
502       WrapPrinterType <
503                   (sizeof(IsContainerTest<T>(0)) == sizeof(IsContainer)) &&
504               !IsRecursiveContainer<T>::value
505           ? kPrintContainer
506           : !std::is_pointer<T>::value
507                 ? kPrintOther
508                 : std::is_function<typename std::remove_pointer<T>::type>::value
509                       ? kPrintFunctionPointer
510                       : kPrintPointer > (),
511       value, os);
512 }
513 
514 // The following list of PrintTo() overloads tells
515 // UniversalPrinter<T>::Print() how to print standard types (built-in
516 // types, strings, plain arrays, and pointers).
517 
518 // Overloads for various char types.
519 GTEST_API_ void PrintTo(unsigned char c, ::std::ostream* os);
520 GTEST_API_ void PrintTo(signed char c, ::std::ostream* os);
PrintTo(char c,::std::ostream * os)521 inline void PrintTo(char c, ::std::ostream* os) {
522   // When printing a plain char, we always treat it as unsigned.  This
523   // way, the output won't be affected by whether the compiler thinks
524   // char is signed or not.
525   PrintTo(static_cast<unsigned char>(c), os);
526 }
527 
528 // Overloads for other simple built-in types.
PrintTo(bool x,::std::ostream * os)529 inline void PrintTo(bool x, ::std::ostream* os) {
530   *os << (x ? "true" : "false");
531 }
532 
533 // Overload for wchar_t type.
534 // Prints a wchar_t as a symbol if it is printable or as its internal
535 // code otherwise and also as its decimal code (except for L'\0').
536 // The L'\0' char is printed as "L'\\0'". The decimal code is printed
537 // as signed integer when wchar_t is implemented by the compiler
538 // as a signed type and is printed as an unsigned integer when wchar_t
539 // is implemented as an unsigned type.
540 GTEST_API_ void PrintTo(wchar_t wc, ::std::ostream* os);
541 
542 // Overloads for C strings.
543 GTEST_API_ void PrintTo(const char* s, ::std::ostream* os);
PrintTo(char * s,::std::ostream * os)544 inline void PrintTo(char* s, ::std::ostream* os) {
545   PrintTo(ImplicitCast_<const char*>(s), os);
546 }
547 
548 // signed/unsigned char is often used for representing binary data, so
549 // we print pointers to it as void* to be safe.
PrintTo(const signed char * s,::std::ostream * os)550 inline void PrintTo(const signed char* s, ::std::ostream* os) {
551   PrintTo(ImplicitCast_<const void*>(s), os);
552 }
PrintTo(signed char * s,::std::ostream * os)553 inline void PrintTo(signed char* s, ::std::ostream* os) {
554   PrintTo(ImplicitCast_<const void*>(s), os);
555 }
PrintTo(const unsigned char * s,::std::ostream * os)556 inline void PrintTo(const unsigned char* s, ::std::ostream* os) {
557   PrintTo(ImplicitCast_<const void*>(s), os);
558 }
PrintTo(unsigned char * s,::std::ostream * os)559 inline void PrintTo(unsigned char* s, ::std::ostream* os) {
560   PrintTo(ImplicitCast_<const void*>(s), os);
561 }
562 
563 // MSVC can be configured to define wchar_t as a typedef of unsigned
564 // short.  It defines _NATIVE_WCHAR_T_DEFINED when wchar_t is a native
565 // type.  When wchar_t is a typedef, defining an overload for const
566 // wchar_t* would cause unsigned short* be printed as a wide string,
567 // possibly causing invalid memory accesses.
568 #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
569 // Overloads for wide C strings
570 GTEST_API_ void PrintTo(const wchar_t* s, ::std::ostream* os);
PrintTo(wchar_t * s,::std::ostream * os)571 inline void PrintTo(wchar_t* s, ::std::ostream* os) {
572   PrintTo(ImplicitCast_<const wchar_t*>(s), os);
573 }
574 #endif
575 
576 // Overload for C arrays.  Multi-dimensional arrays are printed
577 // properly.
578 
579 // Prints the given number of elements in an array, without printing
580 // the curly braces.
581 template <typename T>
PrintRawArrayTo(const T a[],size_t count,::std::ostream * os)582 void PrintRawArrayTo(const T a[], size_t count, ::std::ostream* os) {
583   UniversalPrint(a[0], os);
584   for (size_t i = 1; i != count; i++) {
585     *os << ", ";
586     UniversalPrint(a[i], os);
587   }
588 }
589 
590 // Overloads for ::std::string.
591 GTEST_API_ void PrintStringTo(const ::std::string&s, ::std::ostream* os);
PrintTo(const::std::string & s,::std::ostream * os)592 inline void PrintTo(const ::std::string& s, ::std::ostream* os) {
593   PrintStringTo(s, os);
594 }
595 
596 // Overloads for ::std::wstring.
597 #if GTEST_HAS_STD_WSTRING
598 GTEST_API_ void PrintWideStringTo(const ::std::wstring&s, ::std::ostream* os);
PrintTo(const::std::wstring & s,::std::ostream * os)599 inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) {
600   PrintWideStringTo(s, os);
601 }
602 #endif  // GTEST_HAS_STD_WSTRING
603 
604 #if GTEST_HAS_ABSL
605 // Overload for absl::string_view.
PrintTo(absl::string_view sp,::std::ostream * os)606 inline void PrintTo(absl::string_view sp, ::std::ostream* os) {
607   PrintTo(::std::string(sp), os);
608 }
609 #endif  // GTEST_HAS_ABSL
610 
PrintTo(std::nullptr_t,::std::ostream * os)611 inline void PrintTo(std::nullptr_t, ::std::ostream* os) { *os << "(nullptr)"; }
612 
613 template <typename T>
PrintTo(std::reference_wrapper<T> ref,::std::ostream * os)614 void PrintTo(std::reference_wrapper<T> ref, ::std::ostream* os) {
615   UniversalPrinter<T&>::Print(ref.get(), os);
616 }
617 
618 // Helper function for printing a tuple.  T must be instantiated with
619 // a tuple type.
620 template <typename T>
PrintTupleTo(const T &,std::integral_constant<size_t,0>,::std::ostream *)621 void PrintTupleTo(const T&, std::integral_constant<size_t, 0>,
622                   ::std::ostream*) {}
623 
624 template <typename T, size_t I>
PrintTupleTo(const T & t,std::integral_constant<size_t,I>,::std::ostream * os)625 void PrintTupleTo(const T& t, std::integral_constant<size_t, I>,
626                   ::std::ostream* os) {
627   PrintTupleTo(t, std::integral_constant<size_t, I - 1>(), os);
628   GTEST_INTENTIONAL_CONST_COND_PUSH_()
629   if (I > 1) {
630     GTEST_INTENTIONAL_CONST_COND_POP_()
631     *os << ", ";
632   }
633   UniversalPrinter<typename std::tuple_element<I - 1, T>::type>::Print(
634       std::get<I - 1>(t), os);
635 }
636 
637 template <typename... Types>
PrintTo(const::std::tuple<Types...> & t,::std::ostream * os)638 void PrintTo(const ::std::tuple<Types...>& t, ::std::ostream* os) {
639   *os << "(";
640   PrintTupleTo(t, std::integral_constant<size_t, sizeof...(Types)>(), os);
641   *os << ")";
642 }
643 
644 // Overload for std::pair.
645 template <typename T1, typename T2>
PrintTo(const::std::pair<T1,T2> & value,::std::ostream * os)646 void PrintTo(const ::std::pair<T1, T2>& value, ::std::ostream* os) {
647   *os << '(';
648   // We cannot use UniversalPrint(value.first, os) here, as T1 may be
649   // a reference type.  The same for printing value.second.
650   UniversalPrinter<T1>::Print(value.first, os);
651   *os << ", ";
652   UniversalPrinter<T2>::Print(value.second, os);
653   *os << ')';
654 }
655 
656 // Implements printing a non-reference type T by letting the compiler
657 // pick the right overload of PrintTo() for T.
658 template <typename T>
659 class UniversalPrinter {
660  public:
661   // MSVC warns about adding const to a function type, so we want to
662   // disable the warning.
663   GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180)
664 
665   // Note: we deliberately don't call this PrintTo(), as that name
666   // conflicts with ::testing::internal::PrintTo in the body of the
667   // function.
Print(const T & value,::std::ostream * os)668   static void Print(const T& value, ::std::ostream* os) {
669     // By default, ::testing::internal::PrintTo() is used for printing
670     // the value.
671     //
672     // Thanks to Koenig look-up, if T is a class and has its own
673     // PrintTo() function defined in its namespace, that function will
674     // be visible here.  Since it is more specific than the generic ones
675     // in ::testing::internal, it will be picked by the compiler in the
676     // following statement - exactly what we want.
677     PrintTo(value, os);
678   }
679 
680   GTEST_DISABLE_MSC_WARNINGS_POP_()
681 };
682 
683 #if GTEST_HAS_ABSL
684 
685 // Printer for absl::optional
686 
687 template <typename T>
688 class UniversalPrinter<::absl::optional<T>> {
689  public:
Print(const::absl::optional<T> & value,::std::ostream * os)690   static void Print(const ::absl::optional<T>& value, ::std::ostream* os) {
691     *os << '(';
692     if (!value) {
693       *os << "nullopt";
694     } else {
695       UniversalPrint(*value, os);
696     }
697     *os << ')';
698   }
699 };
700 
701 // Printer for absl::variant
702 
703 template <typename... T>
704 class UniversalPrinter<::absl::variant<T...>> {
705  public:
Print(const::absl::variant<T...> & value,::std::ostream * os)706   static void Print(const ::absl::variant<T...>& value, ::std::ostream* os) {
707     *os << '(';
708     absl::visit(Visitor{os}, value);
709     *os << ')';
710   }
711 
712  private:
713   struct Visitor {
714     template <typename U>
operatorVisitor715     void operator()(const U& u) const {
716       *os << "'" << GetTypeName<U>() << "' with value ";
717       UniversalPrint(u, os);
718     }
719     ::std::ostream* os;
720   };
721 };
722 
723 #endif  // GTEST_HAS_ABSL
724 
725 // UniversalPrintArray(begin, len, os) prints an array of 'len'
726 // elements, starting at address 'begin'.
727 template <typename T>
UniversalPrintArray(const T * begin,size_t len,::std::ostream * os)728 void UniversalPrintArray(const T* begin, size_t len, ::std::ostream* os) {
729   if (len == 0) {
730     *os << "{}";
731   } else {
732     *os << "{ ";
733     const size_t kThreshold = 18;
734     const size_t kChunkSize = 8;
735     // If the array has more than kThreshold elements, we'll have to
736     // omit some details by printing only the first and the last
737     // kChunkSize elements.
738     if (len <= kThreshold) {
739       PrintRawArrayTo(begin, len, os);
740     } else {
741       PrintRawArrayTo(begin, kChunkSize, os);
742       *os << ", ..., ";
743       PrintRawArrayTo(begin + len - kChunkSize, kChunkSize, os);
744     }
745     *os << " }";
746   }
747 }
748 // This overload prints a (const) char array compactly.
749 GTEST_API_ void UniversalPrintArray(
750     const char* begin, size_t len, ::std::ostream* os);
751 
752 // This overload prints a (const) wchar_t array compactly.
753 GTEST_API_ void UniversalPrintArray(
754     const wchar_t* begin, size_t len, ::std::ostream* os);
755 
756 // Implements printing an array type T[N].
757 template <typename T, size_t N>
758 class UniversalPrinter<T[N]> {
759  public:
760   // Prints the given array, omitting some elements when there are too
761   // many.
Print(const T (& a)[N],::std::ostream * os)762   static void Print(const T (&a)[N], ::std::ostream* os) {
763     UniversalPrintArray(a, N, os);
764   }
765 };
766 
767 // Implements printing a reference type T&.
768 template <typename T>
769 class UniversalPrinter<T&> {
770  public:
771   // MSVC warns about adding const to a function type, so we want to
772   // disable the warning.
773   GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180)
774 
Print(const T & value,::std::ostream * os)775   static void Print(const T& value, ::std::ostream* os) {
776     // Prints the address of the value.  We use reinterpret_cast here
777     // as static_cast doesn't compile when T is a function type.
778     *os << "@" << reinterpret_cast<const void*>(&value) << " ";
779 
780     // Then prints the value itself.
781     UniversalPrint(value, os);
782   }
783 
784   GTEST_DISABLE_MSC_WARNINGS_POP_()
785 };
786 
787 // Prints a value tersely: for a reference type, the referenced value
788 // (but not the address) is printed; for a (const) char pointer, the
789 // NUL-terminated string (but not the pointer) is printed.
790 
791 template <typename T>
792 class UniversalTersePrinter {
793  public:
Print(const T & value,::std::ostream * os)794   static void Print(const T& value, ::std::ostream* os) {
795     UniversalPrint(value, os);
796   }
797 };
798 template <typename T>
799 class UniversalTersePrinter<T&> {
800  public:
Print(const T & value,::std::ostream * os)801   static void Print(const T& value, ::std::ostream* os) {
802     UniversalPrint(value, os);
803   }
804 };
805 template <typename T, size_t N>
806 class UniversalTersePrinter<T[N]> {
807  public:
Print(const T (& value)[N],::std::ostream * os)808   static void Print(const T (&value)[N], ::std::ostream* os) {
809     UniversalPrinter<T[N]>::Print(value, os);
810   }
811 };
812 template <>
813 class UniversalTersePrinter<const char*> {
814  public:
Print(const char * str,::std::ostream * os)815   static void Print(const char* str, ::std::ostream* os) {
816     if (str == nullptr) {
817       *os << "NULL";
818     } else {
819       UniversalPrint(std::string(str), os);
820     }
821   }
822 };
823 template <>
824 class UniversalTersePrinter<char*> {
825  public:
Print(char * str,::std::ostream * os)826   static void Print(char* str, ::std::ostream* os) {
827     UniversalTersePrinter<const char*>::Print(str, os);
828   }
829 };
830 
831 #if GTEST_HAS_STD_WSTRING
832 template <>
833 class UniversalTersePrinter<const wchar_t*> {
834  public:
Print(const wchar_t * str,::std::ostream * os)835   static void Print(const wchar_t* str, ::std::ostream* os) {
836     if (str == nullptr) {
837       *os << "NULL";
838     } else {
839       UniversalPrint(::std::wstring(str), os);
840     }
841   }
842 };
843 #endif
844 
845 template <>
846 class UniversalTersePrinter<wchar_t*> {
847  public:
Print(wchar_t * str,::std::ostream * os)848   static void Print(wchar_t* str, ::std::ostream* os) {
849     UniversalTersePrinter<const wchar_t*>::Print(str, os);
850   }
851 };
852 
853 template <typename T>
UniversalTersePrint(const T & value,::std::ostream * os)854 void UniversalTersePrint(const T& value, ::std::ostream* os) {
855   UniversalTersePrinter<T>::Print(value, os);
856 }
857 
858 // Prints a value using the type inferred by the compiler.  The
859 // difference between this and UniversalTersePrint() is that for a
860 // (const) char pointer, this prints both the pointer and the
861 // NUL-terminated string.
862 template <typename T>
UniversalPrint(const T & value,::std::ostream * os)863 void UniversalPrint(const T& value, ::std::ostream* os) {
864   // A workarond for the bug in VC++ 7.1 that prevents us from instantiating
865   // UniversalPrinter with T directly.
866   typedef T T1;
867   UniversalPrinter<T1>::Print(value, os);
868 }
869 
870 typedef ::std::vector< ::std::string> Strings;
871 
872   // Tersely prints the first N fields of a tuple to a string vector,
873   // one element for each field.
874 template <typename Tuple>
TersePrintPrefixToStrings(const Tuple &,std::integral_constant<size_t,0>,Strings *)875 void TersePrintPrefixToStrings(const Tuple&, std::integral_constant<size_t, 0>,
876                                Strings*) {}
877 template <typename Tuple, size_t I>
TersePrintPrefixToStrings(const Tuple & t,std::integral_constant<size_t,I>,Strings * strings)878 void TersePrintPrefixToStrings(const Tuple& t,
879                                std::integral_constant<size_t, I>,
880                                Strings* strings) {
881   TersePrintPrefixToStrings(t, std::integral_constant<size_t, I - 1>(),
882                             strings);
883   ::std::stringstream ss;
884   UniversalTersePrint(std::get<I - 1>(t), &ss);
885   strings->push_back(ss.str());
886 }
887 
888 // Prints the fields of a tuple tersely to a string vector, one
889 // element for each field.  See the comment before
890 // UniversalTersePrint() for how we define "tersely".
891 template <typename Tuple>
UniversalTersePrintTupleFieldsToStrings(const Tuple & value)892 Strings UniversalTersePrintTupleFieldsToStrings(const Tuple& value) {
893   Strings result;
894   TersePrintPrefixToStrings(
895       value, std::integral_constant<size_t, std::tuple_size<Tuple>::value>(),
896       &result);
897   return result;
898 }
899 
900 }  // namespace internal
901 
902 #if GTEST_HAS_ABSL
903 namespace internal2 {
904 template <typename T>
PrintValue(const T & value,::std::ostream * os)905 void TypeWithoutFormatter<T, kConvertibleToStringView>::PrintValue(
906     const T& value, ::std::ostream* os) {
907   internal::PrintTo(absl::string_view(value), os);
908 }
909 }  // namespace internal2
910 #endif
911 
912 template <typename T>
PrintToString(const T & value)913 ::std::string PrintToString(const T& value) {
914   ::std::stringstream ss;
915   internal::UniversalTersePrinter<T>::Print(value, &ss);
916   return ss.str();
917 }
918 
919 }  // namespace testing
920 
921 // Include any custom printer added by the local installation.
922 // We must include this header at the end to make sure it can use the
923 // declarations from this file.
924 #include "gtest/internal/custom/gtest-printers.h"
925 
926 #endif  // GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
927