gtest-printers.cc 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  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. // It uses the << operator when possible, and prints the bytes in the
  37. // object otherwise. A user can override its behavior for a class
  38. // type Foo by defining either operator<<(::std::ostream&, const Foo&)
  39. // or void PrintTo(const Foo&, ::std::ostream*) in the namespace that
  40. // defines Foo.
  41. #include "gtest/gtest-printers.h"
  42. #include <stdio.h>
  43. #include <cctype>
  44. #include <cstdint>
  45. #include <cwchar>
  46. #include <iomanip>
  47. #include <ios>
  48. #include <ostream> // NOLINT
  49. #include <string>
  50. #include <type_traits>
  51. #include "gtest/internal/gtest-port.h"
  52. #include "src/gtest-internal-inl.h"
  53. namespace testing {
  54. namespace {
  55. using ::std::ostream;
  56. // Prints a segment of bytes in the given object.
  57. GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_
  58. GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
  59. GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
  60. GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_
  61. void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start,
  62. size_t count, ostream* os) {
  63. char text[5] = "";
  64. for (size_t i = 0; i != count; i++) {
  65. const size_t j = start + i;
  66. if (i != 0) {
  67. // Organizes the bytes into groups of 2 for easy parsing by
  68. // human.
  69. if ((j % 2) == 0)
  70. *os << ' ';
  71. else
  72. *os << '-';
  73. }
  74. GTEST_SNPRINTF_(text, sizeof(text), "%02X", obj_bytes[j]);
  75. *os << text;
  76. }
  77. }
  78. // Prints the bytes in the given value to the given ostream.
  79. void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,
  80. ostream* os) {
  81. // Tells the user how big the object is.
  82. *os << count << "-byte object <";
  83. const size_t kThreshold = 132;
  84. const size_t kChunkSize = 64;
  85. // If the object size is bigger than kThreshold, we'll have to omit
  86. // some details by printing only the first and the last kChunkSize
  87. // bytes.
  88. if (count < kThreshold) {
  89. PrintByteSegmentInObjectTo(obj_bytes, 0, count, os);
  90. } else {
  91. PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
  92. *os << " ... ";
  93. // Rounds up to 2-byte boundary.
  94. const size_t resume_pos = (count - kChunkSize + 1) / 2 * 2;
  95. PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);
  96. }
  97. *os << ">";
  98. }
  99. // Helpers for widening a character to char32_t. Since the standard does not
  100. // specify if char / wchar_t is signed or unsigned, it is important to first
  101. // convert it to the unsigned type of the same width before widening it to
  102. // char32_t.
  103. template <typename CharType>
  104. char32_t ToChar32(CharType in) {
  105. return static_cast<char32_t>(
  106. static_cast<typename std::make_unsigned<CharType>::type>(in));
  107. }
  108. } // namespace
  109. namespace internal {
  110. // Delegates to PrintBytesInObjectToImpl() to print the bytes in the
  111. // given object. The delegation simplifies the implementation, which
  112. // uses the << operator and thus is easier done outside of the
  113. // ::testing::internal namespace, which contains a << operator that
  114. // sometimes conflicts with the one in STL.
  115. void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,
  116. ostream* os) {
  117. PrintBytesInObjectToImpl(obj_bytes, count, os);
  118. }
  119. // Depending on the value of a char (or wchar_t), we print it in one
  120. // of three formats:
  121. // - as is if it's a printable ASCII (e.g. 'a', '2', ' '),
  122. // - as a hexadecimal escape sequence (e.g. '\x7F'), or
  123. // - as a special escape sequence (e.g. '\r', '\n').
  124. enum CharFormat { kAsIs, kHexEscape, kSpecialEscape };
  125. // Returns true if c is a printable ASCII character. We test the
  126. // value of c directly instead of calling isprint(), which is buggy on
  127. // Windows Mobile.
  128. inline bool IsPrintableAscii(char32_t c) { return 0x20 <= c && c <= 0x7E; }
  129. // Prints c (of type char, char8_t, char16_t, char32_t, or wchar_t) as a
  130. // character literal without the quotes, escaping it when necessary; returns how
  131. // c was formatted.
  132. template <typename Char>
  133. static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
  134. const char32_t u_c = ToChar32(c);
  135. switch (u_c) {
  136. case L'\0':
  137. *os << "\\0";
  138. break;
  139. case L'\'':
  140. *os << "\\'";
  141. break;
  142. case L'\\':
  143. *os << "\\\\";
  144. break;
  145. case L'\a':
  146. *os << "\\a";
  147. break;
  148. case L'\b':
  149. *os << "\\b";
  150. break;
  151. case L'\f':
  152. *os << "\\f";
  153. break;
  154. case L'\n':
  155. *os << "\\n";
  156. break;
  157. case L'\r':
  158. *os << "\\r";
  159. break;
  160. case L'\t':
  161. *os << "\\t";
  162. break;
  163. case L'\v':
  164. *os << "\\v";
  165. break;
  166. default:
  167. if (IsPrintableAscii(u_c)) {
  168. *os << static_cast<char>(c);
  169. return kAsIs;
  170. } else {
  171. ostream::fmtflags flags = os->flags();
  172. *os << "\\x" << std::hex << std::uppercase << static_cast<int>(u_c);
  173. os->flags(flags);
  174. return kHexEscape;
  175. }
  176. }
  177. return kSpecialEscape;
  178. }
  179. // Prints a char32_t c as if it's part of a string literal, escaping it when
  180. // necessary; returns how c was formatted.
  181. static CharFormat PrintAsStringLiteralTo(char32_t c, ostream* os) {
  182. switch (c) {
  183. case L'\'':
  184. *os << "'";
  185. return kAsIs;
  186. case L'"':
  187. *os << "\\\"";
  188. return kSpecialEscape;
  189. default:
  190. return PrintAsCharLiteralTo(c, os);
  191. }
  192. }
  193. static const char* GetCharWidthPrefix(char) { return ""; }
  194. static const char* GetCharWidthPrefix(signed char) { return ""; }
  195. static const char* GetCharWidthPrefix(unsigned char) { return ""; }
  196. #ifdef __cpp_lib_char8_t
  197. static const char* GetCharWidthPrefix(char8_t) { return "u8"; }
  198. #endif
  199. static const char* GetCharWidthPrefix(char16_t) { return "u"; }
  200. static const char* GetCharWidthPrefix(char32_t) { return "U"; }
  201. static const char* GetCharWidthPrefix(wchar_t) { return "L"; }
  202. // Prints a char c as if it's part of a string literal, escaping it when
  203. // necessary; returns how c was formatted.
  204. static CharFormat PrintAsStringLiteralTo(char c, ostream* os) {
  205. return PrintAsStringLiteralTo(ToChar32(c), os);
  206. }
  207. #ifdef __cpp_lib_char8_t
  208. static CharFormat PrintAsStringLiteralTo(char8_t c, ostream* os) {
  209. return PrintAsStringLiteralTo(ToChar32(c), os);
  210. }
  211. #endif
  212. static CharFormat PrintAsStringLiteralTo(char16_t c, ostream* os) {
  213. return PrintAsStringLiteralTo(ToChar32(c), os);
  214. }
  215. static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) {
  216. return PrintAsStringLiteralTo(ToChar32(c), os);
  217. }
  218. // Prints a character c (of type char, char8_t, char16_t, char32_t, or wchar_t)
  219. // and its code. '\0' is printed as "'\\0'", other unprintable characters are
  220. // also properly escaped using the standard C++ escape sequence.
  221. template <typename Char>
  222. void PrintCharAndCodeTo(Char c, ostream* os) {
  223. // First, print c as a literal in the most readable form we can find.
  224. *os << GetCharWidthPrefix(c) << "'";
  225. const CharFormat format = PrintAsCharLiteralTo(c, os);
  226. *os << "'";
  227. // To aid user debugging, we also print c's code in decimal, unless
  228. // it's 0 (in which case c was printed as '\\0', making the code
  229. // obvious).
  230. if (c == 0) return;
  231. *os << " (" << static_cast<int>(c);
  232. // For more convenience, we print c's code again in hexadecimal,
  233. // unless c was already printed in the form '\x##' or the code is in
  234. // [1, 9].
  235. if (format == kHexEscape || (1 <= c && c <= 9)) {
  236. // Do nothing.
  237. } else {
  238. *os << ", 0x" << String::FormatHexInt(static_cast<int>(c));
  239. }
  240. *os << ")";
  241. }
  242. void PrintTo(unsigned char c, ::std::ostream* os) { PrintCharAndCodeTo(c, os); }
  243. void PrintTo(signed char c, ::std::ostream* os) { PrintCharAndCodeTo(c, os); }
  244. // Prints a wchar_t as a symbol if it is printable or as its internal
  245. // code otherwise and also as its code. L'\0' is printed as "L'\\0'".
  246. void PrintTo(wchar_t wc, ostream* os) { PrintCharAndCodeTo(wc, os); }
  247. // TODO(dcheng): Consider making this delegate to PrintCharAndCodeTo() as well.
  248. void PrintTo(char32_t c, ::std::ostream* os) {
  249. *os << std::hex << "U+" << std::uppercase << std::setfill('0') << std::setw(4)
  250. << static_cast<uint32_t>(c);
  251. }
  252. // gcc/clang __{u,}int128_t
  253. #if defined(__SIZEOF_INT128__)
  254. void PrintTo(__uint128_t v, ::std::ostream* os) {
  255. if (v == 0) {
  256. *os << "0";
  257. return;
  258. }
  259. // Buffer large enough for ceil(log10(2^128))==39 and the null terminator
  260. char buf[40];
  261. char* p = buf + sizeof(buf);
  262. // Some configurations have a __uint128_t, but no support for built in
  263. // division. Do manual long division instead.
  264. uint64_t high = static_cast<uint64_t>(v >> 64);
  265. uint64_t low = static_cast<uint64_t>(v);
  266. *--p = 0;
  267. while (high != 0 || low != 0) {
  268. uint64_t high_mod = high % 10;
  269. high = high / 10;
  270. // This is the long division algorithm specialized for a divisor of 10 and
  271. // only two elements.
  272. // Notable values:
  273. // 2^64 / 10 == 1844674407370955161
  274. // 2^64 % 10 == 6
  275. const uint64_t carry = 6 * high_mod + low % 10;
  276. low = low / 10 + high_mod * 1844674407370955161 + carry / 10;
  277. char digit = static_cast<char>(carry % 10);
  278. *--p = static_cast<char>('0' + digit);
  279. }
  280. *os << p;
  281. }
  282. void PrintTo(__int128_t v, ::std::ostream* os) {
  283. __uint128_t uv = static_cast<__uint128_t>(v);
  284. if (v < 0) {
  285. *os << "-";
  286. uv = -uv;
  287. }
  288. PrintTo(uv, os);
  289. }
  290. #endif // __SIZEOF_INT128__
  291. // Prints the given array of characters to the ostream. CharType must be either
  292. // char, char8_t, char16_t, char32_t, or wchar_t.
  293. // The array starts at begin, the length is len, it may include '\0' characters
  294. // and may not be NUL-terminated.
  295. template <typename CharType>
  296. GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
  297. GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
  298. GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ static CharFormat
  299. PrintCharsAsStringTo(const CharType* begin, size_t len, ostream* os) {
  300. const char* const quote_prefix = GetCharWidthPrefix(*begin);
  301. *os << quote_prefix << "\"";
  302. bool is_previous_hex = false;
  303. CharFormat print_format = kAsIs;
  304. for (size_t index = 0; index < len; ++index) {
  305. const CharType cur = begin[index];
  306. if (is_previous_hex && IsXDigit(cur)) {
  307. // Previous character is of '\x..' form and this character can be
  308. // interpreted as another hexadecimal digit in its number. Break string to
  309. // disambiguate.
  310. *os << "\" " << quote_prefix << "\"";
  311. }
  312. is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape;
  313. // Remember if any characters required hex escaping.
  314. if (is_previous_hex) {
  315. print_format = kHexEscape;
  316. }
  317. }
  318. *os << "\"";
  319. return print_format;
  320. }
  321. // Prints a (const) char/wchar_t array of 'len' elements, starting at address
  322. // 'begin'. CharType must be either char or wchar_t.
  323. template <typename CharType>
  324. GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_
  325. GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_
  326. GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ static void
  327. UniversalPrintCharArray(const CharType* begin, size_t len,
  328. ostream* os) {
  329. // The code
  330. // const char kFoo[] = "foo";
  331. // generates an array of 4, not 3, elements, with the last one being '\0'.
  332. //
  333. // Therefore when printing a char array, we don't print the last element if
  334. // it's '\0', such that the output matches the string literal as it's
  335. // written in the source code.
  336. if (len > 0 && begin[len - 1] == '\0') {
  337. PrintCharsAsStringTo(begin, len - 1, os);
  338. return;
  339. }
  340. // If, however, the last element in the array is not '\0', e.g.
  341. // const char kFoo[] = { 'f', 'o', 'o' };
  342. // we must print the entire array. We also print a message to indicate
  343. // that the array is not NUL-terminated.
  344. PrintCharsAsStringTo(begin, len, os);
  345. *os << " (no terminating NUL)";
  346. }
  347. // Prints a (const) char array of 'len' elements, starting at address 'begin'.
  348. void UniversalPrintArray(const char* begin, size_t len, ostream* os) {
  349. UniversalPrintCharArray(begin, len, os);
  350. }
  351. #ifdef __cpp_lib_char8_t
  352. // Prints a (const) char8_t array of 'len' elements, starting at address
  353. // 'begin'.
  354. void UniversalPrintArray(const char8_t* begin, size_t len, ostream* os) {
  355. UniversalPrintCharArray(begin, len, os);
  356. }
  357. #endif
  358. // Prints a (const) char16_t array of 'len' elements, starting at address
  359. // 'begin'.
  360. void UniversalPrintArray(const char16_t* begin, size_t len, ostream* os) {
  361. UniversalPrintCharArray(begin, len, os);
  362. }
  363. // Prints a (const) char32_t array of 'len' elements, starting at address
  364. // 'begin'.
  365. void UniversalPrintArray(const char32_t* begin, size_t len, ostream* os) {
  366. UniversalPrintCharArray(begin, len, os);
  367. }
  368. // Prints a (const) wchar_t array of 'len' elements, starting at address
  369. // 'begin'.
  370. void UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) {
  371. UniversalPrintCharArray(begin, len, os);
  372. }
  373. namespace {
  374. // Prints a null-terminated C-style string to the ostream.
  375. template <typename Char>
  376. void PrintCStringTo(const Char* s, ostream* os) {
  377. if (s == nullptr) {
  378. *os << "NULL";
  379. } else {
  380. *os << ImplicitCast_<const void*>(s) << " pointing to ";
  381. PrintCharsAsStringTo(s, std::char_traits<Char>::length(s), os);
  382. }
  383. }
  384. } // anonymous namespace
  385. void PrintTo(const char* s, ostream* os) { PrintCStringTo(s, os); }
  386. #ifdef __cpp_lib_char8_t
  387. void PrintTo(const char8_t* s, ostream* os) { PrintCStringTo(s, os); }
  388. #endif
  389. void PrintTo(const char16_t* s, ostream* os) { PrintCStringTo(s, os); }
  390. void PrintTo(const char32_t* s, ostream* os) { PrintCStringTo(s, os); }
  391. // MSVC compiler can be configured to define whar_t as a typedef
  392. // of unsigned short. Defining an overload for const wchar_t* in that case
  393. // would cause pointers to unsigned shorts be printed as wide strings,
  394. // possibly accessing more memory than intended and causing invalid
  395. // memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
  396. // wchar_t is implemented as a native type.
  397. #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
  398. // Prints the given wide C string to the ostream.
  399. void PrintTo(const wchar_t* s, ostream* os) { PrintCStringTo(s, os); }
  400. #endif // wchar_t is native
  401. namespace {
  402. bool ContainsUnprintableControlCodes(const char* str, size_t length) {
  403. const unsigned char* s = reinterpret_cast<const unsigned char*>(str);
  404. for (size_t i = 0; i < length; i++) {
  405. unsigned char ch = *s++;
  406. if (std::iscntrl(ch)) {
  407. switch (ch) {
  408. case '\t':
  409. case '\n':
  410. case '\r':
  411. break;
  412. default:
  413. return true;
  414. }
  415. }
  416. }
  417. return false;
  418. }
  419. bool IsUTF8TrailByte(unsigned char t) { return 0x80 <= t && t <= 0xbf; }
  420. bool IsValidUTF8(const char* str, size_t length) {
  421. const unsigned char* s = reinterpret_cast<const unsigned char*>(str);
  422. for (size_t i = 0; i < length;) {
  423. unsigned char lead = s[i++];
  424. if (lead <= 0x7f) {
  425. continue; // single-byte character (ASCII) 0..7F
  426. }
  427. if (lead < 0xc2) {
  428. return false; // trail byte or non-shortest form
  429. } else if (lead <= 0xdf && (i + 1) <= length && IsUTF8TrailByte(s[i])) {
  430. ++i; // 2-byte character
  431. } else if (0xe0 <= lead && lead <= 0xef && (i + 2) <= length &&
  432. IsUTF8TrailByte(s[i]) && IsUTF8TrailByte(s[i + 1]) &&
  433. // check for non-shortest form and surrogate
  434. (lead != 0xe0 || s[i] >= 0xa0) &&
  435. (lead != 0xed || s[i] < 0xa0)) {
  436. i += 2; // 3-byte character
  437. } else if (0xf0 <= lead && lead <= 0xf4 && (i + 3) <= length &&
  438. IsUTF8TrailByte(s[i]) && IsUTF8TrailByte(s[i + 1]) &&
  439. IsUTF8TrailByte(s[i + 2]) &&
  440. // check for non-shortest form
  441. (lead != 0xf0 || s[i] >= 0x90) &&
  442. (lead != 0xf4 || s[i] < 0x90)) {
  443. i += 3; // 4-byte character
  444. } else {
  445. return false;
  446. }
  447. }
  448. return true;
  449. }
  450. void ConditionalPrintAsText(const char* str, size_t length, ostream* os) {
  451. if (!ContainsUnprintableControlCodes(str, length) &&
  452. IsValidUTF8(str, length)) {
  453. *os << "\n As Text: \"" << str << "\"";
  454. }
  455. }
  456. } // anonymous namespace
  457. void PrintStringTo(const ::std::string& s, ostream* os) {
  458. if (PrintCharsAsStringTo(s.data(), s.size(), os) == kHexEscape) {
  459. if (GTEST_FLAG_GET(print_utf8)) {
  460. ConditionalPrintAsText(s.data(), s.size(), os);
  461. }
  462. }
  463. }
  464. #ifdef __cpp_lib_char8_t
  465. void PrintU8StringTo(const ::std::u8string& s, ostream* os) {
  466. PrintCharsAsStringTo(s.data(), s.size(), os);
  467. }
  468. #endif
  469. void PrintU16StringTo(const ::std::u16string& s, ostream* os) {
  470. PrintCharsAsStringTo(s.data(), s.size(), os);
  471. }
  472. void PrintU32StringTo(const ::std::u32string& s, ostream* os) {
  473. PrintCharsAsStringTo(s.data(), s.size(), os);
  474. }
  475. #if GTEST_HAS_STD_WSTRING
  476. void PrintWideStringTo(const ::std::wstring& s, ostream* os) {
  477. PrintCharsAsStringTo(s.data(), s.size(), os);
  478. }
  479. #endif // GTEST_HAS_STD_WSTRING
  480. } // namespace internal
  481. } // namespace testing