Path: blob/master/dep/googletest/include/gtest/gtest-printers.h
4806 views
// Copyright 2007, Google Inc.1// All rights reserved.2//3// Redistribution and use in source and binary forms, with or without4// modification, are permitted provided that the following conditions are5// met:6//7// * Redistributions of source code must retain the above copyright8// notice, this list of conditions and the following disclaimer.9// * Redistributions in binary form must reproduce the above10// copyright notice, this list of conditions and the following disclaimer11// in the documentation and/or other materials provided with the12// distribution.13// * Neither the name of Google Inc. nor the names of its14// contributors may be used to endorse or promote products derived from15// this software without specific prior written permission.16//17// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS18// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT19// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR20// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT21// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,22// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT23// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,24// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY25// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT26// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE27// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.2829// Google Test - The Google C++ Testing and Mocking Framework30//31// This file implements a universal value printer that can print a32// value of any type T:33//34// void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);35//36// A user can teach this function how to print a class type T by37// defining either operator<<() or PrintTo() in the namespace that38// defines T. More specifically, the FIRST defined function in the39// following list will be used (assuming T is defined in namespace40// foo):41//42// 1. foo::PrintTo(const T&, ostream*)43// 2. operator<<(ostream&, const T&) defined in either foo or the44// global namespace.45// * Prefer AbslStringify(..) to operator<<(..), per https://abseil.io/tips/215.46// * Define foo::PrintTo(..) if the type already has AbslStringify(..), but an47// alternative presentation in test results is of interest.48//49// However if T is an STL-style container then it is printed element-wise50// unless foo::PrintTo(const T&, ostream*) is defined. Note that51// operator<<() is ignored for container types.52//53// If none of the above is defined, it will print the debug string of54// the value if it is a protocol buffer, or print the raw bytes in the55// value otherwise.56//57// To aid debugging: when T is a reference type, the address of the58// value is also printed; when T is a (const) char pointer, both the59// pointer value and the NUL-terminated string it points to are60// printed.61//62// We also provide some convenient wrappers:63//64// // Prints a value to a string. For a (const or not) char65// // pointer, the NUL-terminated string (but not the pointer) is66// // printed.67// std::string ::testing::PrintToString(const T& value);68//69// // Prints a value tersely: for a reference type, the referenced70// // value (but not the address) is printed; for a (const or not) char71// // pointer, the NUL-terminated string (but not the pointer) is72// // printed.73// void ::testing::internal::UniversalTersePrint(const T& value, ostream*);74//75// // Prints value using the type inferred by the compiler. The difference76// // from UniversalTersePrint() is that this function prints both the77// // pointer and the NUL-terminated string for a (const or not) char pointer.78// void ::testing::internal::UniversalPrint(const T& value, ostream*);79//80// // Prints the fields of a tuple tersely to a string vector, one81// // element for each field. Tuple support must be enabled in82// // gtest-port.h.83// std::vector<string> UniversalTersePrintTupleFieldsToStrings(84// const Tuple& value);85//86// Known limitation:87//88// The print primitives print the elements of an STL-style container89// using the compiler-inferred type of *iter where iter is a90// const_iterator of the container. When const_iterator is an input91// iterator but not a forward iterator, this inferred type may not92// match value_type, and the print output may be incorrect. In93// practice, this is rarely a problem as for most containers94// const_iterator is a forward iterator. We'll fix this if there's an95// actual need for it. Note that this fix cannot rely on value_type96// being defined as many user-defined container types don't have97// value_type.9899// IWYU pragma: private, include "gtest/gtest.h"100// IWYU pragma: friend gtest/.*101// IWYU pragma: friend gmock/.*102103#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_104#define GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_105106#include <functional>107#include <memory>108#include <ostream> // NOLINT109#include <sstream>110#include <string>111#include <tuple>112#include <type_traits>113#include <typeinfo>114#include <utility>115#include <vector>116117#ifdef GTEST_HAS_ABSL118#include "absl/strings/has_absl_stringify.h"119#include "absl/strings/str_cat.h"120#endif // GTEST_HAS_ABSL121#include "gtest/internal/gtest-internal.h"122#include "gtest/internal/gtest-port.h"123124#if GTEST_INTERNAL_HAS_STD_SPAN125#include <span> // NOLINT126#endif // GTEST_INTERNAL_HAS_STD_SPAN127128#if GTEST_INTERNAL_HAS_COMPARE_LIB129#include <compare> // NOLINT130#endif // GTEST_INTERNAL_HAS_COMPARE_LIB131132namespace testing {133134// Definitions in the internal* namespaces are subject to change without notice.135// DO NOT USE THEM IN USER CODE!136namespace internal {137138template <typename T>139void UniversalPrint(const T& value, ::std::ostream* os);140141template <typename T>142struct IsStdSpan {143static constexpr bool value = false;144};145146#if GTEST_INTERNAL_HAS_STD_SPAN147template <typename E>148struct IsStdSpan<std::span<E>> {149static constexpr bool value = true;150};151#endif // GTEST_INTERNAL_HAS_STD_SPAN152153// Used to print an STL-style container when the user doesn't define154// a PrintTo() for it.155//156// NOTE: Since std::span does not have const_iterator until C++23, it would157// fail IsContainerTest before C++23. However, IsContainerTest only uses158// the presence of const_iterator to avoid treating iterators as containers159// because of iterator::iterator. Which means std::span satisfies the *intended*160// condition of IsContainerTest.161struct ContainerPrinter {162template <typename T,163typename = typename std::enable_if<164((sizeof(IsContainerTest<T>(0)) == sizeof(IsContainer)) &&165!IsRecursiveContainer<T>::value) ||166IsStdSpan<T>::value>::type>167static void PrintValue(const T& container, std::ostream* os) {168const size_t kMaxCount = 32; // The maximum number of elements to print.169*os << '{';170size_t count = 0;171for (auto&& elem : container) {172if (count > 0) {173*os << ',';174if (count == kMaxCount) { // Enough has been printed.175*os << " ...";176break;177}178}179*os << ' ';180// We cannot call PrintTo(elem, os) here as PrintTo() doesn't181// handle `elem` being a native array.182internal::UniversalPrint(elem, os);183++count;184}185186if (count > 0) {187*os << ' ';188}189*os << '}';190}191};192193// Used to print a pointer that is neither a char pointer nor a member194// pointer, when the user doesn't define PrintTo() for it. (A member195// variable pointer or member function pointer doesn't really point to196// a location in the address space. Their representation is197// implementation-defined. Therefore they will be printed as raw198// bytes.)199struct FunctionPointerPrinter {200template <typename T, typename = typename std::enable_if<201std::is_function<T>::value>::type>202static void PrintValue(T* p, ::std::ostream* os) {203if (p == nullptr) {204*os << "NULL";205} else {206// T is a function type, so '*os << p' doesn't do what we want207// (it just prints p as bool). We want to print p as a const208// void*.209*os << reinterpret_cast<const void*>(p);210}211}212};213214struct PointerPrinter {215template <typename T>216static void PrintValue(T* p, ::std::ostream* os) {217if (p == nullptr) {218*os << "NULL";219} else {220// T is not a function type. We just call << to print p,221// relying on ADL to pick up user-defined << for their pointer222// types, if any.223*os << p;224}225}226};227228namespace internal_stream_operator_without_lexical_name_lookup {229230// The presence of an operator<< here will terminate lexical scope lookup231// straight away (even though it cannot be a match because of its argument232// types). Thus, the two operator<< calls in StreamPrinter will find only ADL233// candidates.234struct LookupBlocker {};235void operator<<(LookupBlocker, LookupBlocker);236237struct StreamPrinter {238template <typename T,239// Don't accept member pointers here. We'd print them via implicit240// conversion to bool, which isn't useful.241typename = typename std::enable_if<242!std::is_member_pointer<T>::value>::type>243// Only accept types for which we can find a streaming operator via244// ADL (possibly involving implicit conversions).245// (Use SFINAE via return type, because it seems GCC < 12 doesn't handle name246// lookup properly when we do it in the template parameter list.)247static auto PrintValue(const T& value,248::std::ostream* os) -> decltype((void)(*os << value)) {249// Call streaming operator found by ADL, possibly with implicit conversions250// of the arguments.251*os << value;252}253};254255} // namespace internal_stream_operator_without_lexical_name_lookup256257struct ProtobufPrinter {258// We print a protobuf using its ShortDebugString() when the string259// doesn't exceed this many characters; otherwise we print it using260// DebugString() for better readability.261static const size_t kProtobufOneLinerMaxLength = 50;262263template <typename T,264typename = typename std::enable_if<265internal::HasDebugStringAndShortDebugString<T>::value>::type>266static void PrintValue(const T& value, ::std::ostream* os) {267std::string pretty_str = value.ShortDebugString();268if (pretty_str.length() > kProtobufOneLinerMaxLength) {269pretty_str = "\n" + value.DebugString();270}271*os << ("<" + pretty_str + ">");272}273};274275struct ConvertibleToIntegerPrinter {276// Since T has no << operator or PrintTo() but can be implicitly277// converted to BiggestInt, we print it as a BiggestInt.278//279// Most likely T is an enum type (either named or unnamed), in which280// case printing it as an integer is the desired behavior. In case281// T is not an enum, printing it as an integer is the best we can do282// given that it has no user-defined printer.283static void PrintValue(internal::BiggestInt value, ::std::ostream* os) {284*os << value;285}286};287288struct ConvertibleToStringViewPrinter {289#if GTEST_INTERNAL_HAS_STRING_VIEW290static void PrintValue(internal::StringView value, ::std::ostream* os) {291internal::UniversalPrint(value, os);292}293#endif294};295296#ifdef GTEST_HAS_ABSL297struct ConvertibleToAbslStringifyPrinter {298template <typename T,299typename = typename std::enable_if<300absl::HasAbslStringify<T>::value>::type> // NOLINT301static void PrintValue(const T& value, ::std::ostream* os) {302*os << absl::StrCat(value);303}304};305#endif // GTEST_HAS_ABSL306307// Prints the given number of bytes in the given object to the given308// ostream.309GTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes,310size_t count, ::std::ostream* os);311struct RawBytesPrinter {312// SFINAE on `sizeof` to make sure we have a complete type.313template <typename T, size_t = sizeof(T)>314static void PrintValue(const T& value, ::std::ostream* os) {315PrintBytesInObjectTo(316static_cast<const unsigned char*>(317// Load bearing cast to void* to support iOS318reinterpret_cast<const void*>(std::addressof(value))),319sizeof(value), os);320}321};322323struct FallbackPrinter {324template <typename T>325static void PrintValue(const T&, ::std::ostream* os) {326*os << "(incomplete type)";327}328};329330// Try every printer in order and return the first one that works.331template <typename T, typename E, typename Printer, typename... Printers>332struct FindFirstPrinter : FindFirstPrinter<T, E, Printers...> {};333334template <typename T, typename Printer, typename... Printers>335struct FindFirstPrinter<336T, decltype(Printer::PrintValue(std::declval<const T&>(), nullptr)),337Printer, Printers...> {338using type = Printer;339};340341// Select the best printer in the following order:342// - Print containers (they have begin/end/etc).343// - Print function pointers.344// - Print object pointers.345// - Print protocol buffers.346// - Use the stream operator, if available.347// - Print types convertible to BiggestInt.348// - Print types convertible to StringView, if available.349// - Fallback to printing the raw bytes of the object.350template <typename T>351void PrintWithFallback(const T& value, ::std::ostream* os) {352using Printer = typename FindFirstPrinter<353T, void, ContainerPrinter, FunctionPointerPrinter, PointerPrinter,354ProtobufPrinter,355#ifdef GTEST_HAS_ABSL356ConvertibleToAbslStringifyPrinter,357#endif // GTEST_HAS_ABSL358internal_stream_operator_without_lexical_name_lookup::StreamPrinter,359ConvertibleToIntegerPrinter, ConvertibleToStringViewPrinter,360RawBytesPrinter, FallbackPrinter>::type;361Printer::PrintValue(value, os);362}363364// FormatForComparison<ToPrint, OtherOperand>::Format(value) formats a365// value of type ToPrint that is an operand of a comparison assertion366// (e.g. ASSERT_EQ). OtherOperand is the type of the other operand in367// the comparison, and is used to help determine the best way to368// format the value. In particular, when the value is a C string369// (char pointer) and the other operand is an STL string object, we370// want to format the C string as a string, since we know it is371// compared by value with the string object. If the value is a char372// pointer but the other operand is not an STL string object, we don't373// know whether the pointer is supposed to point to a NUL-terminated374// string, and thus want to print it as a pointer to be safe.375//376// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.377378// The default case.379template <typename ToPrint, typename OtherOperand>380class FormatForComparison {381public:382static ::std::string Format(const ToPrint& value) {383return ::testing::PrintToString(value);384}385};386387// Array.388template <typename ToPrint, size_t N, typename OtherOperand>389class FormatForComparison<ToPrint[N], OtherOperand> {390public:391static ::std::string Format(const ToPrint* value) {392return FormatForComparison<const ToPrint*, OtherOperand>::Format(value);393}394};395396// By default, print C string as pointers to be safe, as we don't know397// whether they actually point to a NUL-terminated string.398399#define GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(CharType) \400template <typename OtherOperand> \401class FormatForComparison<CharType*, OtherOperand> { \402public: \403static ::std::string Format(CharType* value) { \404return ::testing::PrintToString(static_cast<const void*>(value)); \405} \406}407408GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char);409GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char);410GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(wchar_t);411GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const wchar_t);412#ifdef __cpp_lib_char8_t413GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char8_t);414GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char8_t);415#endif416GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char16_t);417GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char16_t);418GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char32_t);419GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char32_t);420421#undef GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_422423// If a C string is compared with an STL string object, we know it's meant424// to point to a NUL-terminated string, and thus can print it as a string.425426#define GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(CharType, OtherStringType) \427template <> \428class FormatForComparison<CharType*, OtherStringType> { \429public: \430static ::std::string Format(CharType* value) { \431return ::testing::PrintToString(value); \432} \433}434435GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::std::string);436GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char, ::std::string);437#ifdef __cpp_lib_char8_t438GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char8_t, ::std::u8string);439GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char8_t, ::std::u8string);440#endif441GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char16_t, ::std::u16string);442GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char16_t, ::std::u16string);443GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char32_t, ::std::u32string);444GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char32_t, ::std::u32string);445446#if GTEST_HAS_STD_WSTRING447GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(wchar_t, ::std::wstring);448GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const wchar_t, ::std::wstring);449#endif450451#undef GTEST_IMPL_FORMAT_C_STRING_AS_STRING_452453// Formats a comparison assertion (e.g. ASSERT_EQ, EXPECT_LT, and etc)454// operand to be used in a failure message. The type (but not value)455// of the other operand may affect the format. This allows us to456// print a char* as a raw pointer when it is compared against another457// char* or void*, and print it as a C string when it is compared458// against an std::string object, for example.459//460// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.461template <typename T1, typename T2>462std::string FormatForComparisonFailureMessage(const T1& value,463const T2& /* other_operand */) {464return FormatForComparison<T1, T2>::Format(value);465}466467// UniversalPrinter<T>::Print(value, ostream_ptr) prints the given468// value to the given ostream. The caller must ensure that469// 'ostream_ptr' is not NULL, or the behavior is undefined.470//471// We define UniversalPrinter as a class template (as opposed to a472// function template), as we need to partially specialize it for473// reference types, which cannot be done with function templates.474template <typename T>475class UniversalPrinter;476477// Prints the given value using the << operator if it has one;478// otherwise prints the bytes in it. This is what479// UniversalPrinter<T>::Print() does when PrintTo() is not specialized480// or overloaded for type T.481//482// A user can override this behavior for a class type Foo by defining483// an overload of PrintTo() in the namespace where Foo is defined. We484// give the user this option as sometimes defining a << operator for485// Foo is not desirable (e.g. the coding style may prevent doing it,486// or there is already a << operator but it doesn't do what the user487// wants).488template <typename T>489void PrintTo(const T& value, ::std::ostream* os) {490internal::PrintWithFallback(value, os);491}492493// The following list of PrintTo() overloads tells494// UniversalPrinter<T>::Print() how to print standard types (built-in495// types, strings, plain arrays, and pointers).496497// Overloads for various char types.498GTEST_API_ void PrintTo(unsigned char c, ::std::ostream* os);499GTEST_API_ void PrintTo(signed char c, ::std::ostream* os);500inline void PrintTo(char c, ::std::ostream* os) {501// When printing a plain char, we always treat it as unsigned. This502// way, the output won't be affected by whether the compiler thinks503// char is signed or not.504PrintTo(static_cast<unsigned char>(c), os);505}506507// Overloads for other simple built-in types.508inline void PrintTo(bool x, ::std::ostream* os) {509*os << (x ? "true" : "false");510}511512// Overload for wchar_t type.513// Prints a wchar_t as a symbol if it is printable or as its internal514// code otherwise and also as its decimal code (except for L'\0').515// The L'\0' char is printed as "L'\\0'". The decimal code is printed516// as signed integer when wchar_t is implemented by the compiler517// as a signed type and is printed as an unsigned integer when wchar_t518// is implemented as an unsigned type.519GTEST_API_ void PrintTo(wchar_t wc, ::std::ostream* os);520521GTEST_API_ void PrintTo(char32_t c, ::std::ostream* os);522inline void PrintTo(char16_t c, ::std::ostream* os) {523PrintTo(ImplicitCast_<char32_t>(c), os);524}525#ifdef __cpp_lib_char8_t526inline void PrintTo(char8_t c, ::std::ostream* os) {527PrintTo(ImplicitCast_<char32_t>(c), os);528}529#endif530531// gcc/clang __{u,}int128_t532#if defined(__SIZEOF_INT128__)533GTEST_API_ void PrintTo(__uint128_t v, ::std::ostream* os);534GTEST_API_ void PrintTo(__int128_t v, ::std::ostream* os);535#endif // __SIZEOF_INT128__536537// The default resolution used to print floating-point values uses only538// 6 digits, which can be confusing if a test compares two values whose539// difference lies in the 7th digit. So we'd like to print out numbers540// in full precision.541// However if the value is something simple like 1.1, full will print a542// long string like 1.100000001 due to floating-point numbers not using543// a base of 10. This routiune returns an appropriate resolution for a544// given floating-point number, that is, 6 if it will be accurate, or a545// max_digits10 value (full precision) if it won't, for values between546// 0.0001 and one million.547// It does this by computing what those digits would be (by multiplying548// by an appropriate power of 10), then dividing by that power again to549// see if gets the original value back.550// A similar algorithm applies for values larger than one million; note551// that for those values, we must divide to get a six-digit number, and552// then multiply to possibly get the original value again.553template <typename FloatType>554int AppropriateResolution(FloatType val) {555int full = std::numeric_limits<FloatType>::max_digits10;556if (val < 0) val = -val;557558#ifdef __GNUC__559#pragma GCC diagnostic push560#pragma GCC diagnostic ignored "-Wfloat-equal"561#endif562if (val < 1000000) {563FloatType mulfor6 = 1e10;564// Without these static casts, the template instantiation for float would565// fail to compile when -Wdouble-promotion is enabled, as the arithmetic and566// comparison logic would promote floats to doubles.567if (val >= static_cast<FloatType>(100000.0)) { // 100,000 to 999,999568mulfor6 = 1.0;569} else if (val >= static_cast<FloatType>(10000.0)) {570mulfor6 = 1e1;571} else if (val >= static_cast<FloatType>(1000.0)) {572mulfor6 = 1e2;573} else if (val >= static_cast<FloatType>(100.0)) {574mulfor6 = 1e3;575} else if (val >= static_cast<FloatType>(10.0)) {576mulfor6 = 1e4;577} else if (val >= static_cast<FloatType>(1.0)) {578mulfor6 = 1e5;579} else if (val >= static_cast<FloatType>(0.1)) {580mulfor6 = 1e6;581} else if (val >= static_cast<FloatType>(0.01)) {582mulfor6 = 1e7;583} else if (val >= static_cast<FloatType>(0.001)) {584mulfor6 = 1e8;585} else if (val >= static_cast<FloatType>(0.0001)) {586mulfor6 = 1e9;587}588if (static_cast<FloatType>(static_cast<int32_t>(589val * mulfor6 + (static_cast<FloatType>(0.5)))) /590mulfor6 ==591val)592return 6;593} else if (val < static_cast<FloatType>(1e10)) {594FloatType divfor6 = static_cast<FloatType>(1.0);595if (val >= static_cast<FloatType>(1e9)) { // 1,000,000,000 to 9,999,999,999596divfor6 = 10000;597} else if (val >=598static_cast<FloatType>(1e8)) { // 100,000,000 to 999,999,999599divfor6 = 1000;600} else if (val >=601static_cast<FloatType>(1e7)) { // 10,000,000 to 99,999,999602divfor6 = 100;603} else if (val >= static_cast<FloatType>(1e6)) { // 1,000,000 to 9,999,999604divfor6 = 10;605}606if (static_cast<FloatType>(static_cast<int32_t>(607val / divfor6 + (static_cast<FloatType>(0.5)))) *608divfor6 ==609val)610return 6;611}612#ifdef __GNUC__613#pragma GCC diagnostic pop614#endif615return full;616}617618inline void PrintTo(float f, ::std::ostream* os) {619auto old_precision = os->precision();620os->precision(AppropriateResolution(f));621*os << f;622os->precision(old_precision);623}624625inline void PrintTo(double d, ::std::ostream* os) {626auto old_precision = os->precision();627os->precision(AppropriateResolution(d));628*os << d;629os->precision(old_precision);630}631632// Overloads for C strings.633GTEST_API_ void PrintTo(const char* s, ::std::ostream* os);634inline void PrintTo(char* s, ::std::ostream* os) {635PrintTo(ImplicitCast_<const char*>(s), os);636}637638// signed/unsigned char is often used for representing binary data, so639// we print pointers to it as void* to be safe.640inline void PrintTo(const signed char* s, ::std::ostream* os) {641PrintTo(ImplicitCast_<const void*>(s), os);642}643inline void PrintTo(signed char* s, ::std::ostream* os) {644PrintTo(ImplicitCast_<const void*>(s), os);645}646inline void PrintTo(const unsigned char* s, ::std::ostream* os) {647PrintTo(ImplicitCast_<const void*>(s), os);648}649inline void PrintTo(unsigned char* s, ::std::ostream* os) {650PrintTo(ImplicitCast_<const void*>(s), os);651}652#ifdef __cpp_lib_char8_t653// Overloads for u8 strings.654GTEST_API_ void PrintTo(const char8_t* s, ::std::ostream* os);655inline void PrintTo(char8_t* s, ::std::ostream* os) {656PrintTo(ImplicitCast_<const char8_t*>(s), os);657}658#endif659// Overloads for u16 strings.660GTEST_API_ void PrintTo(const char16_t* s, ::std::ostream* os);661inline void PrintTo(char16_t* s, ::std::ostream* os) {662PrintTo(ImplicitCast_<const char16_t*>(s), os);663}664// Overloads for u32 strings.665GTEST_API_ void PrintTo(const char32_t* s, ::std::ostream* os);666inline void PrintTo(char32_t* s, ::std::ostream* os) {667PrintTo(ImplicitCast_<const char32_t*>(s), os);668}669670// MSVC can be configured to define wchar_t as a typedef of unsigned671// short. It defines _NATIVE_WCHAR_T_DEFINED when wchar_t is a native672// type. When wchar_t is a typedef, defining an overload for const673// wchar_t* would cause unsigned short* be printed as a wide string,674// possibly causing invalid memory accesses.675#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)676// Overloads for wide C strings677GTEST_API_ void PrintTo(const wchar_t* s, ::std::ostream* os);678inline void PrintTo(wchar_t* s, ::std::ostream* os) {679PrintTo(ImplicitCast_<const wchar_t*>(s), os);680}681#endif682683// Overload for C arrays. Multi-dimensional arrays are printed684// properly.685686// Prints the given number of elements in an array, without printing687// the curly braces.688template <typename T>689void PrintRawArrayTo(const T a[], size_t count, ::std::ostream* os) {690UniversalPrint(a[0], os);691for (size_t i = 1; i != count; i++) {692*os << ", ";693UniversalPrint(a[i], os);694}695}696697// Overloads for ::std::string.698GTEST_API_ void PrintStringTo(const ::std::string& s, ::std::ostream* os);699inline void PrintTo(const ::std::string& s, ::std::ostream* os) {700PrintStringTo(s, os);701}702703// Overloads for ::std::u8string704#ifdef __cpp_lib_char8_t705GTEST_API_ void PrintU8StringTo(const ::std::u8string& s, ::std::ostream* os);706inline void PrintTo(const ::std::u8string& s, ::std::ostream* os) {707PrintU8StringTo(s, os);708}709#endif710711// Overloads for ::std::u16string712GTEST_API_ void PrintU16StringTo(const ::std::u16string& s, ::std::ostream* os);713inline void PrintTo(const ::std::u16string& s, ::std::ostream* os) {714PrintU16StringTo(s, os);715}716717// Overloads for ::std::u32string718GTEST_API_ void PrintU32StringTo(const ::std::u32string& s, ::std::ostream* os);719inline void PrintTo(const ::std::u32string& s, ::std::ostream* os) {720PrintU32StringTo(s, os);721}722723// Overloads for ::std::wstring.724#if GTEST_HAS_STD_WSTRING725GTEST_API_ void PrintWideStringTo(const ::std::wstring& s, ::std::ostream* os);726inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) {727PrintWideStringTo(s, os);728}729#endif // GTEST_HAS_STD_WSTRING730731#if GTEST_INTERNAL_HAS_STRING_VIEW732// Overload for internal::StringView.733inline void PrintTo(internal::StringView sp, ::std::ostream* os) {734PrintTo(::std::string(sp), os);735}736#endif // GTEST_INTERNAL_HAS_STRING_VIEW737738inline void PrintTo(std::nullptr_t, ::std::ostream* os) { *os << "(nullptr)"; }739740#if GTEST_HAS_RTTI741inline void PrintTo(const std::type_info& info, std::ostream* os) {742*os << internal::GetTypeName(info);743}744#endif // GTEST_HAS_RTTI745746template <typename T>747void PrintTo(std::reference_wrapper<T> ref, ::std::ostream* os) {748UniversalPrinter<T&>::Print(ref.get(), os);749}750751inline const void* VoidifyPointer(const void* p) { return p; }752inline const void* VoidifyPointer(volatile const void* p) {753return const_cast<const void*>(p);754}755756template <typename T, typename Ptr>757void PrintSmartPointer(const Ptr& ptr, std::ostream* os, char) {758if (ptr == nullptr) {759*os << "(nullptr)";760} else {761// We can't print the value. Just print the pointer..762*os << "(" << (VoidifyPointer)(ptr.get()) << ")";763}764}765template <typename T, typename Ptr,766typename = typename std::enable_if<!std::is_void<T>::value &&767!std::is_array<T>::value>::type>768void PrintSmartPointer(const Ptr& ptr, std::ostream* os, int) {769if (ptr == nullptr) {770*os << "(nullptr)";771} else {772*os << "(ptr = " << (VoidifyPointer)(ptr.get()) << ", value = ";773UniversalPrinter<T>::Print(*ptr, os);774*os << ")";775}776}777778template <typename T, typename D>779void PrintTo(const std::unique_ptr<T, D>& ptr, std::ostream* os) {780(PrintSmartPointer<T>)(ptr, os, 0);781}782783template <typename T>784void PrintTo(const std::shared_ptr<T>& ptr, std::ostream* os) {785(PrintSmartPointer<T>)(ptr, os, 0);786}787788#if GTEST_INTERNAL_HAS_COMPARE_LIB789template <typename T>790void PrintOrderingHelper(T ordering, std::ostream* os) {791if (ordering == T::less) {792*os << "(less)";793} else if (ordering == T::greater) {794*os << "(greater)";795} else if (ordering == T::equivalent) {796*os << "(equivalent)";797} else {798*os << "(unknown ordering)";799}800}801802inline void PrintTo(std::strong_ordering ordering, std::ostream* os) {803if (ordering == std::strong_ordering::equal) {804*os << "(equal)";805} else {806PrintOrderingHelper(ordering, os);807}808}809810inline void PrintTo(std::partial_ordering ordering, std::ostream* os) {811if (ordering == std::partial_ordering::unordered) {812*os << "(unordered)";813} else {814PrintOrderingHelper(ordering, os);815}816}817818inline void PrintTo(std::weak_ordering ordering, std::ostream* os) {819PrintOrderingHelper(ordering, os);820}821#endif822823// Helper function for printing a tuple. T must be instantiated with824// a tuple type.825template <typename T>826void PrintTupleTo(const T&, std::integral_constant<size_t, 0>,827::std::ostream*) {}828829template <typename T, size_t I>830void PrintTupleTo(const T& t, std::integral_constant<size_t, I>,831::std::ostream* os) {832PrintTupleTo(t, std::integral_constant<size_t, I - 1>(), os);833GTEST_INTENTIONAL_CONST_COND_PUSH_()834if (I > 1) {835GTEST_INTENTIONAL_CONST_COND_POP_()836*os << ", ";837}838UniversalPrinter<typename std::tuple_element<I - 1, T>::type>::Print(839std::get<I - 1>(t), os);840}841842template <typename... Types>843void PrintTo(const ::std::tuple<Types...>& t, ::std::ostream* os) {844*os << "(";845PrintTupleTo(t, std::integral_constant<size_t, sizeof...(Types)>(), os);846*os << ")";847}848849// Overload for std::pair.850template <typename T1, typename T2>851void PrintTo(const ::std::pair<T1, T2>& value, ::std::ostream* os) {852*os << '(';853// We cannot use UniversalPrint(value.first, os) here, as T1 may be854// a reference type. The same for printing value.second.855UniversalPrinter<T1>::Print(value.first, os);856*os << ", ";857UniversalPrinter<T2>::Print(value.second, os);858*os << ')';859}860861// Implements printing a non-reference type T by letting the compiler862// pick the right overload of PrintTo() for T.863template <typename T>864class UniversalPrinter {865public:866// MSVC warns about adding const to a function type, so we want to867// disable the warning.868GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180)869870// Note: we deliberately don't call this PrintTo(), as that name871// conflicts with ::testing::internal::PrintTo in the body of the872// function.873static void Print(const T& value, ::std::ostream* os) {874// By default, ::testing::internal::PrintTo() is used for printing875// the value.876//877// Thanks to Koenig look-up, if T is a class and has its own878// PrintTo() function defined in its namespace, that function will879// be visible here. Since it is more specific than the generic ones880// in ::testing::internal, it will be picked by the compiler in the881// following statement - exactly what we want.882PrintTo(value, os);883}884885GTEST_DISABLE_MSC_WARNINGS_POP_()886};887888// Remove any const-qualifiers before passing a type to UniversalPrinter.889template <typename T>890class UniversalPrinter<const T> : public UniversalPrinter<T> {};891892#if GTEST_INTERNAL_HAS_ANY893894// Printer for std::any / absl::any895896template <>897class UniversalPrinter<Any> {898public:899static void Print(const Any& value, ::std::ostream* os) {900if (value.has_value()) {901*os << "value of type " << GetTypeName(value);902} else {903*os << "no value";904}905}906907private:908static std::string GetTypeName(const Any& value) {909#if GTEST_HAS_RTTI910return internal::GetTypeName(value.type());911#else912static_cast<void>(value); // possibly unused913return "<unknown_type>";914#endif // GTEST_HAS_RTTI915}916};917918#endif // GTEST_INTERNAL_HAS_ANY919920#if GTEST_INTERNAL_HAS_OPTIONAL921922// Printer for std::optional / absl::optional923924template <typename T>925class UniversalPrinter<Optional<T>> {926public:927static void Print(const Optional<T>& value, ::std::ostream* os) {928*os << '(';929if (!value) {930*os << "nullopt";931} else {932UniversalPrint(*value, os);933}934*os << ')';935}936};937938template <>939class UniversalPrinter<decltype(Nullopt())> {940public:941static void Print(decltype(Nullopt()), ::std::ostream* os) {942*os << "(nullopt)";943}944};945946#endif // GTEST_INTERNAL_HAS_OPTIONAL947948#if GTEST_INTERNAL_HAS_VARIANT949950// Printer for std::variant / absl::variant951952template <typename... T>953class UniversalPrinter<Variant<T...>> {954public:955static void Print(const Variant<T...>& value, ::std::ostream* os) {956*os << '(';957#ifdef GTEST_HAS_ABSL958absl::visit(Visitor{os, value.index()}, value);959#else960std::visit(Visitor{os, value.index()}, value);961#endif // GTEST_HAS_ABSL962*os << ')';963}964965private:966struct Visitor {967template <typename U>968void operator()(const U& u) const {969*os << "'" << GetTypeName<U>() << "(index = " << index970<< ")' with value ";971UniversalPrint(u, os);972}973::std::ostream* os;974std::size_t index;975};976};977978#endif // GTEST_INTERNAL_HAS_VARIANT979980// UniversalPrintArray(begin, len, os) prints an array of 'len'981// elements, starting at address 'begin'.982template <typename T>983void UniversalPrintArray(const T* begin, size_t len, ::std::ostream* os) {984if (len == 0) {985*os << "{}";986} else {987*os << "{ ";988const size_t kThreshold = 18;989const size_t kChunkSize = 8;990// If the array has more than kThreshold elements, we'll have to991// omit some details by printing only the first and the last992// kChunkSize elements.993if (len <= kThreshold) {994PrintRawArrayTo(begin, len, os);995} else {996PrintRawArrayTo(begin, kChunkSize, os);997*os << ", ..., ";998PrintRawArrayTo(begin + len - kChunkSize, kChunkSize, os);999}1000*os << " }";1001}1002}1003// This overload prints a (const) char array compactly.1004GTEST_API_ void UniversalPrintArray(const char* begin, size_t len,1005::std::ostream* os);10061007#ifdef __cpp_lib_char8_t1008// This overload prints a (const) char8_t array compactly.1009GTEST_API_ void UniversalPrintArray(const char8_t* begin, size_t len,1010::std::ostream* os);1011#endif10121013// This overload prints a (const) char16_t array compactly.1014GTEST_API_ void UniversalPrintArray(const char16_t* begin, size_t len,1015::std::ostream* os);10161017// This overload prints a (const) char32_t array compactly.1018GTEST_API_ void UniversalPrintArray(const char32_t* begin, size_t len,1019::std::ostream* os);10201021// This overload prints a (const) wchar_t array compactly.1022GTEST_API_ void UniversalPrintArray(const wchar_t* begin, size_t len,1023::std::ostream* os);10241025// Implements printing an array type T[N].1026template <typename T, size_t N>1027class UniversalPrinter<T[N]> {1028public:1029// Prints the given array, omitting some elements when there are too1030// many.1031static void Print(const T (&a)[N], ::std::ostream* os) {1032UniversalPrintArray(a, N, os);1033}1034};10351036// Implements printing a reference type T&.1037template <typename T>1038class UniversalPrinter<T&> {1039public:1040// MSVC warns about adding const to a function type, so we want to1041// disable the warning.1042GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180)10431044static void Print(const T& value, ::std::ostream* os) {1045// Prints the address of the value. We use reinterpret_cast here1046// as static_cast doesn't compile when T is a function type.1047*os << "@" << reinterpret_cast<const void*>(&value) << " ";10481049// Then prints the value itself.1050UniversalPrint(value, os);1051}10521053GTEST_DISABLE_MSC_WARNINGS_POP_()1054};10551056// Prints a value tersely: for a reference type, the referenced value1057// (but not the address) is printed; for a (const) char pointer, the1058// NUL-terminated string (but not the pointer) is printed.10591060template <typename T>1061class UniversalTersePrinter {1062public:1063static void Print(const T& value, ::std::ostream* os) {1064UniversalPrint(value, os);1065}1066};1067template <typename T>1068class UniversalTersePrinter<T&> {1069public:1070static void Print(const T& value, ::std::ostream* os) {1071UniversalPrint(value, os);1072}1073};1074template <typename T>1075class UniversalTersePrinter<std::reference_wrapper<T>> {1076public:1077static void Print(std::reference_wrapper<T> value, ::std::ostream* os) {1078UniversalTersePrinter<T>::Print(value.get(), os);1079}1080};1081template <typename T, size_t N>1082class UniversalTersePrinter<T[N]> {1083public:1084static void Print(const T (&value)[N], ::std::ostream* os) {1085UniversalPrinter<T[N]>::Print(value, os);1086}1087};1088template <>1089class UniversalTersePrinter<const char*> {1090public:1091static void Print(const char* str, ::std::ostream* os) {1092if (str == nullptr) {1093*os << "NULL";1094} else {1095UniversalPrint(std::string(str), os);1096}1097}1098};1099template <>1100class UniversalTersePrinter<char*> : public UniversalTersePrinter<const char*> {1101};11021103#ifdef __cpp_lib_char8_t1104template <>1105class UniversalTersePrinter<const char8_t*> {1106public:1107static void Print(const char8_t* str, ::std::ostream* os) {1108if (str == nullptr) {1109*os << "NULL";1110} else {1111UniversalPrint(::std::u8string(str), os);1112}1113}1114};1115template <>1116class UniversalTersePrinter<char8_t*>1117: public UniversalTersePrinter<const char8_t*> {};1118#endif11191120template <>1121class UniversalTersePrinter<const char16_t*> {1122public:1123static void Print(const char16_t* str, ::std::ostream* os) {1124if (str == nullptr) {1125*os << "NULL";1126} else {1127UniversalPrint(::std::u16string(str), os);1128}1129}1130};1131template <>1132class UniversalTersePrinter<char16_t*>1133: public UniversalTersePrinter<const char16_t*> {};11341135template <>1136class UniversalTersePrinter<const char32_t*> {1137public:1138static void Print(const char32_t* str, ::std::ostream* os) {1139if (str == nullptr) {1140*os << "NULL";1141} else {1142UniversalPrint(::std::u32string(str), os);1143}1144}1145};1146template <>1147class UniversalTersePrinter<char32_t*>1148: public UniversalTersePrinter<const char32_t*> {};11491150#if GTEST_HAS_STD_WSTRING1151template <>1152class UniversalTersePrinter<const wchar_t*> {1153public:1154static void Print(const wchar_t* str, ::std::ostream* os) {1155if (str == nullptr) {1156*os << "NULL";1157} else {1158UniversalPrint(::std::wstring(str), os);1159}1160}1161};1162#endif11631164template <>1165class UniversalTersePrinter<wchar_t*> {1166public:1167static void Print(wchar_t* str, ::std::ostream* os) {1168UniversalTersePrinter<const wchar_t*>::Print(str, os);1169}1170};11711172template <typename T>1173void UniversalTersePrint(const T& value, ::std::ostream* os) {1174UniversalTersePrinter<T>::Print(value, os);1175}11761177// Prints a value using the type inferred by the compiler. The1178// difference between this and UniversalTersePrint() is that for a1179// (const) char pointer, this prints both the pointer and the1180// NUL-terminated string.1181template <typename T>1182void UniversalPrint(const T& value, ::std::ostream* os) {1183// A workarond for the bug in VC++ 7.1 that prevents us from instantiating1184// UniversalPrinter with T directly.1185typedef T T1;1186UniversalPrinter<T1>::Print(value, os);1187}11881189typedef ::std::vector<::std::string> Strings;11901191// Tersely prints the first N fields of a tuple to a string vector,1192// one element for each field.1193template <typename Tuple>1194void TersePrintPrefixToStrings(const Tuple&, std::integral_constant<size_t, 0>,1195Strings*) {}1196template <typename Tuple, size_t I>1197void TersePrintPrefixToStrings(const Tuple& t,1198std::integral_constant<size_t, I>,1199Strings* strings) {1200TersePrintPrefixToStrings(t, std::integral_constant<size_t, I - 1>(),1201strings);1202::std::stringstream ss;1203UniversalTersePrint(std::get<I - 1>(t), &ss);1204strings->push_back(ss.str());1205}12061207// Prints the fields of a tuple tersely to a string vector, one1208// element for each field. See the comment before1209// UniversalTersePrint() for how we define "tersely".1210template <typename Tuple>1211Strings UniversalTersePrintTupleFieldsToStrings(const Tuple& value) {1212Strings result;1213TersePrintPrefixToStrings(1214value, std::integral_constant<size_t, std::tuple_size<Tuple>::value>(),1215&result);1216return result;1217}12181219} // namespace internal12201221template <typename T>1222::std::string PrintToString(const T& value) {1223::std::stringstream ss;1224internal::UniversalTersePrinter<T>::Print(value, &ss);1225return ss.str();1226}12271228} // namespace testing12291230// Include any custom printer added by the local installation.1231// We must include this header at the end to make sure it can use the1232// declarations from this file.1233#include "gtest/internal/custom/gtest-printers.h"12341235#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_123612371238