gtest-printers.h 36 KB

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