gtest-printers.cc 17 KB

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