You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

363 lines
12 KiB

  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. //
  30. // Author: wan@google.com (Zhanyong Wan)
  31. // Google Test - The Google C++ Testing Framework
  32. //
  33. // This file implements a universal value printer that can print a
  34. // value of any type T:
  35. //
  36. // void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
  37. //
  38. // It uses the << operator when possible, and prints the bytes in the
  39. // object otherwise. A user can override its behavior for a class
  40. // type Foo by defining either operator<<(::std::ostream&, const Foo&)
  41. // or void PrintTo(const Foo&, ::std::ostream*) in the namespace that
  42. // defines Foo.
  43. #include "gtest/gtest-printers.h"
  44. #include <ctype.h>
  45. #include <stdio.h>
  46. #include <ostream> // NOLINT
  47. #include <string>
  48. #include "gtest/internal/gtest-port.h"
  49. namespace testing {
  50. namespace {
  51. using ::std::ostream;
  52. // Prints a segment of bytes in the given object.
  53. void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start,
  54. size_t count, ostream* os) {
  55. char text[5] = "";
  56. for (size_t i = 0; i != count; i++) {
  57. const size_t j = start + i;
  58. if (i != 0) {
  59. // Organizes the bytes into groups of 2 for easy parsing by
  60. // human.
  61. if ((j % 2) == 0)
  62. *os << ' ';
  63. else
  64. *os << '-';
  65. }
  66. GTEST_SNPRINTF_(text, sizeof(text), "%02X", obj_bytes[j]);
  67. *os << text;
  68. }
  69. }
  70. // Prints the bytes in the given value to the given ostream.
  71. void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,
  72. ostream* os) {
  73. // Tells the user how big the object is.
  74. *os << count << "-byte object <";
  75. const size_t kThreshold = 132;
  76. const size_t kChunkSize = 64;
  77. // If the object size is bigger than kThreshold, we'll have to omit
  78. // some details by printing only the first and the last kChunkSize
  79. // bytes.
  80. // TODO(wan): let the user control the threshold using a flag.
  81. if (count < kThreshold) {
  82. PrintByteSegmentInObjectTo(obj_bytes, 0, count, os);
  83. } else {
  84. PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);
  85. *os << " ... ";
  86. // Rounds up to 2-byte boundary.
  87. const size_t resume_pos = (count - kChunkSize + 1)/2*2;
  88. PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);
  89. }
  90. *os << ">";
  91. }
  92. } // namespace
  93. namespace internal2 {
  94. // Delegates to PrintBytesInObjectToImpl() to print the bytes in the
  95. // given object. The delegation simplifies the implementation, which
  96. // uses the << operator and thus is easier done outside of the
  97. // ::testing::internal namespace, which contains a << operator that
  98. // sometimes conflicts with the one in STL.
  99. void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,
  100. ostream* os) {
  101. PrintBytesInObjectToImpl(obj_bytes, count, os);
  102. }
  103. } // namespace internal2
  104. namespace internal {
  105. // Depending on the value of a char (or wchar_t), we print it in one
  106. // of three formats:
  107. // - as is if it's a printable ASCII (e.g. 'a', '2', ' '),
  108. // - as a hexidecimal escape sequence (e.g. '\x7F'), or
  109. // - as a special escape sequence (e.g. '\r', '\n').
  110. enum CharFormat {
  111. kAsIs,
  112. kHexEscape,
  113. kSpecialEscape
  114. };
  115. // Returns true if c is a printable ASCII character. We test the
  116. // value of c directly instead of calling isprint(), which is buggy on
  117. // Windows Mobile.
  118. inline bool IsPrintableAscii(wchar_t c) {
  119. return 0x20 <= c && c <= 0x7E;
  120. }
  121. // Prints a wide or narrow char c as a character literal without the
  122. // quotes, escaping it when necessary; returns how c was formatted.
  123. // The template argument UnsignedChar is the unsigned version of Char,
  124. // which is the type of c.
  125. template <typename UnsignedChar, typename Char>
  126. static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {
  127. switch (static_cast<wchar_t>(c)) {
  128. case L'\0':
  129. *os << "\\0";
  130. break;
  131. case L'\'':
  132. *os << "\\'";
  133. break;
  134. case L'\\':
  135. *os << "\\\\";
  136. break;
  137. case L'\a':
  138. *os << "\\a";
  139. break;
  140. case L'\b':
  141. *os << "\\b";
  142. break;
  143. case L'\f':
  144. *os << "\\f";
  145. break;
  146. case L'\n':
  147. *os << "\\n";
  148. break;
  149. case L'\r':
  150. *os << "\\r";
  151. break;
  152. case L'\t':
  153. *os << "\\t";
  154. break;
  155. case L'\v':
  156. *os << "\\v";
  157. break;
  158. default:
  159. if (IsPrintableAscii(c)) {
  160. *os << static_cast<char>(c);
  161. return kAsIs;
  162. } else {
  163. *os << "\\x" + String::FormatHexInt(static_cast<UnsignedChar>(c));
  164. return kHexEscape;
  165. }
  166. }
  167. return kSpecialEscape;
  168. }
  169. // Prints a wchar_t c as if it's part of a string literal, escaping it when
  170. // necessary; returns how c was formatted.
  171. static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) {
  172. switch (c) {
  173. case L'\'':
  174. *os << "'";
  175. return kAsIs;
  176. case L'"':
  177. *os << "\\\"";
  178. return kSpecialEscape;
  179. default:
  180. return PrintAsCharLiteralTo<wchar_t>(c, os);
  181. }
  182. }
  183. // Prints a char c as if it's part of a string literal, escaping it when
  184. // necessary; returns how c was formatted.
  185. static CharFormat PrintAsStringLiteralTo(char c, ostream* os) {
  186. return PrintAsStringLiteralTo(
  187. static_cast<wchar_t>(static_cast<unsigned char>(c)), os);
  188. }
  189. // Prints a wide or narrow character c and its code. '\0' is printed
  190. // as "'\\0'", other unprintable characters are also properly escaped
  191. // using the standard C++ escape sequence. The template argument
  192. // UnsignedChar is the unsigned version of Char, which is the type of c.
  193. template <typename UnsignedChar, typename Char>
  194. void PrintCharAndCodeTo(Char c, ostream* os) {
  195. // First, print c as a literal in the most readable form we can find.
  196. *os << ((sizeof(c) > 1) ? "L'" : "'");
  197. const CharFormat format = PrintAsCharLiteralTo<UnsignedChar>(c, os);
  198. *os << "'";
  199. // To aid user debugging, we also print c's code in decimal, unless
  200. // it's 0 (in which case c was printed as '\\0', making the code
  201. // obvious).
  202. if (c == 0)
  203. return;
  204. *os << " (" << static_cast<int>(c);
  205. // For more convenience, we print c's code again in hexidecimal,
  206. // unless c was already printed in the form '\x##' or the code is in
  207. // [1, 9].
  208. if (format == kHexEscape || (1 <= c && c <= 9)) {
  209. // Do nothing.
  210. } else {
  211. *os << ", 0x" << String::FormatHexInt(static_cast<UnsignedChar>(c));
  212. }
  213. *os << ")";
  214. }
  215. void PrintTo(unsigned char c, ::std::ostream* os) {
  216. PrintCharAndCodeTo<unsigned char>(c, os);
  217. }
  218. void PrintTo(signed char c, ::std::ostream* os) {
  219. PrintCharAndCodeTo<unsigned char>(c, os);
  220. }
  221. // Prints a wchar_t as a symbol if it is printable or as its internal
  222. // code otherwise and also as its code. L'\0' is printed as "L'\\0'".
  223. void PrintTo(wchar_t wc, ostream* os) {
  224. PrintCharAndCodeTo<wchar_t>(wc, os);
  225. }
  226. // Prints the given array of characters to the ostream. CharType must be either
  227. // char or wchar_t.
  228. // The array starts at begin, the length is len, it may include '\0' characters
  229. // and may not be NUL-terminated.
  230. template <typename CharType>
  231. static void PrintCharsAsStringTo(
  232. const CharType* begin, size_t len, ostream* os) {
  233. const char* const kQuoteBegin = sizeof(CharType) == 1 ? "\"" : "L\"";
  234. *os << kQuoteBegin;
  235. bool is_previous_hex = false;
  236. for (size_t index = 0; index < len; ++index) {
  237. const CharType cur = begin[index];
  238. if (is_previous_hex && IsXDigit(cur)) {
  239. // Previous character is of '\x..' form and this character can be
  240. // interpreted as another hexadecimal digit in its number. Break string to
  241. // disambiguate.
  242. *os << "\" " << kQuoteBegin;
  243. }
  244. is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape;
  245. }
  246. *os << "\"";
  247. }
  248. // Prints a (const) char/wchar_t array of 'len' elements, starting at address
  249. // 'begin'. CharType must be either char or wchar_t.
  250. template <typename CharType>
  251. static void UniversalPrintCharArray(
  252. const CharType* begin, size_t len, ostream* os) {
  253. // The code
  254. // const char kFoo[] = "foo";
  255. // generates an array of 4, not 3, elements, with the last one being '\0'.
  256. //
  257. // Therefore when printing a char array, we don't print the last element if
  258. // it's '\0', such that the output matches the string literal as it's
  259. // written in the source code.
  260. if (len > 0 && begin[len - 1] == '\0') {
  261. PrintCharsAsStringTo(begin, len - 1, os);
  262. return;
  263. }
  264. // If, however, the last element in the array is not '\0', e.g.
  265. // const char kFoo[] = { 'f', 'o', 'o' };
  266. // we must print the entire array. We also print a message to indicate
  267. // that the array is not NUL-terminated.
  268. PrintCharsAsStringTo(begin, len, os);
  269. *os << " (no terminating NUL)";
  270. }
  271. // Prints a (const) char array of 'len' elements, starting at address 'begin'.
  272. void UniversalPrintArray(const char* begin, size_t len, ostream* os) {
  273. UniversalPrintCharArray(begin, len, os);
  274. }
  275. // Prints a (const) wchar_t array of 'len' elements, starting at address
  276. // 'begin'.
  277. void UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) {
  278. UniversalPrintCharArray(begin, len, os);
  279. }
  280. // Prints the given C string to the ostream.
  281. void PrintTo(const char* s, ostream* os) {
  282. if (s == NULL) {
  283. *os << "NULL";
  284. } else {
  285. *os << ImplicitCast_<const void*>(s) << " pointing to ";
  286. PrintCharsAsStringTo(s, strlen(s), os);
  287. }
  288. }
  289. // MSVC compiler can be configured to define whar_t as a typedef
  290. // of unsigned short. Defining an overload for const wchar_t* in that case
  291. // would cause pointers to unsigned shorts be printed as wide strings,
  292. // possibly accessing more memory than intended and causing invalid
  293. // memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
  294. // wchar_t is implemented as a native type.
  295. #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
  296. // Prints the given wide C string to the ostream.
  297. void PrintTo(const wchar_t* s, ostream* os) {
  298. if (s == NULL) {
  299. *os << "NULL";
  300. } else {
  301. *os << ImplicitCast_<const void*>(s) << " pointing to ";
  302. PrintCharsAsStringTo(s, wcslen(s), os);
  303. }
  304. }
  305. #endif // wchar_t is native
  306. // Prints a ::string object.
  307. #if GTEST_HAS_GLOBAL_STRING
  308. void PrintStringTo(const ::string& s, ostream* os) {
  309. PrintCharsAsStringTo(s.data(), s.size(), os);
  310. }
  311. #endif // GTEST_HAS_GLOBAL_STRING
  312. void PrintStringTo(const ::std::string& s, ostream* os) {
  313. PrintCharsAsStringTo(s.data(), s.size(), os);
  314. }
  315. // Prints a ::wstring object.
  316. #if GTEST_HAS_GLOBAL_WSTRING
  317. void PrintWideStringTo(const ::wstring& s, ostream* os) {
  318. PrintCharsAsStringTo(s.data(), s.size(), os);
  319. }
  320. #endif // GTEST_HAS_GLOBAL_WSTRING
  321. #if GTEST_HAS_STD_WSTRING
  322. void PrintWideStringTo(const ::std::wstring& s, ostream* os) {
  323. PrintCharsAsStringTo(s.data(), s.size(), os);
  324. }
  325. #endif // GTEST_HAS_STD_WSTRING
  326. } // namespace internal
  327. } // namespace testing