gtest-printers.h 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928
  1. // Copyright 2007, Google Inc.
  2. // All rights reserved.
  3. //
  4. // Redistribution and use in source and binary forms, with or without
  5. // modification, are permitted provided that the following conditions are
  6. // met:
  7. //
  8. // * Redistributions of source code must retain the above copyright
  9. // notice, this list of conditions and the following disclaimer.
  10. // * Redistributions in binary form must reproduce the above
  11. // copyright notice, this list of conditions and the following disclaimer
  12. // in the documentation and/or other materials provided with the
  13. // distribution.
  14. // * Neither the name of Google Inc. nor the names of its
  15. // contributors may be used to endorse or promote products derived from
  16. // this software without specific prior written permission.
  17. //
  18. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  22. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  24. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. // Google Test - The Google C++ Testing and Mocking Framework
  30. //
  31. // This file implements a universal value printer that can print a
  32. // 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 by
  37. // defining either operator<<() or PrintTo() in the namespace that
  38. // defines T. More specifically, the FIRST defined function in the
  39. // following list will be used (assuming T is defined in namespace
  40. // foo):
  41. //
  42. // 1. foo::PrintTo(const T&, ostream*)
  43. // 2. operator<<(ostream&, const T&) defined in either foo or the
  44. // global namespace.
  45. //
  46. // However if T is an STL-style container then it is printed element-wise
  47. // unless foo::PrintTo(const T&, ostream*) is defined. Note that
  48. // operator<<() is ignored for container types.
  49. //
  50. // If none of the above is defined, it will print the debug string of
  51. // the value if it is a protocol buffer, or print the raw bytes in the
  52. // value otherwise.
  53. //
  54. // To aid debugging: when T is a reference type, the address of the
  55. // value is also printed; when T is a (const) char pointer, both the
  56. // pointer value and the NUL-terminated string it points to are
  57. // printed.
  58. //
  59. // We also provide some convenient wrappers:
  60. //
  61. // // Prints a value to a string. For a (const or not) char
  62. // // pointer, the NUL-terminated string (but not the pointer) is
  63. // // printed.
  64. // std::string ::testing::PrintToString(const T& value);
  65. //
  66. // // Prints a value tersely: for a reference type, the referenced
  67. // // value (but not the address) is printed; for a (const or not) char
  68. // // pointer, the NUL-terminated string (but not the pointer) is
  69. // // printed.
  70. // void ::testing::internal::UniversalTersePrint(const T& value, ostream*);
  71. //
  72. // // Prints value using the type inferred by the compiler. The difference
  73. // // from UniversalTersePrint() is that this function prints both the
  74. // // pointer and the NUL-terminated string for a (const or not) char pointer.
  75. // void ::testing::internal::UniversalPrint(const T& value, ostream*);
  76. //
  77. // // Prints the fields of a tuple tersely to a string vector, one
  78. // // element for each field. Tuple support must be enabled in
  79. // // gtest-port.h.
  80. // std::vector<string> UniversalTersePrintTupleFieldsToStrings(
  81. // const Tuple& value);
  82. //
  83. // Known limitation:
  84. //
  85. // The print primitives print the elements of an STL-style container
  86. // using the compiler-inferred type of *iter where iter is a
  87. // const_iterator of the container. When const_iterator is an input
  88. // iterator but not a forward iterator, this inferred type may not
  89. // match value_type, and the print output may be incorrect. In
  90. // practice, this is rarely a problem as for most containers
  91. // const_iterator is a forward iterator. We'll fix this if there's an
  92. // actual need for it. Note that this fix cannot rely on value_type
  93. // being defined as many user-defined container types don't have
  94. // value_type.
  95. // GOOGLETEST_CM0001 DO NOT DELETE
  96. #ifndef GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
  97. #define GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
  98. #include <functional>
  99. #include <ostream> // NOLINT
  100. #include <sstream>
  101. #include <string>
  102. #include <tuple>
  103. #include <type_traits>
  104. #include <utility>
  105. #include <vector>
  106. #include "gtest/internal/gtest-internal.h"
  107. #include "gtest/internal/gtest-port.h"
  108. #if GTEST_HAS_ABSL
  109. #include "absl/strings/string_view.h"
  110. #include "absl/types/optional.h"
  111. #include "absl/types/variant.h"
  112. #endif // GTEST_HAS_ABSL
  113. namespace testing {
  114. // Definitions in the 'internal' and 'internal2' name spaces are
  115. // subject to change without notice. DO NOT USE THEM IN USER CODE!
  116. namespace internal2 {
  117. // Prints the given number of bytes in the given object to the given
  118. // ostream.
  119. GTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes,
  120. size_t count,
  121. ::std::ostream* os);
  122. // For selecting which printer to use when a given type has neither <<
  123. // nor PrintTo().
  124. enum TypeKind {
  125. kProtobuf, // a protobuf type
  126. kConvertibleToInteger, // a type implicitly convertible to BiggestInt
  127. // (e.g. a named or unnamed enum type)
  128. #if GTEST_HAS_ABSL
  129. kConvertibleToStringView, // a type implicitly convertible to
  130. // absl::string_view
  131. #endif
  132. kOtherType // anything else
  133. };
  134. // TypeWithoutFormatter<T, kTypeKind>::PrintValue(value, os) is called
  135. // by the universal printer to print a value of type T when neither
  136. // operator<< nor PrintTo() is defined for T, where kTypeKind is the
  137. // "kind" of T as defined by enum TypeKind.
  138. template <typename T, TypeKind kTypeKind>
  139. class TypeWithoutFormatter {
  140. public:
  141. // This default version is called when kTypeKind is kOtherType.
  142. static void PrintValue(const T& value, ::std::ostream* os) {
  143. PrintBytesInObjectTo(
  144. static_cast<const unsigned char*>(
  145. reinterpret_cast<const void*>(std::addressof(value))),
  146. sizeof(value), os);
  147. }
  148. };
  149. // We print a protobuf using its ShortDebugString() when the string
  150. // doesn't exceed this many characters; otherwise we print it using
  151. // DebugString() for better readability.
  152. const size_t kProtobufOneLinerMaxLength = 50;
  153. template <typename T>
  154. class TypeWithoutFormatter<T, kProtobuf> {
  155. public:
  156. static void PrintValue(const T& value, ::std::ostream* os) {
  157. std::string pretty_str = value.ShortDebugString();
  158. if (pretty_str.length() > kProtobufOneLinerMaxLength) {
  159. pretty_str = "\n" + value.DebugString();
  160. }
  161. *os << ("<" + pretty_str + ">");
  162. }
  163. };
  164. template <typename T>
  165. class TypeWithoutFormatter<T, kConvertibleToInteger> {
  166. public:
  167. // Since T has no << operator or PrintTo() but can be implicitly
  168. // converted to BiggestInt, we print it as a BiggestInt.
  169. //
  170. // Most likely T is an enum type (either named or unnamed), in which
  171. // case printing it as an integer is the desired behavior. In case
  172. // T is not an enum, printing it as an integer is the best we can do
  173. // given that it has no user-defined printer.
  174. static void PrintValue(const T& value, ::std::ostream* os) {
  175. const internal::BiggestInt kBigInt = value;
  176. *os << kBigInt;
  177. }
  178. };
  179. #if GTEST_HAS_ABSL
  180. template <typename T>
  181. class TypeWithoutFormatter<T, kConvertibleToStringView> {
  182. public:
  183. // Since T has neither operator<< nor PrintTo() but can be implicitly
  184. // converted to absl::string_view, we print it as a absl::string_view.
  185. //
  186. // Note: the implementation is further below, as it depends on
  187. // internal::PrintTo symbol which is defined later in the file.
  188. static void PrintValue(const T& value, ::std::ostream* os);
  189. };
  190. #endif
  191. // Prints the given value to the given ostream. If the value is a
  192. // protocol message, its debug string is printed; if it's an enum or
  193. // of a type implicitly convertible to BiggestInt, it's printed as an
  194. // integer; otherwise the bytes in the value are printed. This is
  195. // what UniversalPrinter<T>::Print() does when it knows nothing about
  196. // type T and T has neither << operator nor PrintTo().
  197. //
  198. // A user can override this behavior for a class type Foo by defining
  199. // a << operator in the namespace where Foo is defined.
  200. //
  201. // We put this operator in namespace 'internal2' instead of 'internal'
  202. // to simplify the implementation, as much code in 'internal' needs to
  203. // use << in STL, which would conflict with our own << were it defined
  204. // in 'internal'.
  205. //
  206. // Note that this operator<< takes a generic std::basic_ostream<Char,
  207. // CharTraits> type instead of the more restricted std::ostream. If
  208. // we define it to take an std::ostream instead, we'll get an
  209. // "ambiguous overloads" compiler error when trying to print a type
  210. // Foo that supports streaming to std::basic_ostream<Char,
  211. // CharTraits>, as the compiler cannot tell whether
  212. // operator<<(std::ostream&, const T&) or
  213. // operator<<(std::basic_stream<Char, CharTraits>, const Foo&) is more
  214. // specific.
  215. template <typename Char, typename CharTraits, typename T>
  216. ::std::basic_ostream<Char, CharTraits>& operator<<(
  217. ::std::basic_ostream<Char, CharTraits>& os, const T& x) {
  218. TypeWithoutFormatter<T, (internal::IsAProtocolMessage<T>::value
  219. ? kProtobuf
  220. : std::is_convertible<
  221. const T&, internal::BiggestInt>::value
  222. ? kConvertibleToInteger
  223. :
  224. #if GTEST_HAS_ABSL
  225. std::is_convertible<
  226. const T&, absl::string_view>::value
  227. ? kConvertibleToStringView
  228. :
  229. #endif
  230. kOtherType)>::PrintValue(x, &os);
  231. return os;
  232. }
  233. } // namespace internal2
  234. } // namespace testing
  235. // This namespace MUST NOT BE NESTED IN ::testing, or the name look-up
  236. // magic needed for implementing UniversalPrinter won't work.
  237. namespace testing_internal {
  238. // Used to print a value that is not an STL-style container when the
  239. // user doesn't define PrintTo() for it.
  240. template <typename T>
  241. void DefaultPrintNonContainerTo(const T& value, ::std::ostream* os) {
  242. // With the following statement, during unqualified name lookup,
  243. // testing::internal2::operator<< appears as if it was declared in
  244. // the nearest enclosing namespace that contains both
  245. // ::testing_internal and ::testing::internal2, i.e. the global
  246. // namespace. For more details, refer to the C++ Standard section
  247. // 7.3.4-1 [namespace.udir]. This allows us to fall back onto
  248. // testing::internal2::operator<< in case T doesn't come with a <<
  249. // operator.
  250. //
  251. // We cannot write 'using ::testing::internal2::operator<<;', which
  252. // gcc 3.3 fails to compile due to a compiler bug.
  253. using namespace ::testing::internal2; // NOLINT
  254. // Assuming T is defined in namespace foo, in the next statement,
  255. // the compiler will consider all of:
  256. //
  257. // 1. foo::operator<< (thanks to Koenig look-up),
  258. // 2. ::operator<< (as the current namespace is enclosed in ::),
  259. // 3. testing::internal2::operator<< (thanks to the using statement above).
  260. //
  261. // The operator<< whose type matches T best will be picked.
  262. //
  263. // We deliberately allow #2 to be a candidate, as sometimes it's
  264. // impossible to define #1 (e.g. when foo is ::std, defining
  265. // anything in it is undefined behavior unless you are a compiler
  266. // vendor.).
  267. *os << value;
  268. }
  269. } // namespace testing_internal
  270. namespace testing {
  271. namespace internal {
  272. // FormatForComparison<ToPrint, OtherOperand>::Format(value) formats a
  273. // value of type ToPrint that is an operand of a comparison assertion
  274. // (e.g. ASSERT_EQ). OtherOperand is the type of the other operand in
  275. // the comparison, and is used to help determine the best way to
  276. // format the value. In particular, when the value is a C string
  277. // (char pointer) and the other operand is an STL string object, we
  278. // want to format the C string as a string, since we know it is
  279. // compared by value with the string object. If the value is a char
  280. // pointer but the other operand is not an STL string object, we don't
  281. // know whether the pointer is supposed to point to a NUL-terminated
  282. // string, and thus want to print it as a pointer to be safe.
  283. //
  284. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  285. // The default case.
  286. template <typename ToPrint, typename OtherOperand>
  287. class FormatForComparison {
  288. public:
  289. static ::std::string Format(const ToPrint& value) {
  290. return ::testing::PrintToString(value);
  291. }
  292. };
  293. // Array.
  294. template <typename ToPrint, size_t N, typename OtherOperand>
  295. class FormatForComparison<ToPrint[N], OtherOperand> {
  296. public:
  297. static ::std::string Format(const ToPrint* value) {
  298. return FormatForComparison<const ToPrint*, OtherOperand>::Format(value);
  299. }
  300. };
  301. // By default, print C string as pointers to be safe, as we don't know
  302. // whether they actually point to a NUL-terminated string.
  303. #define GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(CharType) \
  304. template <typename OtherOperand> \
  305. class FormatForComparison<CharType*, OtherOperand> { \
  306. public: \
  307. static ::std::string Format(CharType* value) { \
  308. return ::testing::PrintToString(static_cast<const void*>(value)); \
  309. } \
  310. }
  311. GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char);
  312. GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char);
  313. GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(wchar_t);
  314. GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const wchar_t);
  315. #undef GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_
  316. // If a C string is compared with an STL string object, we know it's meant
  317. // to point to a NUL-terminated string, and thus can print it as a string.
  318. #define GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(CharType, OtherStringType) \
  319. template <> \
  320. class FormatForComparison<CharType*, OtherStringType> { \
  321. public: \
  322. static ::std::string Format(CharType* value) { \
  323. return ::testing::PrintToString(value); \
  324. } \
  325. }
  326. GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::std::string);
  327. GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char, ::std::string);
  328. #if GTEST_HAS_STD_WSTRING
  329. GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(wchar_t, ::std::wstring);
  330. GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const wchar_t, ::std::wstring);
  331. #endif
  332. #undef GTEST_IMPL_FORMAT_C_STRING_AS_STRING_
  333. // Formats a comparison assertion (e.g. ASSERT_EQ, EXPECT_LT, and etc)
  334. // operand to be used in a failure message. The type (but not value)
  335. // of the other operand may affect the format. This allows us to
  336. // print a char* as a raw pointer when it is compared against another
  337. // char* or void*, and print it as a C string when it is compared
  338. // against an std::string object, for example.
  339. //
  340. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
  341. template <typename T1, typename T2>
  342. std::string FormatForComparisonFailureMessage(
  343. const T1& value, const T2& /* other_operand */) {
  344. return FormatForComparison<T1, T2>::Format(value);
  345. }
  346. // UniversalPrinter<T>::Print(value, ostream_ptr) prints the given
  347. // value to the given ostream. The caller must ensure that
  348. // 'ostream_ptr' is not NULL, or the behavior is undefined.
  349. //
  350. // We define UniversalPrinter as a class template (as opposed to a
  351. // function template), as we need to partially specialize it for
  352. // reference types, which cannot be done with function templates.
  353. template <typename T>
  354. class UniversalPrinter;
  355. template <typename T>
  356. void UniversalPrint(const T& value, ::std::ostream* os);
  357. enum DefaultPrinterType {
  358. kPrintContainer,
  359. kPrintPointer,
  360. kPrintFunctionPointer,
  361. kPrintOther,
  362. };
  363. template <DefaultPrinterType type> struct WrapPrinterType {};
  364. // Used to print an STL-style container when the user doesn't define
  365. // a PrintTo() for it.
  366. template <typename C>
  367. void DefaultPrintTo(WrapPrinterType<kPrintContainer> /* dummy */,
  368. const C& container, ::std::ostream* os) {
  369. const size_t kMaxCount = 32; // The maximum number of elements to print.
  370. *os << '{';
  371. size_t count = 0;
  372. for (typename C::const_iterator it = container.begin();
  373. it != container.end(); ++it, ++count) {
  374. if (count > 0) {
  375. *os << ',';
  376. if (count == kMaxCount) { // Enough has been printed.
  377. *os << " ...";
  378. break;
  379. }
  380. }
  381. *os << ' ';
  382. // We cannot call PrintTo(*it, os) here as PrintTo() doesn't
  383. // handle *it being a native array.
  384. internal::UniversalPrint(*it, os);
  385. }
  386. if (count > 0) {
  387. *os << ' ';
  388. }
  389. *os << '}';
  390. }
  391. // Used to print a pointer that is neither a char pointer nor a member
  392. // pointer, when the user doesn't define PrintTo() for it. (A member
  393. // variable pointer or member function pointer doesn't really point to
  394. // a location in the address space. Their representation is
  395. // implementation-defined. Therefore they will be printed as raw
  396. // bytes.)
  397. template <typename T>
  398. void DefaultPrintTo(WrapPrinterType<kPrintPointer> /* dummy */,
  399. T* p, ::std::ostream* os) {
  400. if (p == nullptr) {
  401. *os << "NULL";
  402. } else {
  403. // T is not a function type. We just call << to print p,
  404. // relying on ADL to pick up user-defined << for their pointer
  405. // types, if any.
  406. *os << p;
  407. }
  408. }
  409. template <typename T>
  410. void DefaultPrintTo(WrapPrinterType<kPrintFunctionPointer> /* dummy */,
  411. T* p, ::std::ostream* os) {
  412. if (p == nullptr) {
  413. *os << "NULL";
  414. } else {
  415. // T is a function type, so '*os << p' doesn't do what we want
  416. // (it just prints p as bool). We want to print p as a const
  417. // void*.
  418. *os << reinterpret_cast<const void*>(p);
  419. }
  420. }
  421. // Used to print a non-container, non-pointer value when the user
  422. // doesn't define PrintTo() for it.
  423. template <typename T>
  424. void DefaultPrintTo(WrapPrinterType<kPrintOther> /* dummy */,
  425. const T& value, ::std::ostream* os) {
  426. ::testing_internal::DefaultPrintNonContainerTo(value, os);
  427. }
  428. // Prints the given value using the << operator if it has one;
  429. // otherwise prints the bytes in it. This is what
  430. // UniversalPrinter<T>::Print() does when PrintTo() is not specialized
  431. // or overloaded for type T.
  432. //
  433. // A user can override this behavior for a class type Foo by defining
  434. // an overload of PrintTo() in the namespace where Foo is defined. We
  435. // give the user this option as sometimes defining a << operator for
  436. // Foo is not desirable (e.g. the coding style may prevent doing it,
  437. // or there is already a << operator but it doesn't do what the user
  438. // wants).
  439. template <typename T>
  440. void PrintTo(const T& value, ::std::ostream* os) {
  441. // DefaultPrintTo() is overloaded. The type of its first argument
  442. // determines which version will be picked.
  443. //
  444. // Note that we check for container types here, prior to we check
  445. // for protocol message types in our operator<<. The rationale is:
  446. //
  447. // For protocol messages, we want to give people a chance to
  448. // override Google Mock's format by defining a PrintTo() or
  449. // operator<<. For STL containers, other formats can be
  450. // incompatible with Google Mock's format for the container
  451. // elements; therefore we check for container types here to ensure
  452. // that our format is used.
  453. //
  454. // Note that MSVC and clang-cl do allow an implicit conversion from
  455. // pointer-to-function to pointer-to-object, but clang-cl warns on it.
  456. // So don't use ImplicitlyConvertible if it can be helped since it will
  457. // cause this warning, and use a separate overload of DefaultPrintTo for
  458. // function pointers so that the `*os << p` in the object pointer overload
  459. // doesn't cause that warning either.
  460. DefaultPrintTo(
  461. WrapPrinterType <
  462. (sizeof(IsContainerTest<T>(0)) == sizeof(IsContainer)) &&
  463. !IsRecursiveContainer<T>::value
  464. ? kPrintContainer
  465. : !std::is_pointer<T>::value
  466. ? kPrintOther
  467. : std::is_function<typename std::remove_pointer<T>::type>::value
  468. ? kPrintFunctionPointer
  469. : kPrintPointer > (),
  470. value, os);
  471. }
  472. // The following list of PrintTo() overloads tells
  473. // UniversalPrinter<T>::Print() how to print standard types (built-in
  474. // types, strings, plain arrays, and pointers).
  475. // Overloads for various char types.
  476. GTEST_API_ void PrintTo(unsigned char c, ::std::ostream* os);
  477. GTEST_API_ void PrintTo(signed char c, ::std::ostream* os);
  478. inline void PrintTo(char c, ::std::ostream* os) {
  479. // When printing a plain char, we always treat it as unsigned. This
  480. // way, the output won't be affected by whether the compiler thinks
  481. // char is signed or not.
  482. PrintTo(static_cast<unsigned char>(c), os);
  483. }
  484. // Overloads for other simple built-in types.
  485. inline void PrintTo(bool x, ::std::ostream* os) {
  486. *os << (x ? "true" : "false");
  487. }
  488. // Overload for wchar_t type.
  489. // Prints a wchar_t as a symbol if it is printable or as its internal
  490. // code otherwise and also as its decimal code (except for L'\0').
  491. // The L'\0' char is printed as "L'\\0'". The decimal code is printed
  492. // as signed integer when wchar_t is implemented by the compiler
  493. // as a signed type and is printed as an unsigned integer when wchar_t
  494. // is implemented as an unsigned type.
  495. GTEST_API_ void PrintTo(wchar_t wc, ::std::ostream* os);
  496. // Overloads for C strings.
  497. GTEST_API_ void PrintTo(const char* s, ::std::ostream* os);
  498. inline void PrintTo(char* s, ::std::ostream* os) {
  499. PrintTo(ImplicitCast_<const char*>(s), os);
  500. }
  501. // signed/unsigned char is often used for representing binary data, so
  502. // we print pointers to it as void* to be safe.
  503. inline void PrintTo(const signed char* s, ::std::ostream* os) {
  504. PrintTo(ImplicitCast_<const void*>(s), os);
  505. }
  506. inline void PrintTo(signed char* s, ::std::ostream* os) {
  507. PrintTo(ImplicitCast_<const void*>(s), os);
  508. }
  509. inline void PrintTo(const unsigned char* s, ::std::ostream* os) {
  510. PrintTo(ImplicitCast_<const void*>(s), os);
  511. }
  512. inline void PrintTo(unsigned char* s, ::std::ostream* os) {
  513. PrintTo(ImplicitCast_<const void*>(s), os);
  514. }
  515. // MSVC can be configured to define wchar_t as a typedef of unsigned
  516. // short. It defines _NATIVE_WCHAR_T_DEFINED when wchar_t is a native
  517. // type. When wchar_t is a typedef, defining an overload for const
  518. // wchar_t* would cause unsigned short* be printed as a wide string,
  519. // possibly causing invalid memory accesses.
  520. #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
  521. // Overloads for wide C strings
  522. GTEST_API_ void PrintTo(const wchar_t* s, ::std::ostream* os);
  523. inline void PrintTo(wchar_t* s, ::std::ostream* os) {
  524. PrintTo(ImplicitCast_<const wchar_t*>(s), os);
  525. }
  526. #endif
  527. // Overload for C arrays. Multi-dimensional arrays are printed
  528. // properly.
  529. // Prints the given number of elements in an array, without printing
  530. // the curly braces.
  531. template <typename T>
  532. void PrintRawArrayTo(const T a[], size_t count, ::std::ostream* os) {
  533. UniversalPrint(a[0], os);
  534. for (size_t i = 1; i != count; i++) {
  535. *os << ", ";
  536. UniversalPrint(a[i], os);
  537. }
  538. }
  539. // Overloads for ::std::string.
  540. GTEST_API_ void PrintStringTo(const ::std::string&s, ::std::ostream* os);
  541. inline void PrintTo(const ::std::string& s, ::std::ostream* os) {
  542. PrintStringTo(s, os);
  543. }
  544. // Overloads for ::std::wstring.
  545. #if GTEST_HAS_STD_WSTRING
  546. GTEST_API_ void PrintWideStringTo(const ::std::wstring&s, ::std::ostream* os);
  547. inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) {
  548. PrintWideStringTo(s, os);
  549. }
  550. #endif // GTEST_HAS_STD_WSTRING
  551. #if GTEST_HAS_ABSL
  552. // Overload for absl::string_view.
  553. inline void PrintTo(absl::string_view sp, ::std::ostream* os) {
  554. PrintTo(::std::string(sp), os);
  555. }
  556. #endif // GTEST_HAS_ABSL
  557. inline void PrintTo(std::nullptr_t, ::std::ostream* os) { *os << "(nullptr)"; }
  558. template <typename T>
  559. void PrintTo(std::reference_wrapper<T> ref, ::std::ostream* os) {
  560. UniversalPrinter<T&>::Print(ref.get(), os);
  561. }
  562. // Helper function for printing a tuple. T must be instantiated with
  563. // a tuple type.
  564. template <typename T>
  565. void PrintTupleTo(const T&, std::integral_constant<size_t, 0>,
  566. ::std::ostream*) {}
  567. template <typename T, size_t I>
  568. void PrintTupleTo(const T& t, std::integral_constant<size_t, I>,
  569. ::std::ostream* os) {
  570. PrintTupleTo(t, std::integral_constant<size_t, I - 1>(), os);
  571. GTEST_INTENTIONAL_CONST_COND_PUSH_()
  572. if (I > 1) {
  573. GTEST_INTENTIONAL_CONST_COND_POP_()
  574. *os << ", ";
  575. }
  576. UniversalPrinter<typename std::tuple_element<I - 1, T>::type>::Print(
  577. std::get<I - 1>(t), os);
  578. }
  579. template <typename... Types>
  580. void PrintTo(const ::std::tuple<Types...>& t, ::std::ostream* os) {
  581. *os << "(";
  582. PrintTupleTo(t, std::integral_constant<size_t, sizeof...(Types)>(), os);
  583. *os << ")";
  584. }
  585. // Overload for std::pair.
  586. template <typename T1, typename T2>
  587. void PrintTo(const ::std::pair<T1, T2>& value, ::std::ostream* os) {
  588. *os << '(';
  589. // We cannot use UniversalPrint(value.first, os) here, as T1 may be
  590. // a reference type. The same for printing value.second.
  591. UniversalPrinter<T1>::Print(value.first, os);
  592. *os << ", ";
  593. UniversalPrinter<T2>::Print(value.second, os);
  594. *os << ')';
  595. }
  596. // Implements printing a non-reference type T by letting the compiler
  597. // pick the right overload of PrintTo() for T.
  598. template <typename T>
  599. class UniversalPrinter {
  600. public:
  601. // MSVC warns about adding const to a function type, so we want to
  602. // disable the warning.
  603. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180)
  604. // Note: we deliberately don't call this PrintTo(), as that name
  605. // conflicts with ::testing::internal::PrintTo in the body of the
  606. // function.
  607. static void Print(const T& value, ::std::ostream* os) {
  608. // By default, ::testing::internal::PrintTo() is used for printing
  609. // the value.
  610. //
  611. // Thanks to Koenig look-up, if T is a class and has its own
  612. // PrintTo() function defined in its namespace, that function will
  613. // be visible here. Since it is more specific than the generic ones
  614. // in ::testing::internal, it will be picked by the compiler in the
  615. // following statement - exactly what we want.
  616. PrintTo(value, os);
  617. }
  618. GTEST_DISABLE_MSC_WARNINGS_POP_()
  619. };
  620. #if GTEST_HAS_ABSL
  621. // Printer for absl::optional
  622. template <typename T>
  623. class UniversalPrinter<::absl::optional<T>> {
  624. public:
  625. static void Print(const ::absl::optional<T>& value, ::std::ostream* os) {
  626. *os << '(';
  627. if (!value) {
  628. *os << "nullopt";
  629. } else {
  630. UniversalPrint(*value, os);
  631. }
  632. *os << ')';
  633. }
  634. };
  635. // Printer for absl::variant
  636. template <typename... T>
  637. class UniversalPrinter<::absl::variant<T...>> {
  638. public:
  639. static void Print(const ::absl::variant<T...>& value, ::std::ostream* os) {
  640. *os << '(';
  641. absl::visit(Visitor{os}, value);
  642. *os << ')';
  643. }
  644. private:
  645. struct Visitor {
  646. template <typename U>
  647. void operator()(const U& u) const {
  648. *os << "'" << GetTypeName<U>() << "' with value ";
  649. UniversalPrint(u, os);
  650. }
  651. ::std::ostream* os;
  652. };
  653. };
  654. #endif // GTEST_HAS_ABSL
  655. // UniversalPrintArray(begin, len, os) prints an array of 'len'
  656. // elements, starting at address 'begin'.
  657. template <typename T>
  658. void UniversalPrintArray(const T* begin, size_t len, ::std::ostream* os) {
  659. if (len == 0) {
  660. *os << "{}";
  661. } else {
  662. *os << "{ ";
  663. const size_t kThreshold = 18;
  664. const size_t kChunkSize = 8;
  665. // If the array has more than kThreshold elements, we'll have to
  666. // omit some details by printing only the first and the last
  667. // kChunkSize elements.
  668. if (len <= kThreshold) {
  669. PrintRawArrayTo(begin, len, os);
  670. } else {
  671. PrintRawArrayTo(begin, kChunkSize, os);
  672. *os << ", ..., ";
  673. PrintRawArrayTo(begin + len - kChunkSize, kChunkSize, os);
  674. }
  675. *os << " }";
  676. }
  677. }
  678. // This overload prints a (const) char array compactly.
  679. GTEST_API_ void UniversalPrintArray(
  680. const char* begin, size_t len, ::std::ostream* os);
  681. // This overload prints a (const) wchar_t array compactly.
  682. GTEST_API_ void UniversalPrintArray(
  683. const wchar_t* begin, size_t len, ::std::ostream* os);
  684. // Implements printing an array type T[N].
  685. template <typename T, size_t N>
  686. class UniversalPrinter<T[N]> {
  687. public:
  688. // Prints the given array, omitting some elements when there are too
  689. // many.
  690. static void Print(const T (&a)[N], ::std::ostream* os) {
  691. UniversalPrintArray(a, N, os);
  692. }
  693. };
  694. // Implements printing a reference type T&.
  695. template <typename T>
  696. class UniversalPrinter<T&> {
  697. public:
  698. // MSVC warns about adding const to a function type, so we want to
  699. // disable the warning.
  700. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180)
  701. static void Print(const T& value, ::std::ostream* os) {
  702. // Prints the address of the value. We use reinterpret_cast here
  703. // as static_cast doesn't compile when T is a function type.
  704. *os << "@" << reinterpret_cast<const void*>(&value) << " ";
  705. // Then prints the value itself.
  706. UniversalPrint(value, os);
  707. }
  708. GTEST_DISABLE_MSC_WARNINGS_POP_()
  709. };
  710. // Prints a value tersely: for a reference type, the referenced value
  711. // (but not the address) is printed; for a (const) char pointer, the
  712. // NUL-terminated string (but not the pointer) is printed.
  713. template <typename T>
  714. class UniversalTersePrinter {
  715. public:
  716. static void Print(const T& value, ::std::ostream* os) {
  717. UniversalPrint(value, os);
  718. }
  719. };
  720. template <typename T>
  721. class UniversalTersePrinter<T&> {
  722. public:
  723. static void Print(const T& value, ::std::ostream* os) {
  724. UniversalPrint(value, os);
  725. }
  726. };
  727. template <typename T, size_t N>
  728. class UniversalTersePrinter<T[N]> {
  729. public:
  730. static void Print(const T (&value)[N], ::std::ostream* os) {
  731. UniversalPrinter<T[N]>::Print(value, os);
  732. }
  733. };
  734. template <>
  735. class UniversalTersePrinter<const char*> {
  736. public:
  737. static void Print(const char* str, ::std::ostream* os) {
  738. if (str == nullptr) {
  739. *os << "NULL";
  740. } else {
  741. UniversalPrint(std::string(str), os);
  742. }
  743. }
  744. };
  745. template <>
  746. class UniversalTersePrinter<char*> {
  747. public:
  748. static void Print(char* str, ::std::ostream* os) {
  749. UniversalTersePrinter<const char*>::Print(str, os);
  750. }
  751. };
  752. #if GTEST_HAS_STD_WSTRING
  753. template <>
  754. class UniversalTersePrinter<const wchar_t*> {
  755. public:
  756. static void Print(const wchar_t* str, ::std::ostream* os) {
  757. if (str == nullptr) {
  758. *os << "NULL";
  759. } else {
  760. UniversalPrint(::std::wstring(str), os);
  761. }
  762. }
  763. };
  764. #endif
  765. template <>
  766. class UniversalTersePrinter<wchar_t*> {
  767. public:
  768. static void Print(wchar_t* str, ::std::ostream* os) {
  769. UniversalTersePrinter<const wchar_t*>::Print(str, os);
  770. }
  771. };
  772. template <typename T>
  773. void UniversalTersePrint(const T& value, ::std::ostream* os) {
  774. UniversalTersePrinter<T>::Print(value, os);
  775. }
  776. // Prints a value using the type inferred by the compiler. The
  777. // difference between this and UniversalTersePrint() is that for a
  778. // (const) char pointer, this prints both the pointer and the
  779. // NUL-terminated string.
  780. template <typename T>
  781. void UniversalPrint(const T& value, ::std::ostream* os) {
  782. // A workarond for the bug in VC++ 7.1 that prevents us from instantiating
  783. // UniversalPrinter with T directly.
  784. typedef T T1;
  785. UniversalPrinter<T1>::Print(value, os);
  786. }
  787. typedef ::std::vector< ::std::string> Strings;
  788. // Tersely prints the first N fields of a tuple to a string vector,
  789. // one element for each field.
  790. template <typename Tuple>
  791. void TersePrintPrefixToStrings(const Tuple&, std::integral_constant<size_t, 0>,
  792. Strings*) {}
  793. template <typename Tuple, size_t I>
  794. void TersePrintPrefixToStrings(const Tuple& t,
  795. std::integral_constant<size_t, I>,
  796. Strings* strings) {
  797. TersePrintPrefixToStrings(t, std::integral_constant<size_t, I - 1>(),
  798. strings);
  799. ::std::stringstream ss;
  800. UniversalTersePrint(std::get<I - 1>(t), &ss);
  801. strings->push_back(ss.str());
  802. }
  803. // Prints the fields of a tuple tersely to a string vector, one
  804. // element for each field. See the comment before
  805. // UniversalTersePrint() for how we define "tersely".
  806. template <typename Tuple>
  807. Strings UniversalTersePrintTupleFieldsToStrings(const Tuple& value) {
  808. Strings result;
  809. TersePrintPrefixToStrings(
  810. value, std::integral_constant<size_t, std::tuple_size<Tuple>::value>(),
  811. &result);
  812. return result;
  813. }
  814. } // namespace internal
  815. #if GTEST_HAS_ABSL
  816. namespace internal2 {
  817. template <typename T>
  818. void TypeWithoutFormatter<T, kConvertibleToStringView>::PrintValue(
  819. const T& value, ::std::ostream* os) {
  820. internal::PrintTo(absl::string_view(value), os);
  821. }
  822. } // namespace internal2
  823. #endif
  824. template <typename T>
  825. ::std::string PrintToString(const T& value) {
  826. ::std::stringstream ss;
  827. internal::UniversalTersePrinter<T>::Print(value, &ss);
  828. return ss.str();
  829. }
  830. } // namespace testing
  831. // Include any custom printer added by the local installation.
  832. // We must include this header at the end to make sure it can use the
  833. // declarations from this file.
  834. #include "gtest/internal/custom/gtest-printers.h"
  835. #endif // GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_