gtest-printers.h 35 KB

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