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.

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