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