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