brintos

brintos / llvm-project-archived public Read only

0
0
Text · 40.3 KiB · 409b135 Raw
1181 lines · c
1// Copyright 2007, Google Inc.2// All rights reserved.3//4// Redistribution and use in source and binary forms, with or without5// modification, are permitted provided that the following conditions are6// met:7//8//     * Redistributions of source code must retain the above copyright9// notice, this list of conditions and the following disclaimer.10//     * Redistributions in binary form must reproduce the above11// copyright notice, this list of conditions and the following disclaimer12// in the documentation and/or other materials provided with the13// distribution.14//     * Neither the name of Google Inc. nor the names of its15// contributors may be used to endorse or promote products derived from16// this software without specific prior written permission.17//18// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS19// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT20// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR21// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT22// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,23// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT24// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,25// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY26// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT27// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE28// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.29 30// Google Test - The Google C++ Testing and Mocking Framework31//32// This file implements a universal value printer that can print a33// value of any type T:34//35//   void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);36//37// A user can teach this function how to print a class type T by38// defining either operator<<() or PrintTo() in the namespace that39// defines T.  More specifically, the FIRST defined function in the40// following list will be used (assuming T is defined in namespace41// foo):42//43//   1. foo::PrintTo(const T&, ostream*)44//   2. operator<<(ostream&, const T&) defined in either foo or the45//      global namespace.46// * Prefer AbslStringify(..) to operator<<(..), per https://abseil.io/tips/215.47// * Define foo::PrintTo(..) if the type already has AbslStringify(..), but an48//   alternative presentation in test results is of interest.49//50// However if T is an STL-style container then it is printed element-wise51// unless foo::PrintTo(const T&, ostream*) is defined. Note that52// operator<<() is ignored for container types.53//54// If none of the above is defined, it will print the debug string of55// the value if it is a protocol buffer, or print the raw bytes in the56// value otherwise.57//58// To aid debugging: when T is a reference type, the address of the59// value is also printed; when T is a (const) char pointer, both the60// pointer value and the NUL-terminated string it points to are61// printed.62//63// We also provide some convenient wrappers:64//65//   // Prints a value to a string.  For a (const or not) char66//   // pointer, the NUL-terminated string (but not the pointer) is67//   // printed.68//   std::string ::testing::PrintToString(const T& value);69//70//   // Prints a value tersely: for a reference type, the referenced71//   // value (but not the address) is printed; for a (const or not) char72//   // pointer, the NUL-terminated string (but not the pointer) is73//   // printed.74//   void ::testing::internal::UniversalTersePrint(const T& value, ostream*);75//76//   // Prints value using the type inferred by the compiler.  The difference77//   // from UniversalTersePrint() is that this function prints both the78//   // pointer and the NUL-terminated string for a (const or not) char pointer.79//   void ::testing::internal::UniversalPrint(const T& value, ostream*);80//81//   // Prints the fields of a tuple tersely to a string vector, one82//   // element for each field. Tuple support must be enabled in83//   // gtest-port.h.84//   std::vector<string> UniversalTersePrintTupleFieldsToStrings(85//       const Tuple& value);86//87// Known limitation:88//89// The print primitives print the elements of an STL-style container90// using the compiler-inferred type of *iter where iter is a91// const_iterator of the container.  When const_iterator is an input92// iterator but not a forward iterator, this inferred type may not93// match value_type, and the print output may be incorrect.  In94// practice, this is rarely a problem as for most containers95// const_iterator is a forward iterator.  We'll fix this if there's an96// actual need for it.  Note that this fix cannot rely on value_type97// being defined as many user-defined container types don't have98// value_type.99 100// IWYU pragma: private, include "gtest/gtest.h"101// IWYU pragma: friend gtest/.*102// IWYU pragma: friend gmock/.*103 104#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_105#define GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_106 107#include <functional>108#include <memory>109#include <ostream>  // NOLINT110#include <sstream>111#include <string>112#include <tuple>113#include <type_traits>114#include <typeinfo>115#include <utility>116#include <vector>117 118#ifdef GTEST_HAS_ABSL119#include "absl/strings/internal/has_absl_stringify.h"120#include "absl/strings/str_cat.h"121#endif  // GTEST_HAS_ABSL122#include "gtest/internal/gtest-internal.h"123#include "gtest/internal/gtest-port.h"124 125namespace testing {126 127// Definitions in the internal* namespaces are subject to change without notice.128// DO NOT USE THEM IN USER CODE!129namespace internal {130 131template <typename T>132void UniversalPrint(const T& value, ::std::ostream* os);133 134// Used to print an STL-style container when the user doesn't define135// a PrintTo() for it.136struct ContainerPrinter {137  template <typename T,138            typename = typename std::enable_if<139                (sizeof(IsContainerTest<T>(0)) == sizeof(IsContainer)) &&140                !IsRecursiveContainer<T>::value>::type>141  static void PrintValue(const T& container, std::ostream* os) {142    const size_t kMaxCount = 32;  // The maximum number of elements to print.143    *os << '{';144    size_t count = 0;145    for (auto&& elem : container) {146      if (count > 0) {147        *os << ',';148        if (count == kMaxCount) {  // Enough has been printed.149          *os << " ...";150          break;151        }152      }153      *os << ' ';154      // We cannot call PrintTo(elem, os) here as PrintTo() doesn't155      // handle `elem` being a native array.156      internal::UniversalPrint(elem, os);157      ++count;158    }159 160    if (count > 0) {161      *os << ' ';162    }163    *os << '}';164  }165};166 167// Used to print a pointer that is neither a char pointer nor a member168// pointer, when the user doesn't define PrintTo() for it.  (A member169// variable pointer or member function pointer doesn't really point to170// a location in the address space.  Their representation is171// implementation-defined.  Therefore they will be printed as raw172// bytes.)173struct FunctionPointerPrinter {174  template <typename T, typename = typename std::enable_if<175                            std::is_function<T>::value>::type>176  static void PrintValue(T* p, ::std::ostream* os) {177    if (p == nullptr) {178      *os << "NULL";179    } else {180      // T is a function type, so '*os << p' doesn't do what we want181      // (it just prints p as bool).  We want to print p as a const182      // void*.183      *os << reinterpret_cast<const void*>(p);184    }185  }186};187 188struct PointerPrinter {189  template <typename T>190  static void PrintValue(T* p, ::std::ostream* os) {191    if (p == nullptr) {192      *os << "NULL";193    } else {194      // T is not a function type.  We just call << to print p,195      // relying on ADL to pick up user-defined << for their pointer196      // types, if any.197      *os << p;198    }199  }200};201 202namespace internal_stream_operator_without_lexical_name_lookup {203 204// The presence of an operator<< here will terminate lexical scope lookup205// straight away (even though it cannot be a match because of its argument206// types). Thus, the two operator<< calls in StreamPrinter will find only ADL207// candidates.208struct LookupBlocker {};209void operator<<(LookupBlocker, LookupBlocker);210 211struct StreamPrinter {212  template <typename T,213            // Don't accept member pointers here. We'd print them via implicit214            // conversion to bool, which isn't useful.215            typename = typename std::enable_if<216                !std::is_member_pointer<T>::value>::type>217  // Only accept types for which we can find a streaming operator via218  // ADL (possibly involving implicit conversions).219  // (Use SFINAE via return type, because it seems GCC < 12 doesn't handle name220  // lookup properly when we do it in the template parameter list.)221 222  // LLVM local change to support llvm printables.223  //224  // static auto PrintValue(const T& value, ::std::ostream* os)225  //     -> decltype((void)(*os << value)) {226  //   // Call streaming operator found by ADL, possibly with implicit conversions227  //   // of the arguments.228  //   // LLVM local change to support llvm printables.229  //   //230  //   *os << value;231  //   // LLVM local change end.232  // }233  static auto PrintValue(const T& value, ::std::ostream* os)234      -> decltype((void)(*os << ::llvm_gtest::printable(value))) {235    // Call streaming operator found by ADL, possibly with implicit conversions236    // of the arguments.237    // LLVM local change to support llvm printables.238    //239    *os << ::llvm_gtest::printable(value);240    // LLVM local change end.241  }242};243 244}  // namespace internal_stream_operator_without_lexical_name_lookup245 246struct ProtobufPrinter {247  // We print a protobuf using its ShortDebugString() when the string248  // doesn't exceed this many characters; otherwise we print it using249  // DebugString() for better readability.250  static const size_t kProtobufOneLinerMaxLength = 50;251 252  template <typename T,253            typename = typename std::enable_if<254                internal::HasDebugStringAndShortDebugString<T>::value>::type>255  static void PrintValue(const T& value, ::std::ostream* os) {256    std::string pretty_str = value.ShortDebugString();257    if (pretty_str.length() > kProtobufOneLinerMaxLength) {258      pretty_str = "\n" + value.DebugString();259    }260    *os << ("<" + pretty_str + ">");261  }262};263 264struct ConvertibleToIntegerPrinter {265  // Since T has no << operator or PrintTo() but can be implicitly266  // converted to BiggestInt, we print it as a BiggestInt.267  //268  // Most likely T is an enum type (either named or unnamed), in which269  // case printing it as an integer is the desired behavior.  In case270  // T is not an enum, printing it as an integer is the best we can do271  // given that it has no user-defined printer.272  static void PrintValue(internal::BiggestInt value, ::std::ostream* os) {273    *os << value;274  }275};276 277struct ConvertibleToStringViewPrinter {278#if GTEST_INTERNAL_HAS_STRING_VIEW279  static void PrintValue(internal::StringView value, ::std::ostream* os) {280    internal::UniversalPrint(value, os);281  }282#endif283};284 285#ifdef GTEST_HAS_ABSL286struct ConvertibleToAbslStringifyPrinter {287  template <288      typename T,289      typename = typename std::enable_if<290          absl::strings_internal::HasAbslStringify<T>::value>::type>  // NOLINT291  static void PrintValue(const T& value, ::std::ostream* os) {292    *os << absl::StrCat(value);293  }294};295#endif  // GTEST_HAS_ABSL296 297// Prints the given number of bytes in the given object to the given298// ostream.299GTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes,300                                     size_t count, ::std::ostream* os);301struct RawBytesPrinter {302  // SFINAE on `sizeof` to make sure we have a complete type.303  template <typename T, size_t = sizeof(T)>304  static void PrintValue(const T& value, ::std::ostream* os) {305    PrintBytesInObjectTo(306        static_cast<const unsigned char*>(307            // Load bearing cast to void* to support iOS308            reinterpret_cast<const void*>(std::addressof(value))),309        sizeof(value), os);310  }311};312 313struct FallbackPrinter {314  template <typename T>315  static void PrintValue(const T&, ::std::ostream* os) {316    *os << "(incomplete type)";317  }318};319 320// Try every printer in order and return the first one that works.321template <typename T, typename E, typename Printer, typename... Printers>322struct FindFirstPrinter : FindFirstPrinter<T, E, Printers...> {};323 324template <typename T, typename Printer, typename... Printers>325struct FindFirstPrinter<326    T, decltype(Printer::PrintValue(std::declval<const T&>(), nullptr)),327    Printer, Printers...> {328  using type = Printer;329};330 331// Select the best printer in the following order:332//  - Print containers (they have begin/end/etc).333//  - Print function pointers.334//  - Print object pointers.335//  - Print protocol buffers.336//  - Use the stream operator, if available.337//  - Print types convertible to BiggestInt.338//  - Print types convertible to StringView, if available.339//  - Fallback to printing the raw bytes of the object.340template <typename T>341void PrintWithFallback(const T& value, ::std::ostream* os) {342  using Printer = typename FindFirstPrinter<343      T, void, ContainerPrinter, FunctionPointerPrinter, PointerPrinter,344      ProtobufPrinter,345#ifdef GTEST_HAS_ABSL346      ConvertibleToAbslStringifyPrinter,347#endif  // GTEST_HAS_ABSL348      internal_stream_operator_without_lexical_name_lookup::StreamPrinter,349      ConvertibleToIntegerPrinter, ConvertibleToStringViewPrinter,350      RawBytesPrinter, FallbackPrinter>::type;351  Printer::PrintValue(value, os);352}353 354// FormatForComparison<ToPrint, OtherOperand>::Format(value) formats a355// value of type ToPrint that is an operand of a comparison assertion356// (e.g. ASSERT_EQ).  OtherOperand is the type of the other operand in357// the comparison, and is used to help determine the best way to358// format the value.  In particular, when the value is a C string359// (char pointer) and the other operand is an STL string object, we360// want to format the C string as a string, since we know it is361// compared by value with the string object.  If the value is a char362// pointer but the other operand is not an STL string object, we don't363// know whether the pointer is supposed to point to a NUL-terminated364// string, and thus want to print it as a pointer to be safe.365//366// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.367 368// The default case.369template <typename ToPrint, typename OtherOperand>370class FormatForComparison {371 public:372  static ::std::string Format(const ToPrint& value) {373    return ::testing::PrintToString(value);374  }375};376 377// Array.378template <typename ToPrint, size_t N, typename OtherOperand>379class FormatForComparison<ToPrint[N], OtherOperand> {380 public:381  static ::std::string Format(const ToPrint* value) {382    return FormatForComparison<const ToPrint*, OtherOperand>::Format(value);383  }384};385 386// By default, print C string as pointers to be safe, as we don't know387// whether they actually point to a NUL-terminated string.388 389#define GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(CharType)                \390  template <typename OtherOperand>                                      \391  class FormatForComparison<CharType*, OtherOperand> {                  \392   public:                                                              \393    static ::std::string Format(CharType* value) {                      \394      return ::testing::PrintToString(static_cast<const void*>(value)); \395    }                                                                   \396  }397 398GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char);399GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char);400GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(wchar_t);401GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const wchar_t);402#ifdef __cpp_lib_char8_t403GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char8_t);404GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char8_t);405#endif406GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char16_t);407GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char16_t);408GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char32_t);409GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char32_t);410 411#undef GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_412 413// If a C string is compared with an STL string object, we know it's meant414// to point to a NUL-terminated string, and thus can print it as a string.415 416#define GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(CharType, OtherStringType) \417  template <>                                                            \418  class FormatForComparison<CharType*, OtherStringType> {                \419   public:                                                               \420    static ::std::string Format(CharType* value) {                       \421      return ::testing::PrintToString(value);                            \422    }                                                                    \423  }424 425GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::std::string);426GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char, ::std::string);427#ifdef __cpp_lib_char8_t428GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char8_t, ::std::u8string);429GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char8_t, ::std::u8string);430#endif431GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char16_t, ::std::u16string);432GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char16_t, ::std::u16string);433GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char32_t, ::std::u32string);434GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char32_t, ::std::u32string);435 436#if GTEST_HAS_STD_WSTRING437GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(wchar_t, ::std::wstring);438GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const wchar_t, ::std::wstring);439#endif440 441#undef GTEST_IMPL_FORMAT_C_STRING_AS_STRING_442 443// Formats a comparison assertion (e.g. ASSERT_EQ, EXPECT_LT, and etc)444// operand to be used in a failure message.  The type (but not value)445// of the other operand may affect the format.  This allows us to446// print a char* as a raw pointer when it is compared against another447// char* or void*, and print it as a C string when it is compared448// against an std::string object, for example.449//450// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.451template <typename T1, typename T2>452std::string FormatForComparisonFailureMessage(const T1& value,453                                              const T2& /* other_operand */) {454  return FormatForComparison<T1, T2>::Format(value);455}456 457// UniversalPrinter<T>::Print(value, ostream_ptr) prints the given458// value to the given ostream.  The caller must ensure that459// 'ostream_ptr' is not NULL, or the behavior is undefined.460//461// We define UniversalPrinter as a class template (as opposed to a462// function template), as we need to partially specialize it for463// reference types, which cannot be done with function templates.464template <typename T>465class UniversalPrinter;466 467// Prints the given value using the << operator if it has one;468// otherwise prints the bytes in it.  This is what469// UniversalPrinter<T>::Print() does when PrintTo() is not specialized470// or overloaded for type T.471//472// A user can override this behavior for a class type Foo by defining473// an overload of PrintTo() in the namespace where Foo is defined.  We474// give the user this option as sometimes defining a << operator for475// Foo is not desirable (e.g. the coding style may prevent doing it,476// or there is already a << operator but it doesn't do what the user477// wants).478template <typename T>479void PrintTo(const T& value, ::std::ostream* os) {480  internal::PrintWithFallback(value, os);481}482 483// The following list of PrintTo() overloads tells484// UniversalPrinter<T>::Print() how to print standard types (built-in485// types, strings, plain arrays, and pointers).486 487// Overloads for various char types.488GTEST_API_ void PrintTo(unsigned char c, ::std::ostream* os);489GTEST_API_ void PrintTo(signed char c, ::std::ostream* os);490inline void PrintTo(char c, ::std::ostream* os) {491  // When printing a plain char, we always treat it as unsigned.  This492  // way, the output won't be affected by whether the compiler thinks493  // char is signed or not.494  PrintTo(static_cast<unsigned char>(c), os);495}496 497// Overloads for other simple built-in types.498inline void PrintTo(bool x, ::std::ostream* os) {499  *os << (x ? "true" : "false");500}501 502// Overload for wchar_t type.503// Prints a wchar_t as a symbol if it is printable or as its internal504// code otherwise and also as its decimal code (except for L'\0').505// The L'\0' char is printed as "L'\\0'". The decimal code is printed506// as signed integer when wchar_t is implemented by the compiler507// as a signed type and is printed as an unsigned integer when wchar_t508// is implemented as an unsigned type.509GTEST_API_ void PrintTo(wchar_t wc, ::std::ostream* os);510 511GTEST_API_ void PrintTo(char32_t c, ::std::ostream* os);512inline void PrintTo(char16_t c, ::std::ostream* os) {513  // FIXME: the cast from char16_t to char32_t may be incorrect514  // for a lone surrogate515  PrintTo(static_cast<char32_t>(c), os);516}517#ifdef __cpp_lib_char8_t518inline void PrintTo(char8_t c, ::std::ostream* os) {519  // FIXME: the cast from char8_t to char32_t may be incorrect520  // for c > 0x7F521  PrintTo(static_cast<char32_t>(c), os);522}523#endif524 525// gcc/clang __{u,}int128_t526#if defined(__SIZEOF_INT128__)527GTEST_API_ void PrintTo(__uint128_t v, ::std::ostream* os);528GTEST_API_ void PrintTo(__int128_t v, ::std::ostream* os);529#endif  // __SIZEOF_INT128__530 531// The default resolution used to print floating-point values uses only532// 6 digits, which can be confusing if a test compares two values whose533// difference lies in the 7th digit.  So we'd like to print out numbers534// in full precision.535// However if the value is something simple like 1.1, full will print a536// long string like 1.100000001 due to floating-point numbers not using537// a base of 10.  This routiune returns an appropriate resolution for a538// given floating-point number, that is, 6 if it will be accurate, or a539// max_digits10 value (full precision) if it won't,  for values between540// 0.0001 and one million.541// It does this by computing what those digits would be (by multiplying542// by an appropriate power of 10), then dividing by that power again to543// see if gets the original value back.544// A similar algorithm applies for values larger than one million; note545// that for those values, we must divide to get a six-digit number, and546// then multiply to possibly get the original value again.547template <typename FloatType>548int AppropriateResolution(FloatType val) {549  int full = std::numeric_limits<FloatType>::max_digits10;550  if (val < 0) val = -val;551 552  if (val < 1000000) {553    FloatType mulfor6 = 1e10;554    if (val >= 100000.0) {  // 100,000 to 999,999555      mulfor6 = 1.0;556    } else if (val >= 10000.0) {557      mulfor6 = 1e1;558    } else if (val >= 1000.0) {559      mulfor6 = 1e2;560    } else if (val >= 100.0) {561      mulfor6 = 1e3;562    } else if (val >= 10.0) {563      mulfor6 = 1e4;564    } else if (val >= 1.0) {565      mulfor6 = 1e5;566    } else if (val >= 0.1) {567      mulfor6 = 1e6;568    } else if (val >= 0.01) {569      mulfor6 = 1e7;570    } else if (val >= 0.001) {571      mulfor6 = 1e8;572    } else if (val >= 0.0001) {573      mulfor6 = 1e9;574    }575    if (static_cast<FloatType>(static_cast<int32_t>(val * mulfor6 + 0.5)) /576            mulfor6 ==577        val)578      return 6;579  } else if (val < 1e10) {580    FloatType divfor6 = 1.0;581    if (val >= 1e9) {  // 1,000,000,000 to 9,999,999,999582      divfor6 = 10000;583    } else if (val >= 1e8) {  // 100,000,000 to 999,999,999584      divfor6 = 1000;585    } else if (val >= 1e7) {  // 10,000,000 to 99,999,999586      divfor6 = 100;587    } else if (val >= 1e6) {  // 1,000,000 to 9,999,999588      divfor6 = 10;589    }590    if (static_cast<FloatType>(static_cast<int32_t>(val / divfor6 + 0.5)) *591            divfor6 ==592        val)593      return 6;594  }595  return full;596}597 598inline void PrintTo(float f, ::std::ostream* os) {599  auto old_precision = os->precision();600  os->precision(AppropriateResolution(f));601  *os << f;602  os->precision(old_precision);603}604 605inline void PrintTo(double d, ::std::ostream* os) {606  auto old_precision = os->precision();607  os->precision(AppropriateResolution(d));608  *os << d;609  os->precision(old_precision);610}611 612// Overloads for C strings.613GTEST_API_ void PrintTo(const char* s, ::std::ostream* os);614inline void PrintTo(char* s, ::std::ostream* os) {615  PrintTo(ImplicitCast_<const char*>(s), os);616}617 618// signed/unsigned char is often used for representing binary data, so619// we print pointers to it as void* to be safe.620inline void PrintTo(const signed char* s, ::std::ostream* os) {621  PrintTo(ImplicitCast_<const void*>(s), os);622}623inline void PrintTo(signed char* s, ::std::ostream* os) {624  PrintTo(ImplicitCast_<const void*>(s), os);625}626inline void PrintTo(const unsigned char* s, ::std::ostream* os) {627  PrintTo(ImplicitCast_<const void*>(s), os);628}629inline void PrintTo(unsigned char* s, ::std::ostream* os) {630  PrintTo(ImplicitCast_<const void*>(s), os);631}632#ifdef __cpp_lib_char8_t633// Overloads for u8 strings.634GTEST_API_ void PrintTo(const char8_t* s, ::std::ostream* os);635inline void PrintTo(char8_t* s, ::std::ostream* os) {636  PrintTo(ImplicitCast_<const char8_t*>(s), os);637}638#endif639// Overloads for u16 strings.640GTEST_API_ void PrintTo(const char16_t* s, ::std::ostream* os);641inline void PrintTo(char16_t* s, ::std::ostream* os) {642  PrintTo(ImplicitCast_<const char16_t*>(s), os);643}644// Overloads for u32 strings.645GTEST_API_ void PrintTo(const char32_t* s, ::std::ostream* os);646inline void PrintTo(char32_t* s, ::std::ostream* os) {647  PrintTo(ImplicitCast_<const char32_t*>(s), os);648}649 650// MSVC can be configured to define wchar_t as a typedef of unsigned651// short.  It defines _NATIVE_WCHAR_T_DEFINED when wchar_t is a native652// type.  When wchar_t is a typedef, defining an overload for const653// wchar_t* would cause unsigned short* be printed as a wide string,654// possibly causing invalid memory accesses.655#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)656// Overloads for wide C strings657GTEST_API_ void PrintTo(const wchar_t* s, ::std::ostream* os);658inline void PrintTo(wchar_t* s, ::std::ostream* os) {659  PrintTo(ImplicitCast_<const wchar_t*>(s), os);660}661#endif662 663// Overload for C arrays.  Multi-dimensional arrays are printed664// properly.665 666// Prints the given number of elements in an array, without printing667// the curly braces.668template <typename T>669void PrintRawArrayTo(const T a[], size_t count, ::std::ostream* os) {670  UniversalPrint(a[0], os);671  for (size_t i = 1; i != count; i++) {672    *os << ", ";673    UniversalPrint(a[i], os);674  }675}676 677// Overloads for ::std::string.678GTEST_API_ void PrintStringTo(const ::std::string& s, ::std::ostream* os);679inline void PrintTo(const ::std::string& s, ::std::ostream* os) {680  PrintStringTo(s, os);681}682 683// Overloads for ::std::u8string684#ifdef __cpp_lib_char8_t685GTEST_API_ void PrintU8StringTo(const ::std::u8string& s, ::std::ostream* os);686inline void PrintTo(const ::std::u8string& s, ::std::ostream* os) {687  PrintU8StringTo(s, os);688}689#endif690 691// Overloads for ::std::u16string692GTEST_API_ void PrintU16StringTo(const ::std::u16string& s, ::std::ostream* os);693inline void PrintTo(const ::std::u16string& s, ::std::ostream* os) {694  PrintU16StringTo(s, os);695}696 697// Overloads for ::std::u32string698GTEST_API_ void PrintU32StringTo(const ::std::u32string& s, ::std::ostream* os);699inline void PrintTo(const ::std::u32string& s, ::std::ostream* os) {700  PrintU32StringTo(s, os);701}702 703// Overloads for ::std::wstring.704#if GTEST_HAS_STD_WSTRING705GTEST_API_ void PrintWideStringTo(const ::std::wstring& s, ::std::ostream* os);706inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) {707  PrintWideStringTo(s, os);708}709#endif  // GTEST_HAS_STD_WSTRING710 711#if GTEST_INTERNAL_HAS_STRING_VIEW712// Overload for internal::StringView.713inline void PrintTo(internal::StringView sp, ::std::ostream* os) {714  PrintTo(::std::string(sp), os);715}716#endif  // GTEST_INTERNAL_HAS_STRING_VIEW717 718inline void PrintTo(std::nullptr_t, ::std::ostream* os) { *os << "(nullptr)"; }719 720#if GTEST_HAS_RTTI721inline void PrintTo(const std::type_info& info, std::ostream* os) {722  *os << internal::GetTypeName(info);723}724#endif  // GTEST_HAS_RTTI725 726template <typename T>727void PrintTo(std::reference_wrapper<T> ref, ::std::ostream* os) {728  UniversalPrinter<T&>::Print(ref.get(), os);729}730 731inline const void* VoidifyPointer(const void* p) { return p; }732inline const void* VoidifyPointer(volatile const void* p) {733  return const_cast<const void*>(p);734}735 736template <typename T, typename Ptr>737void PrintSmartPointer(const Ptr& ptr, std::ostream* os, char) {738  if (ptr == nullptr) {739    *os << "(nullptr)";740  } else {741    // We can't print the value. Just print the pointer..742    *os << "(" << (VoidifyPointer)(ptr.get()) << ")";743  }744}745template <typename T, typename Ptr,746          typename = typename std::enable_if<!std::is_void<T>::value &&747                                             !std::is_array<T>::value>::type>748void PrintSmartPointer(const Ptr& ptr, std::ostream* os, int) {749  if (ptr == nullptr) {750    *os << "(nullptr)";751  } else {752    *os << "(ptr = " << (VoidifyPointer)(ptr.get()) << ", value = ";753    UniversalPrinter<T>::Print(*ptr, os);754    *os << ")";755  }756}757 758template <typename T, typename D>759void PrintTo(const std::unique_ptr<T, D>& ptr, std::ostream* os) {760  (PrintSmartPointer<T>)(ptr, os, 0);761}762 763template <typename T>764void PrintTo(const std::shared_ptr<T>& ptr, std::ostream* os) {765  (PrintSmartPointer<T>)(ptr, os, 0);766}767 768// Helper function for printing a tuple.  T must be instantiated with769// a tuple type.770template <typename T>771void PrintTupleTo(const T&, std::integral_constant<size_t, 0>,772                  ::std::ostream*) {}773 774template <typename T, size_t I>775void PrintTupleTo(const T& t, std::integral_constant<size_t, I>,776                  ::std::ostream* os) {777  PrintTupleTo(t, std::integral_constant<size_t, I - 1>(), os);778  GTEST_INTENTIONAL_CONST_COND_PUSH_()779  if (I > 1) {780    GTEST_INTENTIONAL_CONST_COND_POP_()781    *os << ", ";782  }783  UniversalPrinter<typename std::tuple_element<I - 1, T>::type>::Print(784      std::get<I - 1>(t), os);785}786 787template <typename... Types>788void PrintTo(const ::std::tuple<Types...>& t, ::std::ostream* os) {789  *os << "(";790  PrintTupleTo(t, std::integral_constant<size_t, sizeof...(Types)>(), os);791  *os << ")";792}793 794// Overload for std::pair.795template <typename T1, typename T2>796void PrintTo(const ::std::pair<T1, T2>& value, ::std::ostream* os) {797  *os << '(';798  // We cannot use UniversalPrint(value.first, os) here, as T1 may be799  // a reference type.  The same for printing value.second.800  UniversalPrinter<T1>::Print(value.first, os);801  *os << ", ";802  UniversalPrinter<T2>::Print(value.second, os);803  *os << ')';804}805 806// Implements printing a non-reference type T by letting the compiler807// pick the right overload of PrintTo() for T.808template <typename T>809class UniversalPrinter {810 public:811  // MSVC warns about adding const to a function type, so we want to812  // disable the warning.813  GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180)814 815  // Note: we deliberately don't call this PrintTo(), as that name816  // conflicts with ::testing::internal::PrintTo in the body of the817  // function.818  static void Print(const T& value, ::std::ostream* os) {819    // By default, ::testing::internal::PrintTo() is used for printing820    // the value.821    //822    // Thanks to Koenig look-up, if T is a class and has its own823    // PrintTo() function defined in its namespace, that function will824    // be visible here.  Since it is more specific than the generic ones825    // in ::testing::internal, it will be picked by the compiler in the826    // following statement - exactly what we want.827    PrintTo(value, os);828  }829 830  GTEST_DISABLE_MSC_WARNINGS_POP_()831};832 833// Remove any const-qualifiers before passing a type to UniversalPrinter.834template <typename T>835class UniversalPrinter<const T> : public UniversalPrinter<T> {};836 837#if GTEST_INTERNAL_HAS_ANY838 839// Printer for std::any / absl::any840 841template <>842class UniversalPrinter<Any> {843 public:844  static void Print(const Any& value, ::std::ostream* os) {845    if (value.has_value()) {846      *os << "value of type " << GetTypeName(value);847    } else {848      *os << "no value";849    }850  }851 852 private:853  static std::string GetTypeName(const Any& value) {854#if GTEST_HAS_RTTI855    return internal::GetTypeName(value.type());856#else857    static_cast<void>(value);  // possibly unused858    return "<unknown_type>";859#endif  // GTEST_HAS_RTTI860  }861};862 863#endif  // GTEST_INTERNAL_HAS_ANY864 865#if GTEST_INTERNAL_HAS_OPTIONAL866 867// Printer for std::optional / absl::optional868 869template <typename T>870class UniversalPrinter<Optional<T>> {871 public:872  static void Print(const Optional<T>& value, ::std::ostream* os) {873    *os << '(';874    if (!value) {875      *os << "nullopt";876    } else {877      UniversalPrint(*value, os);878    }879    *os << ')';880  }881};882 883template <>884class UniversalPrinter<decltype(Nullopt())> {885 public:886  static void Print(decltype(Nullopt()), ::std::ostream* os) {887    *os << "(nullopt)";888  }889};890 891#endif  // GTEST_INTERNAL_HAS_OPTIONAL892 893#if GTEST_INTERNAL_HAS_VARIANT894 895// Printer for std::variant / absl::variant896 897template <typename... T>898class UniversalPrinter<Variant<T...>> {899 public:900  static void Print(const Variant<T...>& value, ::std::ostream* os) {901    *os << '(';902#ifdef GTEST_HAS_ABSL903    absl::visit(Visitor{os, value.index()}, value);904#else905    std::visit(Visitor{os, value.index()}, value);906#endif  // GTEST_HAS_ABSL907    *os << ')';908  }909 910 private:911  struct Visitor {912    template <typename U>913    void operator()(const U& u) const {914      *os << "'" << GetTypeName<U>() << "(index = " << index915          << ")' with value ";916      UniversalPrint(u, os);917    }918    ::std::ostream* os;919    std::size_t index;920  };921};922 923#endif  // GTEST_INTERNAL_HAS_VARIANT924 925// UniversalPrintArray(begin, len, os) prints an array of 'len'926// elements, starting at address 'begin'.927template <typename T>928void UniversalPrintArray(const T* begin, size_t len, ::std::ostream* os) {929  if (len == 0) {930    *os << "{}";931  } else {932    *os << "{ ";933    const size_t kThreshold = 18;934    const size_t kChunkSize = 8;935    // If the array has more than kThreshold elements, we'll have to936    // omit some details by printing only the first and the last937    // kChunkSize elements.938    if (len <= kThreshold) {939      PrintRawArrayTo(begin, len, os);940    } else {941      PrintRawArrayTo(begin, kChunkSize, os);942      *os << ", ..., ";943      PrintRawArrayTo(begin + len - kChunkSize, kChunkSize, os);944    }945    *os << " }";946  }947}948// This overload prints a (const) char array compactly.949GTEST_API_ void UniversalPrintArray(const char* begin, size_t len,950                                    ::std::ostream* os);951 952#ifdef __cpp_lib_char8_t953// This overload prints a (const) char8_t array compactly.954GTEST_API_ void UniversalPrintArray(const char8_t* begin, size_t len,955                                    ::std::ostream* os);956#endif957 958// This overload prints a (const) char16_t array compactly.959GTEST_API_ void UniversalPrintArray(const char16_t* begin, size_t len,960                                    ::std::ostream* os);961 962// This overload prints a (const) char32_t array compactly.963GTEST_API_ void UniversalPrintArray(const char32_t* begin, size_t len,964                                    ::std::ostream* os);965 966// This overload prints a (const) wchar_t array compactly.967GTEST_API_ void UniversalPrintArray(const wchar_t* begin, size_t len,968                                    ::std::ostream* os);969 970// Implements printing an array type T[N].971template <typename T, size_t N>972class UniversalPrinter<T[N]> {973 public:974  // Prints the given array, omitting some elements when there are too975  // many.976  static void Print(const T (&a)[N], ::std::ostream* os) {977    UniversalPrintArray(a, N, os);978  }979};980 981// Implements printing a reference type T&.982template <typename T>983class UniversalPrinter<T&> {984 public:985  // MSVC warns about adding const to a function type, so we want to986  // disable the warning.987  GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180)988 989  static void Print(const T& value, ::std::ostream* os) {990    // Prints the address of the value.  We use reinterpret_cast here991    // as static_cast doesn't compile when T is a function type.992    *os << "@" << reinterpret_cast<const void*>(&value) << " ";993 994    // Then prints the value itself.995    UniversalPrint(value, os);996  }997 998  GTEST_DISABLE_MSC_WARNINGS_POP_()999};1000 1001// Prints a value tersely: for a reference type, the referenced value1002// (but not the address) is printed; for a (const) char pointer, the1003// NUL-terminated string (but not the pointer) is printed.1004 1005template <typename T>1006class UniversalTersePrinter {1007 public:1008  static void Print(const T& value, ::std::ostream* os) {1009    UniversalPrint(value, os);1010  }1011};1012template <typename T>1013class UniversalTersePrinter<T&> {1014 public:1015  static void Print(const T& value, ::std::ostream* os) {1016    UniversalPrint(value, os);1017  }1018};1019template <typename T>1020class UniversalTersePrinter<std::reference_wrapper<T>> {1021 public:1022  static void Print(std::reference_wrapper<T> value, ::std::ostream* os) {1023    UniversalTersePrinter<T>::Print(value.get(), os);1024  }1025};1026template <typename T, size_t N>1027class UniversalTersePrinter<T[N]> {1028 public:1029  static void Print(const T (&value)[N], ::std::ostream* os) {1030    UniversalPrinter<T[N]>::Print(value, os);1031  }1032};1033template <>1034class UniversalTersePrinter<const char*> {1035 public:1036  static void Print(const char* str, ::std::ostream* os) {1037    if (str == nullptr) {1038      *os << "NULL";1039    } else {1040      UniversalPrint(std::string(str), os);1041    }1042  }1043};1044template <>1045class UniversalTersePrinter<char*> : public UniversalTersePrinter<const char*> {1046};1047 1048#ifdef __cpp_lib_char8_t1049template <>1050class UniversalTersePrinter<const char8_t*> {1051 public:1052  static void Print(const char8_t* str, ::std::ostream* os) {1053    if (str == nullptr) {1054      *os << "NULL";1055    } else {1056      UniversalPrint(::std::u8string(str), os);1057    }1058  }1059};1060template <>1061class UniversalTersePrinter<char8_t*>1062    : public UniversalTersePrinter<const char8_t*> {};1063#endif1064 1065template <>1066class UniversalTersePrinter<const char16_t*> {1067 public:1068  static void Print(const char16_t* str, ::std::ostream* os) {1069    if (str == nullptr) {1070      *os << "NULL";1071    } else {1072      UniversalPrint(::std::u16string(str), os);1073    }1074  }1075};1076template <>1077class UniversalTersePrinter<char16_t*>1078    : public UniversalTersePrinter<const char16_t*> {};1079 1080template <>1081class UniversalTersePrinter<const char32_t*> {1082 public:1083  static void Print(const char32_t* str, ::std::ostream* os) {1084    if (str == nullptr) {1085      *os << "NULL";1086    } else {1087      UniversalPrint(::std::u32string(str), os);1088    }1089  }1090};1091template <>1092class UniversalTersePrinter<char32_t*>1093    : public UniversalTersePrinter<const char32_t*> {};1094 1095#if GTEST_HAS_STD_WSTRING1096template <>1097class UniversalTersePrinter<const wchar_t*> {1098 public:1099  static void Print(const wchar_t* str, ::std::ostream* os) {1100    if (str == nullptr) {1101      *os << "NULL";1102    } else {1103      UniversalPrint(::std::wstring(str), os);1104    }1105  }1106};1107#endif1108 1109template <>1110class UniversalTersePrinter<wchar_t*> {1111 public:1112  static void Print(wchar_t* str, ::std::ostream* os) {1113    UniversalTersePrinter<const wchar_t*>::Print(str, os);1114  }1115};1116 1117template <typename T>1118void UniversalTersePrint(const T& value, ::std::ostream* os) {1119  UniversalTersePrinter<T>::Print(value, os);1120}1121 1122// Prints a value using the type inferred by the compiler.  The1123// difference between this and UniversalTersePrint() is that for a1124// (const) char pointer, this prints both the pointer and the1125// NUL-terminated string.1126template <typename T>1127void UniversalPrint(const T& value, ::std::ostream* os) {1128  // A workarond for the bug in VC++ 7.1 that prevents us from instantiating1129  // UniversalPrinter with T directly.1130  typedef T T1;1131  UniversalPrinter<T1>::Print(value, os);1132}1133 1134typedef ::std::vector<::std::string> Strings;1135 1136// Tersely prints the first N fields of a tuple to a string vector,1137// one element for each field.1138template <typename Tuple>1139void TersePrintPrefixToStrings(const Tuple&, std::integral_constant<size_t, 0>,1140                               Strings*) {}1141template <typename Tuple, size_t I>1142void TersePrintPrefixToStrings(const Tuple& t,1143                               std::integral_constant<size_t, I>,1144                               Strings* strings) {1145  TersePrintPrefixToStrings(t, std::integral_constant<size_t, I - 1>(),1146                            strings);1147  ::std::stringstream ss;1148  UniversalTersePrint(std::get<I - 1>(t), &ss);1149  strings->push_back(ss.str());1150}1151 1152// Prints the fields of a tuple tersely to a string vector, one1153// element for each field.  See the comment before1154// UniversalTersePrint() for how we define "tersely".1155template <typename Tuple>1156Strings UniversalTersePrintTupleFieldsToStrings(const Tuple& value) {1157  Strings result;1158  TersePrintPrefixToStrings(1159      value, std::integral_constant<size_t, std::tuple_size<Tuple>::value>(),1160      &result);1161  return result;1162}1163 1164}  // namespace internal1165 1166template <typename T>1167::std::string PrintToString(const T& value) {1168  ::std::stringstream ss;1169  internal::UniversalTersePrinter<T>::Print(value, &ss);1170  return ss.str();1171}1172 1173}  // namespace testing1174 1175// Include any custom printer added by the local installation.1176// We must include this header at the end to make sure it can use the1177// declarations from this file.1178#include "gtest/internal/custom/gtest-printers.h"1179 1180#endif  // GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_1181