Revert "Move googletest to the third-party directory"
[llvm-project.git] / llvm / utils / unittest / googletest / include / gtest / gtest-printers.h
blob8479435ac7e61c14c53fdb727579ba14e72dce83
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.
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.
30 // Google Test - The Google C++ Testing and Mocking Framework
32 // This file implements a universal value printer that can print a
33 // value of any type T:
35 // void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
37 // A user can teach this function how to print a class type T by
38 // defining either operator<<() or PrintTo() in the namespace that
39 // defines T. More specifically, the FIRST defined function in the
40 // following list will be used (assuming T is defined in namespace
41 // foo):
43 // 1. foo::PrintTo(const T&, ostream*)
44 // 2. operator<<(ostream&, const T&) defined in either foo or the
45 // global namespace.
47 // However if T is an STL-style container then it is printed element-wise
48 // unless foo::PrintTo(const T&, ostream*) is defined. Note that
49 // operator<<() is ignored for container types.
51 // If none of the above is defined, it will print the debug string of
52 // the value if it is a protocol buffer, or print the raw bytes in the
53 // value otherwise.
55 // To aid debugging: when T is a reference type, the address of the
56 // value is also printed; when T is a (const) char pointer, both the
57 // pointer value and the NUL-terminated string it points to are
58 // printed.
60 // We also provide some convenient wrappers:
62 // // Prints a value to a string. For a (const or not) char
63 // // pointer, the NUL-terminated string (but not the pointer) is
64 // // printed.
65 // std::string ::testing::PrintToString(const T& value);
67 // // Prints a value tersely: for a reference type, the referenced
68 // // value (but not the address) is printed; for a (const or not) char
69 // // pointer, the NUL-terminated string (but not the pointer) is
70 // // printed.
71 // void ::testing::internal::UniversalTersePrint(const T& value, ostream*);
73 // // Prints value using the type inferred by the compiler. The difference
74 // // from UniversalTersePrint() is that this function prints both the
75 // // pointer and the NUL-terminated string for a (const or not) char pointer.
76 // void ::testing::internal::UniversalPrint(const T& value, ostream*);
78 // // Prints the fields of a tuple tersely to a string vector, one
79 // // element for each field. Tuple support must be enabled in
80 // // gtest-port.h.
81 // std::vector<string> UniversalTersePrintTupleFieldsToStrings(
82 // const Tuple& value);
84 // Known limitation:
86 // The print primitives print the elements of an STL-style container
87 // using the compiler-inferred type of *iter where iter is a
88 // const_iterator of the container. When const_iterator is an input
89 // iterator but not a forward iterator, this inferred type may not
90 // match value_type, and the print output may be incorrect. In
91 // practice, this is rarely a problem as for most containers
92 // const_iterator is a forward iterator. We'll fix this if there's an
93 // actual need for it. Note that this fix cannot rely on value_type
94 // being defined as many user-defined container types don't have
95 // value_type.
97 // GOOGLETEST_CM0001 DO NOT DELETE
99 // IWYU pragma: private, include "gtest/gtest.h"
100 // IWYU pragma: friend gtest/.*
101 // IWYU pragma: friend gmock/.*
103 #ifndef GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
104 #define GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
106 #include <functional>
107 #include <ostream> // NOLINT
108 #include <sstream>
109 #include <string>
110 #include <tuple>
111 #include <type_traits>
112 #include <utility>
113 #include <vector>
114 #include "gtest/internal/gtest-internal.h"
115 #include "gtest/internal/gtest-port.h"
116 #include "gtest/internal/custom/raw-ostream.h"
118 #if GTEST_HAS_ABSL
119 #include "absl/strings/string_view.h"
120 #include "absl/types/optional.h"
121 #include "absl/types/variant.h"
122 #endif // GTEST_HAS_ABSL
124 namespace testing {
126 // Definitions in the 'internal' and 'internal2' name spaces are
127 // subject to change without notice. DO NOT USE THEM IN USER CODE!
128 namespace internal2 {
130 // Prints the given number of bytes in the given object to the given
131 // ostream.
132 GTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes,
133 size_t count,
134 ::std::ostream* os);
136 // For selecting which printer to use when a given type has neither <<
137 // nor PrintTo().
138 enum TypeKind {
139 kProtobuf, // a protobuf type
140 kConvertibleToInteger, // a type implicitly convertible to BiggestInt
141 // (e.g. a named or unnamed enum type)
142 #if GTEST_HAS_ABSL
143 kConvertibleToStringView, // a type implicitly convertible to
144 // absl::string_view
145 #endif
146 kOtherType // anything else
149 // TypeWithoutFormatter<T, kTypeKind>::PrintValue(value, os) is called
150 // by the universal printer to print a value of type T when neither
151 // operator<< nor PrintTo() is defined for T, where kTypeKind is the
152 // "kind" of T as defined by enum TypeKind.
153 template <typename T, TypeKind kTypeKind>
154 class TypeWithoutFormatter {
155 public:
156 // This default version is called when kTypeKind is kOtherType.
157 static void PrintValue(const T& value, ::std::ostream* os) {
158 PrintBytesInObjectTo(
159 static_cast<const unsigned char*>(
160 reinterpret_cast<const void*>(std::addressof(value))),
161 sizeof(value), os);
165 // We print a protobuf using its ShortDebugString() when the string
166 // doesn't exceed this many characters; otherwise we print it using
167 // DebugString() for better readability.
168 const size_t kProtobufOneLinerMaxLength = 50;
170 template <typename T>
171 class TypeWithoutFormatter<T, kProtobuf> {
172 public:
173 static void PrintValue(const T& value, ::std::ostream* os) {
174 std::string pretty_str = value.ShortDebugString();
175 if (pretty_str.length() > kProtobufOneLinerMaxLength) {
176 pretty_str = "\n" + value.DebugString();
178 *os << ("<" + pretty_str + ">");
182 template <typename T>
183 class TypeWithoutFormatter<T, kConvertibleToInteger> {
184 public:
185 // Since T has no << operator or PrintTo() but can be implicitly
186 // converted to BiggestInt, we print it as a BiggestInt.
188 // Most likely T is an enum type (either named or unnamed), in which
189 // case printing it as an integer is the desired behavior. In case
190 // T is not an enum, printing it as an integer is the best we can do
191 // given that it has no user-defined printer.
192 static void PrintValue(const T& value, ::std::ostream* os) {
193 const internal::BiggestInt kBigInt = value;
194 *os << kBigInt;
198 #if GTEST_HAS_ABSL
199 template <typename T>
200 class TypeWithoutFormatter<T, kConvertibleToStringView> {
201 public:
202 // Since T has neither operator<< nor PrintTo() but can be implicitly
203 // converted to absl::string_view, we print it as a absl::string_view.
205 // Note: the implementation is further below, as it depends on
206 // internal::PrintTo symbol which is defined later in the file.
207 static void PrintValue(const T& value, ::std::ostream* os);
209 #endif
211 // Prints the given value to the given ostream. If the value is a
212 // protocol message, its debug string is printed; if it's an enum or
213 // of a type implicitly convertible to BiggestInt, it's printed as an
214 // integer; otherwise the bytes in the value are printed. This is
215 // what UniversalPrinter<T>::Print() does when it knows nothing about
216 // type T and T has neither << operator nor PrintTo().
218 // A user can override this behavior for a class type Foo by defining
219 // a << operator in the namespace where Foo is defined.
221 // We put this operator in namespace 'internal2' instead of 'internal'
222 // to simplify the implementation, as much code in 'internal' needs to
223 // use << in STL, which would conflict with our own << were it defined
224 // in 'internal'.
226 // Note that this operator<< takes a generic std::basic_ostream<Char,
227 // CharTraits> type instead of the more restricted std::ostream. If
228 // we define it to take an std::ostream instead, we'll get an
229 // "ambiguous overloads" compiler error when trying to print a type
230 // Foo that supports streaming to std::basic_ostream<Char,
231 // CharTraits>, as the compiler cannot tell whether
232 // operator<<(std::ostream&, const T&) or
233 // operator<<(std::basic_stream<Char, CharTraits>, const Foo&) is more
234 // specific.
235 template <typename Char, typename CharTraits, typename T>
236 ::std::basic_ostream<Char, CharTraits>& operator<<(
237 ::std::basic_ostream<Char, CharTraits>& os, const T& x) {
238 TypeWithoutFormatter<T, (internal::IsAProtocolMessage<T>::value
239 ? kProtobuf
240 : std::is_convertible<
241 const T&, internal::BiggestInt>::value
242 ? kConvertibleToInteger
244 #if GTEST_HAS_ABSL
245 std::is_convertible<
246 const T&, absl::string_view>::value
247 ? kConvertibleToStringView
249 #endif
250 kOtherType)>::PrintValue(x, &os);
251 return os;
254 } // namespace internal2
255 } // namespace testing
257 // This namespace MUST NOT BE NESTED IN ::testing, or the name look-up
258 // magic needed for implementing UniversalPrinter won't work.
259 namespace testing_internal {
261 // Used to print a value that is not an STL-style container when the
262 // user doesn't define PrintTo() for it.
263 template <typename T>
264 void DefaultPrintNonContainerTo(const T& value, ::std::ostream* os) {
265 // With the following statement, during unqualified name lookup,
266 // testing::internal2::operator<< appears as if it was declared in
267 // the nearest enclosing namespace that contains both
268 // ::testing_internal and ::testing::internal2, i.e. the global
269 // namespace. For more details, refer to the C++ Standard section
270 // 7.3.4-1 [namespace.udir]. This allows us to fall back onto
271 // testing::internal2::operator<< in case T doesn't come with a <<
272 // operator.
274 // We cannot write 'using ::testing::internal2::operator<<;', which
275 // gcc 3.3 fails to compile due to a compiler bug.
276 using namespace ::testing::internal2; // NOLINT
278 // Assuming T is defined in namespace foo, in the next statement,
279 // the compiler will consider all of:
281 // 1. foo::operator<< (thanks to Koenig look-up),
282 // 2. ::operator<< (as the current namespace is enclosed in ::),
283 // 3. testing::internal2::operator<< (thanks to the using statement above).
285 // The operator<< whose type matches T best will be picked.
287 // We deliberately allow #2 to be a candidate, as sometimes it's
288 // impossible to define #1 (e.g. when foo is ::std, defining
289 // anything in it is undefined behavior unless you are a compiler
290 // vendor.).
291 *os << ::llvm_gtest::printable(value);
294 } // namespace testing_internal
296 namespace testing {
297 namespace internal {
299 // FormatForComparison<ToPrint, OtherOperand>::Format(value) formats a
300 // value of type ToPrint that is an operand of a comparison assertion
301 // (e.g. ASSERT_EQ). OtherOperand is the type of the other operand in
302 // the comparison, and is used to help determine the best way to
303 // format the value. In particular, when the value is a C string
304 // (char pointer) and the other operand is an STL string object, we
305 // want to format the C string as a string, since we know it is
306 // compared by value with the string object. If the value is a char
307 // pointer but the other operand is not an STL string object, we don't
308 // know whether the pointer is supposed to point to a NUL-terminated
309 // string, and thus want to print it as a pointer to be safe.
311 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
313 // The default case.
314 template <typename ToPrint, typename OtherOperand>
315 class FormatForComparison {
316 public:
317 static ::std::string Format(const ToPrint& value) {
318 return ::testing::PrintToString(value);
322 // Array.
323 template <typename ToPrint, size_t N, typename OtherOperand>
324 class FormatForComparison<ToPrint[N], OtherOperand> {
325 public:
326 static ::std::string Format(const ToPrint* value) {
327 return FormatForComparison<const ToPrint*, OtherOperand>::Format(value);
331 // By default, print C string as pointers to be safe, as we don't know
332 // whether they actually point to a NUL-terminated string.
334 #define GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(CharType) \
335 template <typename OtherOperand> \
336 class FormatForComparison<CharType*, OtherOperand> { \
337 public: \
338 static ::std::string Format(CharType* value) { \
339 return ::testing::PrintToString(static_cast<const void*>(value)); \
343 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char);
344 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char);
345 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(wchar_t);
346 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const wchar_t);
348 #undef GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_
350 // If a C string is compared with an STL string object, we know it's meant
351 // to point to a NUL-terminated string, and thus can print it as a string.
353 #define GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(CharType, OtherStringType) \
354 template <> \
355 class FormatForComparison<CharType*, OtherStringType> { \
356 public: \
357 static ::std::string Format(CharType* value) { \
358 return ::testing::PrintToString(value); \
362 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::std::string);
363 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char, ::std::string);
365 #if GTEST_HAS_STD_WSTRING
366 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(wchar_t, ::std::wstring);
367 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const wchar_t, ::std::wstring);
368 #endif
370 #undef GTEST_IMPL_FORMAT_C_STRING_AS_STRING_
372 // Formats a comparison assertion (e.g. ASSERT_EQ, EXPECT_LT, and etc)
373 // operand to be used in a failure message. The type (but not value)
374 // of the other operand may affect the format. This allows us to
375 // print a char* as a raw pointer when it is compared against another
376 // char* or void*, and print it as a C string when it is compared
377 // against an std::string object, for example.
379 // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
380 template <typename T1, typename T2>
381 std::string FormatForComparisonFailureMessage(
382 const T1& value, const T2& /* other_operand */) {
383 return FormatForComparison<T1, T2>::Format(value);
386 // UniversalPrinter<T>::Print(value, ostream_ptr) prints the given
387 // value to the given ostream. The caller must ensure that
388 // 'ostream_ptr' is not NULL, or the behavior is undefined.
390 // We define UniversalPrinter as a class template (as opposed to a
391 // function template), as we need to partially specialize it for
392 // reference types, which cannot be done with function templates.
393 template <typename T>
394 class UniversalPrinter;
396 template <typename T>
397 void UniversalPrint(const T& value, ::std::ostream* os);
399 enum DefaultPrinterType {
400 kPrintContainer,
401 kPrintPointer,
402 kPrintFunctionPointer,
403 kPrintOther,
405 template <DefaultPrinterType type> struct WrapPrinterType {};
407 // Used to print an STL-style container when the user doesn't define
408 // a PrintTo() for it.
409 template <typename C>
410 void DefaultPrintTo(WrapPrinterType<kPrintContainer> /* dummy */,
411 const C& container, ::std::ostream* os) {
412 const size_t kMaxCount = 32; // The maximum number of elements to print.
413 *os << '{';
414 size_t count = 0;
415 for (typename C::const_iterator it = container.begin();
416 it != container.end(); ++it, ++count) {
417 if (count > 0) {
418 *os << ',';
419 if (count == kMaxCount) { // Enough has been printed.
420 *os << " ...";
421 break;
424 *os << ' ';
425 // We cannot call PrintTo(*it, os) here as PrintTo() doesn't
426 // handle *it being a native array.
427 internal::UniversalPrint(*it, os);
430 if (count > 0) {
431 *os << ' ';
433 *os << '}';
436 // Used to print a pointer that is neither a char pointer nor a member
437 // pointer, when the user doesn't define PrintTo() for it. (A member
438 // variable pointer or member function pointer doesn't really point to
439 // a location in the address space. Their representation is
440 // implementation-defined. Therefore they will be printed as raw
441 // bytes.)
442 template <typename T>
443 void DefaultPrintTo(WrapPrinterType<kPrintPointer> /* dummy */,
444 T* p, ::std::ostream* os) {
445 if (p == nullptr) {
446 *os << "NULL";
447 } else {
448 // T is not a function type. We just call << to print p,
449 // relying on ADL to pick up user-defined << for their pointer
450 // types, if any.
451 *os << p;
454 template <typename T>
455 void DefaultPrintTo(WrapPrinterType<kPrintFunctionPointer> /* dummy */,
456 T* p, ::std::ostream* os) {
457 if (p == nullptr) {
458 *os << "NULL";
459 } else {
460 // T is a function type, so '*os << p' doesn't do what we want
461 // (it just prints p as bool). We want to print p as a const
462 // void*.
463 *os << reinterpret_cast<const void*>(p);
467 // Used to print a non-container, non-pointer value when the user
468 // doesn't define PrintTo() for it.
469 template <typename T>
470 void DefaultPrintTo(WrapPrinterType<kPrintOther> /* dummy */,
471 const T& value, ::std::ostream* os) {
472 ::testing_internal::DefaultPrintNonContainerTo(value, os);
475 // Prints the given value using the << operator if it has one;
476 // otherwise prints the bytes in it. This is what
477 // UniversalPrinter<T>::Print() does when PrintTo() is not specialized
478 // or overloaded for type T.
480 // A user can override this behavior for a class type Foo by defining
481 // an overload of PrintTo() in the namespace where Foo is defined. We
482 // give the user this option as sometimes defining a << operator for
483 // Foo is not desirable (e.g. the coding style may prevent doing it,
484 // or there is already a << operator but it doesn't do what the user
485 // wants).
486 template <typename T>
487 void PrintTo(const T& value, ::std::ostream* os) {
488 // DefaultPrintTo() is overloaded. The type of its first argument
489 // determines which version will be picked.
491 // Note that we check for container types here, prior to we check
492 // for protocol message types in our operator<<. The rationale is:
494 // For protocol messages, we want to give people a chance to
495 // override Google Mock's format by defining a PrintTo() or
496 // operator<<. For STL containers, other formats can be
497 // incompatible with Google Mock's format for the container
498 // elements; therefore we check for container types here to ensure
499 // that our format is used.
501 // Note that MSVC and clang-cl do allow an implicit conversion from
502 // pointer-to-function to pointer-to-object, but clang-cl warns on it.
503 // So don't use ImplicitlyConvertible if it can be helped since it will
504 // cause this warning, and use a separate overload of DefaultPrintTo for
505 // function pointers so that the `*os << p` in the object pointer overload
506 // doesn't cause that warning either.
507 DefaultPrintTo(
508 WrapPrinterType <
509 (sizeof(IsContainerTest<T>(0)) == sizeof(IsContainer)) &&
510 !IsRecursiveContainer<T>::value
511 ? kPrintContainer
512 : !std::is_pointer<T>::value
513 ? kPrintOther
514 : std::is_function<typename std::remove_pointer<T>::type>::value
515 ? kPrintFunctionPointer
516 : kPrintPointer > (),
517 value, os);
520 // The following list of PrintTo() overloads tells
521 // UniversalPrinter<T>::Print() how to print standard types (built-in
522 // types, strings, plain arrays, and pointers).
524 // Overloads for various char types.
525 GTEST_API_ void PrintTo(unsigned char c, ::std::ostream* os);
526 GTEST_API_ void PrintTo(signed char c, ::std::ostream* os);
527 inline void PrintTo(char c, ::std::ostream* os) {
528 // When printing a plain char, we always treat it as unsigned. This
529 // way, the output won't be affected by whether the compiler thinks
530 // char is signed or not.
531 PrintTo(static_cast<unsigned char>(c), os);
534 // Overloads for other simple built-in types.
535 inline void PrintTo(bool x, ::std::ostream* os) {
536 *os << (x ? "true" : "false");
539 // Overload for wchar_t type.
540 // Prints a wchar_t as a symbol if it is printable or as its internal
541 // code otherwise and also as its decimal code (except for L'\0').
542 // The L'\0' char is printed as "L'\\0'". The decimal code is printed
543 // as signed integer when wchar_t is implemented by the compiler
544 // as a signed type and is printed as an unsigned integer when wchar_t
545 // is implemented as an unsigned type.
546 GTEST_API_ void PrintTo(wchar_t wc, ::std::ostream* os);
548 // Overloads for C strings.
549 GTEST_API_ void PrintTo(const char* s, ::std::ostream* os);
550 inline void PrintTo(char* s, ::std::ostream* os) {
551 PrintTo(ImplicitCast_<const char*>(s), os);
554 // signed/unsigned char is often used for representing binary data, so
555 // we print pointers to it as void* to be safe.
556 inline void PrintTo(const signed char* s, ::std::ostream* os) {
557 PrintTo(ImplicitCast_<const void*>(s), os);
559 inline void PrintTo(signed char* s, ::std::ostream* os) {
560 PrintTo(ImplicitCast_<const void*>(s), os);
562 inline void PrintTo(const unsigned char* s, ::std::ostream* os) {
563 PrintTo(ImplicitCast_<const void*>(s), os);
565 inline void PrintTo(unsigned char* s, ::std::ostream* os) {
566 PrintTo(ImplicitCast_<const void*>(s), os);
569 // MSVC can be configured to define wchar_t as a typedef of unsigned
570 // short. It defines _NATIVE_WCHAR_T_DEFINED when wchar_t is a native
571 // type. When wchar_t is a typedef, defining an overload for const
572 // wchar_t* would cause unsigned short* be printed as a wide string,
573 // possibly causing invalid memory accesses.
574 #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
575 // Overloads for wide C strings
576 GTEST_API_ void PrintTo(const wchar_t* s, ::std::ostream* os);
577 inline void PrintTo(wchar_t* s, ::std::ostream* os) {
578 PrintTo(ImplicitCast_<const wchar_t*>(s), os);
580 #endif
582 // Overload for C arrays. Multi-dimensional arrays are printed
583 // properly.
585 // Prints the given number of elements in an array, without printing
586 // the curly braces.
587 template <typename T>
588 void PrintRawArrayTo(const T a[], size_t count, ::std::ostream* os) {
589 UniversalPrint(a[0], os);
590 for (size_t i = 1; i != count; i++) {
591 *os << ", ";
592 UniversalPrint(a[i], os);
596 // Overloads for ::std::string.
597 GTEST_API_ void PrintStringTo(const ::std::string&s, ::std::ostream* os);
598 inline void PrintTo(const ::std::string& s, ::std::ostream* os) {
599 PrintStringTo(s, os);
602 // Overloads for ::std::wstring.
603 #if GTEST_HAS_STD_WSTRING
604 GTEST_API_ void PrintWideStringTo(const ::std::wstring&s, ::std::ostream* os);
605 inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) {
606 PrintWideStringTo(s, os);
608 #endif // GTEST_HAS_STD_WSTRING
610 #if GTEST_HAS_ABSL
611 // Overload for absl::string_view.
612 inline void PrintTo(absl::string_view sp, ::std::ostream* os) {
613 PrintTo(::std::string(sp), os);
615 #endif // GTEST_HAS_ABSL
617 inline void PrintTo(std::nullptr_t, ::std::ostream* os) { *os << "(nullptr)"; }
619 template <typename T>
620 void PrintTo(std::reference_wrapper<T> ref, ::std::ostream* os) {
621 UniversalPrinter<T&>::Print(ref.get(), os);
624 // Helper function for printing a tuple. T must be instantiated with
625 // a tuple type.
626 template <typename T>
627 void PrintTupleTo(const T&, std::integral_constant<size_t, 0>,
628 ::std::ostream*) {}
630 template <typename T, size_t I>
631 void PrintTupleTo(const T& t, std::integral_constant<size_t, I>,
632 ::std::ostream* os) {
633 PrintTupleTo(t, std::integral_constant<size_t, I - 1>(), os);
634 GTEST_INTENTIONAL_CONST_COND_PUSH_()
635 if (I > 1) {
636 GTEST_INTENTIONAL_CONST_COND_POP_()
637 *os << ", ";
639 UniversalPrinter<typename std::tuple_element<I - 1, T>::type>::Print(
640 std::get<I - 1>(t), os);
643 template <typename... Types>
644 void PrintTo(const ::std::tuple<Types...>& t, ::std::ostream* os) {
645 *os << "(";
646 PrintTupleTo(t, std::integral_constant<size_t, sizeof...(Types)>(), os);
647 *os << ")";
650 // Overload for std::pair.
651 template <typename T1, typename T2>
652 void PrintTo(const ::std::pair<T1, T2>& value, ::std::ostream* os) {
653 *os << '(';
654 // We cannot use UniversalPrint(value.first, os) here, as T1 may be
655 // a reference type. The same for printing value.second.
656 UniversalPrinter<T1>::Print(value.first, os);
657 *os << ", ";
658 UniversalPrinter<T2>::Print(value.second, os);
659 *os << ')';
662 // Implements printing a non-reference type T by letting the compiler
663 // pick the right overload of PrintTo() for T.
664 template <typename T>
665 class UniversalPrinter {
666 public:
667 // MSVC warns about adding const to a function type, so we want to
668 // disable the warning.
669 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180)
671 // Note: we deliberately don't call this PrintTo(), as that name
672 // conflicts with ::testing::internal::PrintTo in the body of the
673 // function.
674 static void Print(const T& value, ::std::ostream* os) {
675 // By default, ::testing::internal::PrintTo() is used for printing
676 // the value.
678 // Thanks to Koenig look-up, if T is a class and has its own
679 // PrintTo() function defined in its namespace, that function will
680 // be visible here. Since it is more specific than the generic ones
681 // in ::testing::internal, it will be picked by the compiler in the
682 // following statement - exactly what we want.
683 PrintTo(value, os);
686 GTEST_DISABLE_MSC_WARNINGS_POP_()
689 #if GTEST_HAS_ABSL
691 // Printer for absl::optional
693 template <typename T>
694 class UniversalPrinter<::absl::optional<T>> {
695 public:
696 static void Print(const ::absl::optional<T>& value, ::std::ostream* os) {
697 *os << '(';
698 if (!value) {
699 *os << "nullopt";
700 } else {
701 UniversalPrint(*value, os);
703 *os << ')';
707 // Printer for absl::variant
709 template <typename... T>
710 class UniversalPrinter<::absl::variant<T...>> {
711 public:
712 static void Print(const ::absl::variant<T...>& value, ::std::ostream* os) {
713 *os << '(';
714 absl::visit(Visitor{os}, value);
715 *os << ')';
718 private:
719 struct Visitor {
720 template <typename U>
721 void operator()(const U& u) const {
722 *os << "'" << GetTypeName<U>() << "' with value ";
723 UniversalPrint(u, os);
725 ::std::ostream* os;
729 #endif // GTEST_HAS_ABSL
731 // UniversalPrintArray(begin, len, os) prints an array of 'len'
732 // elements, starting at address 'begin'.
733 template <typename T>
734 void UniversalPrintArray(const T* begin, size_t len, ::std::ostream* os) {
735 if (len == 0) {
736 *os << "{}";
737 } else {
738 *os << "{ ";
739 const size_t kThreshold = 18;
740 const size_t kChunkSize = 8;
741 // If the array has more than kThreshold elements, we'll have to
742 // omit some details by printing only the first and the last
743 // kChunkSize elements.
744 if (len <= kThreshold) {
745 PrintRawArrayTo(begin, len, os);
746 } else {
747 PrintRawArrayTo(begin, kChunkSize, os);
748 *os << ", ..., ";
749 PrintRawArrayTo(begin + len - kChunkSize, kChunkSize, os);
751 *os << " }";
754 // This overload prints a (const) char array compactly.
755 GTEST_API_ void UniversalPrintArray(
756 const char* begin, size_t len, ::std::ostream* os);
758 // This overload prints a (const) wchar_t array compactly.
759 GTEST_API_ void UniversalPrintArray(
760 const wchar_t* begin, size_t len, ::std::ostream* os);
762 // Implements printing an array type T[N].
763 template <typename T, size_t N>
764 class UniversalPrinter<T[N]> {
765 public:
766 // Prints the given array, omitting some elements when there are too
767 // many.
768 static void Print(const T (&a)[N], ::std::ostream* os) {
769 UniversalPrintArray(a, N, os);
773 // Implements printing a reference type T&.
774 template <typename T>
775 class UniversalPrinter<T&> {
776 public:
777 // MSVC warns about adding const to a function type, so we want to
778 // disable the warning.
779 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180)
781 static void Print(const T& value, ::std::ostream* os) {
782 // Prints the address of the value. We use reinterpret_cast here
783 // as static_cast doesn't compile when T is a function type.
784 *os << "@" << reinterpret_cast<const void*>(&value) << " ";
786 // Then prints the value itself.
787 UniversalPrint(value, os);
790 GTEST_DISABLE_MSC_WARNINGS_POP_()
793 // Prints a value tersely: for a reference type, the referenced value
794 // (but not the address) is printed; for a (const) char pointer, the
795 // NUL-terminated string (but not the pointer) is printed.
797 template <typename T>
798 class UniversalTersePrinter {
799 public:
800 static void Print(const T& value, ::std::ostream* os) {
801 UniversalPrint(value, os);
804 template <typename T>
805 class UniversalTersePrinter<T&> {
806 public:
807 static void Print(const T& value, ::std::ostream* os) {
808 UniversalPrint(value, os);
811 template <typename T, size_t N>
812 class UniversalTersePrinter<T[N]> {
813 public:
814 static void Print(const T (&value)[N], ::std::ostream* os) {
815 UniversalPrinter<T[N]>::Print(value, os);
818 template <>
819 class UniversalTersePrinter<const char*> {
820 public:
821 static void Print(const char* str, ::std::ostream* os) {
822 if (str == nullptr) {
823 *os << "NULL";
824 } else {
825 UniversalPrint(std::string(str), os);
829 template <>
830 class UniversalTersePrinter<char*> {
831 public:
832 static void Print(char* str, ::std::ostream* os) {
833 UniversalTersePrinter<const char*>::Print(str, os);
837 #if GTEST_HAS_STD_WSTRING
838 template <>
839 class UniversalTersePrinter<const wchar_t*> {
840 public:
841 static void Print(const wchar_t* str, ::std::ostream* os) {
842 if (str == nullptr) {
843 *os << "NULL";
844 } else {
845 UniversalPrint(::std::wstring(str), os);
849 #endif
851 template <>
852 class UniversalTersePrinter<wchar_t*> {
853 public:
854 static void Print(wchar_t* str, ::std::ostream* os) {
855 UniversalTersePrinter<const wchar_t*>::Print(str, os);
859 template <typename T>
860 void UniversalTersePrint(const T& value, ::std::ostream* os) {
861 UniversalTersePrinter<T>::Print(value, os);
864 // Prints a value using the type inferred by the compiler. The
865 // difference between this and UniversalTersePrint() is that for a
866 // (const) char pointer, this prints both the pointer and the
867 // NUL-terminated string.
868 template <typename T>
869 void UniversalPrint(const T& value, ::std::ostream* os) {
870 // A workarond for the bug in VC++ 7.1 that prevents us from instantiating
871 // UniversalPrinter with T directly.
872 typedef T T1;
873 UniversalPrinter<T1>::Print(value, os);
876 typedef ::std::vector< ::std::string> Strings;
878 // Tersely prints the first N fields of a tuple to a string vector,
879 // one element for each field.
880 template <typename Tuple>
881 void TersePrintPrefixToStrings(const Tuple&, std::integral_constant<size_t, 0>,
882 Strings*) {}
883 template <typename Tuple, size_t I>
884 void TersePrintPrefixToStrings(const Tuple& t,
885 std::integral_constant<size_t, I>,
886 Strings* strings) {
887 TersePrintPrefixToStrings(t, std::integral_constant<size_t, I - 1>(),
888 strings);
889 ::std::stringstream ss;
890 UniversalTersePrint(std::get<I - 1>(t), &ss);
891 strings->push_back(ss.str());
894 // Prints the fields of a tuple tersely to a string vector, one
895 // element for each field. See the comment before
896 // UniversalTersePrint() for how we define "tersely".
897 template <typename Tuple>
898 Strings UniversalTersePrintTupleFieldsToStrings(const Tuple& value) {
899 Strings result;
900 TersePrintPrefixToStrings(
901 value, std::integral_constant<size_t, std::tuple_size<Tuple>::value>(),
902 &result);
903 return result;
906 } // namespace internal
908 #if GTEST_HAS_ABSL
909 namespace internal2 {
910 template <typename T>
911 void TypeWithoutFormatter<T, kConvertibleToStringView>::PrintValue(
912 const T& value, ::std::ostream* os) {
913 internal::PrintTo(absl::string_view(value), os);
915 } // namespace internal2
916 #endif
918 template <typename T>
919 ::std::string PrintToString(const T& value) {
920 ::std::stringstream ss;
921 internal::UniversalTersePrinter<T>::Print(value, &ss);
922 return ss.str();
925 } // namespace testing
927 // Include any custom printer added by the local installation.
928 // We must include this header at the end to make sure it can use the
929 // declarations from this file.
930 #include "gtest/internal/custom/gtest-printers.h"
932 #endif // GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_