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 // A user can teach this function how to print a class type T by
40 // defining either operator<<() or PrintTo() in the namespace that
41 // defines T.  More specifically, the FIRST defined function in the
42 // following list will be used (assuming T is defined in namespace
43 // foo):
44 //
45 //   1. foo::PrintTo(const T&, ostream*)
46 //   2. operator<<(ostream&, const T&) defined in either foo or the
47 //      global namespace.
48 //
49 // If none of the above is defined, it will print the debug string of
50 // the value if it is a protocol buffer, or print the raw bytes in the
51 // value otherwise.
52 //
53 // To aid debugging: when T is a reference type, the address of the
54 // value is also printed; when T is a (const) char pointer, both the
55 // pointer value and the NUL-terminated string it points to are
56 // printed.
57 //
58 // We also provide some convenient wrappers:
59 //
60 //   // Prints a value to a string.  For a (const or not) char
61 //   // pointer, the NUL-terminated string (but not the pointer) is
62 //   // printed.
63 //   std::string ::testing::PrintToString(const T& value);
64 //
65 //   // Prints a value tersely: for a reference type, the referenced
66 //   // value (but not the address) is printed; for a (const or not) char
67 //   // pointer, the NUL-terminated string (but not the pointer) is
68 //   // printed.
69 //   void ::testing::internal::UniversalTersePrint(const T& value, ostream*);
70 //
71 //   // Prints value using the type inferred by the compiler.  The difference
72 //   // from UniversalTersePrint() is that this function prints both the
73 //   // pointer and the NUL-terminated string for a (const or not) char pointer.
74 //   void ::testing::internal::UniversalPrint(const T& value, ostream*);
75 //
76 //   // Prints the fields of a tuple tersely to a string vector, one
77 //   // element for each field. Tuple support must be enabled in
78 //   // gtest-port.h.
79 //   std::vector<string> UniversalTersePrintTupleFieldsToStrings(
80 //       const Tuple& value);
81 //
82 // Known limitation:
83 //
84 // The print primitives print the elements of an STL-style container
85 // using the compiler-inferred type of *iter where iter is a
86 // const_iterator of the container.  When const_iterator is an input
87 // iterator but not a forward iterator, this inferred type may not
88 // match value_type, and the print output may be incorrect.  In
89 // practice, this is rarely a problem as for most containers
90 // const_iterator is a forward iterator.  We'll fix this if there's an
91 // actual need for it.  Note that this fix cannot rely on value_type
92 // being defined as many user-defined container types don't have
93 // value_type.
94 
95 #ifndef GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
96 #define GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
97 
98 #include <ostream>  // NOLINT
99 #include <sstream>
100 #include <string>
101 #include <utility>
102 #include <vector>
103 #include "gtest/internal/gtest-port.h"
104 #include "gtest/internal/gtest-internal.h"
105 
106 #if GTEST_HAS_STD_TUPLE_
107 # include <tuple>
108 #endif
109 
110 namespace testing {
111 
112 // Definitions in the 'internal' and 'internal2' name spaces are
113 // subject to change without notice.  DO NOT USE THEM IN USER CODE!
114 namespace internal2 {
115 
116 // Prints the given number of bytes in the given object to the given
117 // ostream.
118 GTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes,
119                                      size_t count,
120                                      ::std::ostream* os);
121 
122 // For selecting which printer to use when a given type has neither <<
123 // nor PrintTo().
124 enum TypeKind {
125   kProtobuf,              // a protobuf type
126   kConvertibleToInteger,  // a type implicitly convertible to BiggestInt
127                           // (e.g. a named or unnamed enum type)
128   kOtherType              // anything else
129 };
130 
131 // TypeWithoutFormatter<T, kTypeKind>::PrintValue(value, os) is called
132 // by the universal printer to print a value of type T when neither
133 // operator<< nor PrintTo() is defined for T, where kTypeKind is the
134 // "kind" of T as defined by enum TypeKind.
135 template <typename T, TypeKind kTypeKind>
136 class TypeWithoutFormatter {
137  public:
138   // This default version is called when kTypeKind is kOtherType.
PrintValue(const T & value,::std::ostream * os)139   static void PrintValue(const T& value, ::std::ostream* os) {
140     PrintBytesInObjectTo(reinterpret_cast<const unsigned char*>(&value),
141                          sizeof(value), os);
142   }
143 };
144 
145 // We print a protobuf using its ShortDebugString() when the string
146 // doesn't exceed this many characters; otherwise we print it using
147 // DebugString() for better readability.
148 const size_t kProtobufOneLinerMaxLength = 50;
149 
150 template <typename T>
151 class TypeWithoutFormatter<T, kProtobuf> {
152  public:
PrintValue(const T & value,::std::ostream * os)153   static void PrintValue(const T& value, ::std::ostream* os) {
154     const ::testing::internal::string short_str = value.ShortDebugString();
155     const ::testing::internal::string pretty_str =
156         short_str.length() <= kProtobufOneLinerMaxLength ?
157         short_str : ("\n" + value.DebugString());
158     *os << ("<" + pretty_str + ">");
159   }
160 };
161 
162 template <typename T>
163 class TypeWithoutFormatter<T, kConvertibleToInteger> {
164  public:
165   // Since T has no << operator or PrintTo() but can be implicitly
166   // converted to BiggestInt, we print it as a BiggestInt.
167   //
168   // Most likely T is an enum type (either named or unnamed), in which
169   // case printing it as an integer is the desired behavior.  In case
170   // T is not an enum, printing it as an integer is the best we can do
171   // given that it has no user-defined printer.
PrintValue(const T & value,::std::ostream * os)172   static void PrintValue(const T& value, ::std::ostream* os) {
173     const internal::BiggestInt kBigInt = value;
174     *os << kBigInt;
175   }
176 };
177 
178 // Prints the given value to the given ostream.  If the value is a
179 // protocol message, its debug string is printed; if it's an enum or
180 // of a type implicitly convertible to BiggestInt, it's printed as an
181 // integer; otherwise the bytes in the value are printed.  This is
182 // what UniversalPrinter<T>::Print() does when it knows nothing about
183 // type T and T has neither << operator nor PrintTo().
184 //
185 // A user can override this behavior for a class type Foo by defining
186 // a << operator in the namespace where Foo is defined.
187 //
188 // We put this operator in namespace 'internal2' instead of 'internal'
189 // to simplify the implementation, as much code in 'internal' needs to
190 // use << in STL, which would conflict with our own << were it defined
191 // in 'internal'.
192 //
193 // Note that this operator<< takes a generic std::basic_ostream<Char,
194 // CharTraits> type instead of the more restricted std::ostream.  If
195 // we define it to take an std::ostream instead, we'll get an
196 // "ambiguous overloads" compiler error when trying to print a type
197 // Foo that supports streaming to std::basic_ostream<Char,
198 // CharTraits>, as the compiler cannot tell whether
199 // operator<<(std::ostream&, const T&) or
200 // operator<<(std::basic_stream<Char, CharTraits>, const Foo&) is more
201 // specific.
202 template <typename Char, typename CharTraits, typename T>
203 ::std::basic_ostream<Char, CharTraits>& operator<<(
204     ::std::basic_ostream<Char, CharTraits>& os, const T& x) {
205   TypeWithoutFormatter<T,
206       (internal::IsAProtocolMessage<T>::value ? kProtobuf :
207        internal::ImplicitlyConvertible<const T&, internal::BiggestInt>::value ?
208        kConvertibleToInteger : kOtherType)>::PrintValue(x, &os);
209   return os;
210 }
211 
212 }  // namespace internal2
213 }  // namespace testing
214 
215 // This namespace MUST NOT BE NESTED IN ::testing, or the name look-up
216 // magic needed for implementing UniversalPrinter won't work.
217 namespace testing_internal {
218 
219 // Used to print a value that is not an STL-style container when the
220 // user doesn't define PrintTo() for it.
221 template <typename T>
DefaultPrintNonContainerTo(const T & value,::std::ostream * os)222 void DefaultPrintNonContainerTo(const T& value, ::std::ostream* os) {
223   // With the following statement, during unqualified name lookup,
224   // testing::internal2::operator<< appears as if it was declared in
225   // the nearest enclosing namespace that contains both
226   // ::testing_internal and ::testing::internal2, i.e. the global
227   // namespace.  For more details, refer to the C++ Standard section
228   // 7.3.4-1 [namespace.udir].  This allows us to fall back onto
229   // testing::internal2::operator<< in case T doesn't come with a <<
230   // operator.
231   //
232   // We cannot write 'using ::testing::internal2::operator<<;', which
233   // gcc 3.3 fails to compile due to a compiler bug.
234   using namespace ::testing::internal2;  // NOLINT
235 
236   // Assuming T is defined in namespace foo, in the next statement,
237   // the compiler will consider all of:
238   //
239   //   1. foo::operator<< (thanks to Koenig look-up),
240   //   2. ::operator<< (as the current namespace is enclosed in ::),
241   //   3. testing::internal2::operator<< (thanks to the using statement above).
242   //
243   // The operator<< whose type matches T best will be picked.
244   //
245   // We deliberately allow #2 to be a candidate, as sometimes it's
246   // impossible to define #1 (e.g. when foo is ::std, defining
247   // anything in it is undefined behavior unless you are a compiler
248   // vendor.).
249   *os << value;
250 }
251 
252 }  // namespace testing_internal
253 
254 namespace testing {
255 namespace internal {
256 
257 // UniversalPrinter<T>::Print(value, ostream_ptr) prints the given
258 // value to the given ostream.  The caller must ensure that
259 // 'ostream_ptr' is not NULL, or the behavior is undefined.
260 //
261 // We define UniversalPrinter as a class template (as opposed to a
262 // function template), as we need to partially specialize it for
263 // reference types, which cannot be done with function templates.
264 template <typename T>
265 class UniversalPrinter;
266 
267 template <typename T>
268 void UniversalPrint(const T& value, ::std::ostream* os);
269 
270 // Used to print an STL-style container when the user doesn't define
271 // a PrintTo() for it.
272 template <typename C>
DefaultPrintTo(IsContainer,false_type,const C & container,::std::ostream * os)273 void DefaultPrintTo(IsContainer /* dummy */,
274                     false_type /* is not a pointer */,
275                     const C& container, ::std::ostream* os) {
276   const size_t kMaxCount = 32;  // The maximum number of elements to print.
277   *os << '{';
278   size_t count = 0;
279   for (typename C::const_iterator it = container.begin();
280        it != container.end(); ++it, ++count) {
281     if (count > 0) {
282       *os << ',';
283       if (count == kMaxCount) {  // Enough has been printed.
284         *os << " ...";
285         break;
286       }
287     }
288     *os << ' ';
289     // We cannot call PrintTo(*it, os) here as PrintTo() doesn't
290     // handle *it being a native array.
291     internal::UniversalPrint(*it, os);
292   }
293 
294   if (count > 0) {
295     *os << ' ';
296   }
297   *os << '}';
298 }
299 
300 // Used to print a pointer that is neither a char pointer nor a member
301 // pointer, when the user doesn't define PrintTo() for it.  (A member
302 // variable pointer or member function pointer doesn't really point to
303 // a location in the address space.  Their representation is
304 // implementation-defined.  Therefore they will be printed as raw
305 // bytes.)
306 template <typename T>
DefaultPrintTo(IsNotContainer,true_type,T * p,::std::ostream * os)307 void DefaultPrintTo(IsNotContainer /* dummy */,
308                     true_type /* is a pointer */,
309                     T* p, ::std::ostream* os) {
310   if (p == NULL) {
311     *os << "NULL";
312   } else {
313     // C++ doesn't allow casting from a function pointer to any object
314     // pointer.
315     //
316     // IsTrue() silences warnings: "Condition is always true",
317     // "unreachable code".
318     if (IsTrue(ImplicitlyConvertible<T*, const void*>::value)) {
319       // T is not a function type.  We just call << to print p,
320       // relying on ADL to pick up user-defined << for their pointer
321       // types, if any.
322       *os << p;
323     } else {
324       // T is a function type, so '*os << p' doesn't do what we want
325       // (it just prints p as bool).  We want to print p as a const
326       // void*.  However, we cannot cast it to const void* directly,
327       // even using reinterpret_cast, as earlier versions of gcc
328       // (e.g. 3.4.5) cannot compile the cast when p is a function
329       // pointer.  Casting to UInt64 first solves the problem.
330       *os << reinterpret_cast<const void*>(
331           reinterpret_cast<internal::UInt64>(p));
332     }
333   }
334 }
335 
336 // Used to print a non-container, non-pointer value when the user
337 // doesn't define PrintTo() for it.
338 template <typename T>
DefaultPrintTo(IsNotContainer,false_type,const T & value,::std::ostream * os)339 void DefaultPrintTo(IsNotContainer /* dummy */,
340                     false_type /* is not a pointer */,
341                     const T& value, ::std::ostream* os) {
342   ::testing_internal::DefaultPrintNonContainerTo(value, os);
343 }
344 
345 // Prints the given value using the << operator if it has one;
346 // otherwise prints the bytes in it.  This is what
347 // UniversalPrinter<T>::Print() does when PrintTo() is not specialized
348 // or overloaded for type T.
349 //
350 // A user can override this behavior for a class type Foo by defining
351 // an overload of PrintTo() in the namespace where Foo is defined.  We
352 // give the user this option as sometimes defining a << operator for
353 // Foo is not desirable (e.g. the coding style may prevent doing it,
354 // or there is already a << operator but it doesn't do what the user
355 // wants).
356 template <typename T>
PrintTo(const T & value,::std::ostream * os)357 void PrintTo(const T& value, ::std::ostream* os) {
358   // DefaultPrintTo() is overloaded.  The type of its first two
359   // arguments determine which version will be picked.  If T is an
360   // STL-style container, the version for container will be called; if
361   // T is a pointer, the pointer version will be called; otherwise the
362   // generic version will be called.
363   //
364   // Note that we check for container types here, prior to we check
365   // for protocol message types in our operator<<.  The rationale is:
366   //
367   // For protocol messages, we want to give people a chance to
368   // override Google Mock's format by defining a PrintTo() or
369   // operator<<.  For STL containers, other formats can be
370   // incompatible with Google Mock's format for the container
371   // elements; therefore we check for container types here to ensure
372   // that our format is used.
373   //
374   // The second argument of DefaultPrintTo() is needed to bypass a bug
375   // in Symbian's C++ compiler that prevents it from picking the right
376   // overload between:
377   //
378   //   PrintTo(const T& x, ...);
379   //   PrintTo(T* x, ...);
380   DefaultPrintTo(IsContainerTest<T>(0), is_pointer<T>(), value, os);
381 }
382 
383 // The following list of PrintTo() overloads tells
384 // UniversalPrinter<T>::Print() how to print standard types (built-in
385 // types, strings, plain arrays, and pointers).
386 
387 // Overloads for various char types.
388 GTEST_API_ void PrintTo(unsigned char c, ::std::ostream* os);
389 GTEST_API_ void PrintTo(signed char c, ::std::ostream* os);
PrintTo(char c,::std::ostream * os)390 inline void PrintTo(char c, ::std::ostream* os) {
391   // When printing a plain char, we always treat it as unsigned.  This
392   // way, the output won't be affected by whether the compiler thinks
393   // char is signed or not.
394   PrintTo(static_cast<unsigned char>(c), os);
395 }
396 
397 // Overloads for other simple built-in types.
PrintTo(bool x,::std::ostream * os)398 inline void PrintTo(bool x, ::std::ostream* os) {
399   *os << (x ? "true" : "false");
400 }
401 
402 // Overload for wchar_t type.
403 // Prints a wchar_t as a symbol if it is printable or as its internal
404 // code otherwise and also as its decimal code (except for L'\0').
405 // The L'\0' char is printed as "L'\\0'". The decimal code is printed
406 // as signed integer when wchar_t is implemented by the compiler
407 // as a signed type and is printed as an unsigned integer when wchar_t
408 // is implemented as an unsigned type.
409 GTEST_API_ void PrintTo(wchar_t wc, ::std::ostream* os);
410 
411 // Overloads for C strings.
412 GTEST_API_ void PrintTo(const char* s, ::std::ostream* os);
PrintTo(char * s,::std::ostream * os)413 inline void PrintTo(char* s, ::std::ostream* os) {
414   PrintTo(ImplicitCast_<const char*>(s), os);
415 }
416 
417 // signed/unsigned char is often used for representing binary data, so
418 // we print pointers to it as void* to be safe.
PrintTo(const signed char * s,::std::ostream * os)419 inline void PrintTo(const signed char* s, ::std::ostream* os) {
420   PrintTo(ImplicitCast_<const void*>(s), os);
421 }
PrintTo(signed char * s,::std::ostream * os)422 inline void PrintTo(signed char* s, ::std::ostream* os) {
423   PrintTo(ImplicitCast_<const void*>(s), os);
424 }
PrintTo(const unsigned char * s,::std::ostream * os)425 inline void PrintTo(const unsigned char* s, ::std::ostream* os) {
426   PrintTo(ImplicitCast_<const void*>(s), os);
427 }
PrintTo(unsigned char * s,::std::ostream * os)428 inline void PrintTo(unsigned char* s, ::std::ostream* os) {
429   PrintTo(ImplicitCast_<const void*>(s), os);
430 }
431 
432 // MSVC can be configured to define wchar_t as a typedef of unsigned
433 // short.  It defines _NATIVE_WCHAR_T_DEFINED when wchar_t is a native
434 // type.  When wchar_t is a typedef, defining an overload for const
435 // wchar_t* would cause unsigned short* be printed as a wide string,
436 // possibly causing invalid memory accesses.
437 #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
438 // Overloads for wide C strings
439 GTEST_API_ void PrintTo(const wchar_t* s, ::std::ostream* os);
PrintTo(wchar_t * s,::std::ostream * os)440 inline void PrintTo(wchar_t* s, ::std::ostream* os) {
441   PrintTo(ImplicitCast_<const wchar_t*>(s), os);
442 }
443 #endif
444 
445 // Overload for C arrays.  Multi-dimensional arrays are printed
446 // properly.
447 
448 // Prints the given number of elements in an array, without printing
449 // the curly braces.
450 template <typename T>
PrintRawArrayTo(const T a[],size_t count,::std::ostream * os)451 void PrintRawArrayTo(const T a[], size_t count, ::std::ostream* os) {
452   UniversalPrint(a[0], os);
453   for (size_t i = 1; i != count; i++) {
454     *os << ", ";
455     UniversalPrint(a[i], os);
456   }
457 }
458 
459 // Overloads for ::string and ::std::string.
460 #if GTEST_HAS_GLOBAL_STRING
461 GTEST_API_ void PrintStringTo(const ::string&s, ::std::ostream* os);
PrintTo(const::string & s,::std::ostream * os)462 inline void PrintTo(const ::string& s, ::std::ostream* os) {
463   PrintStringTo(s, os);
464 }
465 #endif  // GTEST_HAS_GLOBAL_STRING
466 
467 GTEST_API_ void PrintStringTo(const ::std::string&s, ::std::ostream* os);
PrintTo(const::std::string & s,::std::ostream * os)468 inline void PrintTo(const ::std::string& s, ::std::ostream* os) {
469   PrintStringTo(s, os);
470 }
471 
472 // Overloads for ::wstring and ::std::wstring.
473 #if GTEST_HAS_GLOBAL_WSTRING
474 GTEST_API_ void PrintWideStringTo(const ::wstring&s, ::std::ostream* os);
PrintTo(const::wstring & s,::std::ostream * os)475 inline void PrintTo(const ::wstring& s, ::std::ostream* os) {
476   PrintWideStringTo(s, os);
477 }
478 #endif  // GTEST_HAS_GLOBAL_WSTRING
479 
480 #if GTEST_HAS_STD_WSTRING
481 GTEST_API_ void PrintWideStringTo(const ::std::wstring&s, ::std::ostream* os);
PrintTo(const::std::wstring & s,::std::ostream * os)482 inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) {
483   PrintWideStringTo(s, os);
484 }
485 #endif  // GTEST_HAS_STD_WSTRING
486 
487 #if GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_
488 // Helper function for printing a tuple.  T must be instantiated with
489 // a tuple type.
490 template <typename T>
491 void PrintTupleTo(const T& t, ::std::ostream* os);
492 #endif  // GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_
493 
494 #if GTEST_HAS_TR1_TUPLE
495 // Overload for ::std::tr1::tuple.  Needed for printing function arguments,
496 // which are packed as tuples.
497 
498 // Overloaded PrintTo() for tuples of various arities.  We support
499 // tuples of up-to 10 fields.  The following implementation works
500 // regardless of whether tr1::tuple is implemented using the
501 // non-standard variadic template feature or not.
502 
PrintTo(const::std::tr1::tuple<> & t,::std::ostream * os)503 inline void PrintTo(const ::std::tr1::tuple<>& t, ::std::ostream* os) {
504   PrintTupleTo(t, os);
505 }
506 
507 template <typename T1>
PrintTo(const::std::tr1::tuple<T1> & t,::std::ostream * os)508 void PrintTo(const ::std::tr1::tuple<T1>& t, ::std::ostream* os) {
509   PrintTupleTo(t, os);
510 }
511 
512 template <typename T1, typename T2>
PrintTo(const::std::tr1::tuple<T1,T2> & t,::std::ostream * os)513 void PrintTo(const ::std::tr1::tuple<T1, T2>& t, ::std::ostream* os) {
514   PrintTupleTo(t, os);
515 }
516 
517 template <typename T1, typename T2, typename T3>
PrintTo(const::std::tr1::tuple<T1,T2,T3> & t,::std::ostream * os)518 void PrintTo(const ::std::tr1::tuple<T1, T2, T3>& t, ::std::ostream* os) {
519   PrintTupleTo(t, os);
520 }
521 
522 template <typename T1, typename T2, typename T3, typename T4>
PrintTo(const::std::tr1::tuple<T1,T2,T3,T4> & t,::std::ostream * os)523 void PrintTo(const ::std::tr1::tuple<T1, T2, T3, T4>& t, ::std::ostream* os) {
524   PrintTupleTo(t, os);
525 }
526 
527 template <typename T1, typename T2, typename T3, typename T4, typename T5>
PrintTo(const::std::tr1::tuple<T1,T2,T3,T4,T5> & t,::std::ostream * os)528 void PrintTo(const ::std::tr1::tuple<T1, T2, T3, T4, T5>& t,
529              ::std::ostream* os) {
530   PrintTupleTo(t, os);
531 }
532 
533 template <typename T1, typename T2, typename T3, typename T4, typename T5,
534           typename T6>
PrintTo(const::std::tr1::tuple<T1,T2,T3,T4,T5,T6> & t,::std::ostream * os)535 void PrintTo(const ::std::tr1::tuple<T1, T2, T3, T4, T5, T6>& t,
536              ::std::ostream* os) {
537   PrintTupleTo(t, os);
538 }
539 
540 template <typename T1, typename T2, typename T3, typename T4, typename T5,
541           typename T6, typename T7>
PrintTo(const::std::tr1::tuple<T1,T2,T3,T4,T5,T6,T7> & t,::std::ostream * os)542 void PrintTo(const ::std::tr1::tuple<T1, T2, T3, T4, T5, T6, T7>& t,
543              ::std::ostream* os) {
544   PrintTupleTo(t, os);
545 }
546 
547 template <typename T1, typename T2, typename T3, typename T4, typename T5,
548           typename T6, typename T7, typename T8>
PrintTo(const::std::tr1::tuple<T1,T2,T3,T4,T5,T6,T7,T8> & t,::std::ostream * os)549 void PrintTo(const ::std::tr1::tuple<T1, T2, T3, T4, T5, T6, T7, T8>& t,
550              ::std::ostream* os) {
551   PrintTupleTo(t, os);
552 }
553 
554 template <typename T1, typename T2, typename T3, typename T4, typename T5,
555           typename T6, typename T7, typename T8, typename T9>
PrintTo(const::std::tr1::tuple<T1,T2,T3,T4,T5,T6,T7,T8,T9> & t,::std::ostream * os)556 void PrintTo(const ::std::tr1::tuple<T1, T2, T3, T4, T5, T6, T7, T8, T9>& t,
557              ::std::ostream* os) {
558   PrintTupleTo(t, os);
559 }
560 
561 template <typename T1, typename T2, typename T3, typename T4, typename T5,
562           typename T6, typename T7, typename T8, typename T9, typename T10>
PrintTo(const::std::tr1::tuple<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10> & t,::std::ostream * os)563 void PrintTo(
564     const ::std::tr1::tuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>& t,
565     ::std::ostream* os) {
566   PrintTupleTo(t, os);
567 }
568 #endif  // GTEST_HAS_TR1_TUPLE
569 
570 #if GTEST_HAS_STD_TUPLE_
571 template <typename... Types>
PrintTo(const::std::tuple<Types...> & t,::std::ostream * os)572 void PrintTo(const ::std::tuple<Types...>& t, ::std::ostream* os) {
573   PrintTupleTo(t, os);
574 }
575 #endif  // GTEST_HAS_STD_TUPLE_
576 
577 // Overload for std::pair.
578 template <typename T1, typename T2>
PrintTo(const::std::pair<T1,T2> & value,::std::ostream * os)579 void PrintTo(const ::std::pair<T1, T2>& value, ::std::ostream* os) {
580   *os << '(';
581   // We cannot use UniversalPrint(value.first, os) here, as T1 may be
582   // a reference type.  The same for printing value.second.
583   UniversalPrinter<T1>::Print(value.first, os);
584   *os << ", ";
585   UniversalPrinter<T2>::Print(value.second, os);
586   *os << ')';
587 }
588 
589 // Implements printing a non-reference type T by letting the compiler
590 // pick the right overload of PrintTo() for T.
591 template <typename T>
592 class UniversalPrinter {
593  public:
594   // MSVC warns about adding const to a function type, so we want to
595   // disable the warning.
596   GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180)
597 
598   // Note: we deliberately don't call this PrintTo(), as that name
599   // conflicts with ::testing::internal::PrintTo in the body of the
600   // function.
Print(const T & value,::std::ostream * os)601   static void Print(const T& value, ::std::ostream* os) {
602     // By default, ::testing::internal::PrintTo() is used for printing
603     // the value.
604     //
605     // Thanks to Koenig look-up, if T is a class and has its own
606     // PrintTo() function defined in its namespace, that function will
607     // be visible here.  Since it is more specific than the generic ones
608     // in ::testing::internal, it will be picked by the compiler in the
609     // following statement - exactly what we want.
610     PrintTo(value, os);
611   }
612 
613   GTEST_DISABLE_MSC_WARNINGS_POP_()
614 };
615 
616 // UniversalPrintArray(begin, len, os) prints an array of 'len'
617 // elements, starting at address 'begin'.
618 template <typename T>
UniversalPrintArray(const T * begin,size_t len,::std::ostream * os)619 void UniversalPrintArray(const T* begin, size_t len, ::std::ostream* os) {
620   if (len == 0) {
621     *os << "{}";
622   } else {
623     *os << "{ ";
624     const size_t kThreshold = 18;
625     const size_t kChunkSize = 8;
626     // If the array has more than kThreshold elements, we'll have to
627     // omit some details by printing only the first and the last
628     // kChunkSize elements.
629     // TODO(wan@google.com): let the user control the threshold using a flag.
630     if (len <= kThreshold) {
631       PrintRawArrayTo(begin, len, os);
632     } else {
633       PrintRawArrayTo(begin, kChunkSize, os);
634       *os << ", ..., ";
635       PrintRawArrayTo(begin + len - kChunkSize, kChunkSize, os);
636     }
637     *os << " }";
638   }
639 }
640 // This overload prints a (const) char array compactly.
641 GTEST_API_ void UniversalPrintArray(
642     const char* begin, size_t len, ::std::ostream* os);
643 
644 // This overload prints a (const) wchar_t array compactly.
645 GTEST_API_ void UniversalPrintArray(
646     const wchar_t* begin, size_t len, ::std::ostream* os);
647 
648 // Implements printing an array type T[N].
649 template <typename T, size_t N>
650 class UniversalPrinter<T[N]> {
651  public:
652   // Prints the given array, omitting some elements when there are too
653   // many.
Print(const T (& a)[N],::std::ostream * os)654   static void Print(const T (&a)[N], ::std::ostream* os) {
655     UniversalPrintArray(a, N, os);
656   }
657 };
658 
659 // Implements printing a reference type T&.
660 template <typename T>
661 class UniversalPrinter<T&> {
662  public:
663   // MSVC warns about adding const to a function type, so we want to
664   // disable the warning.
665   GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180)
666 
Print(const T & value,::std::ostream * os)667   static void Print(const T& value, ::std::ostream* os) {
668     // Prints the address of the value.  We use reinterpret_cast here
669     // as static_cast doesn't compile when T is a function type.
670     *os << "@" << reinterpret_cast<const void*>(&value) << " ";
671 
672     // Then prints the value itself.
673     UniversalPrint(value, os);
674   }
675 
676   GTEST_DISABLE_MSC_WARNINGS_POP_()
677 };
678 
679 // Prints a value tersely: for a reference type, the referenced value
680 // (but not the address) is printed; for a (const) char pointer, the
681 // NUL-terminated string (but not the pointer) is printed.
682 
683 template <typename T>
684 class UniversalTersePrinter {
685  public:
Print(const T & value,::std::ostream * os)686   static void Print(const T& value, ::std::ostream* os) {
687     UniversalPrint(value, os);
688   }
689 };
690 template <typename T>
691 class UniversalTersePrinter<T&> {
692  public:
Print(const T & value,::std::ostream * os)693   static void Print(const T& value, ::std::ostream* os) {
694     UniversalPrint(value, os);
695   }
696 };
697 template <typename T, size_t N>
698 class UniversalTersePrinter<T[N]> {
699  public:
Print(const T (& value)[N],::std::ostream * os)700   static void Print(const T (&value)[N], ::std::ostream* os) {
701     UniversalPrinter<T[N]>::Print(value, os);
702   }
703 };
704 template <>
705 class UniversalTersePrinter<const char*> {
706  public:
Print(const char * str,::std::ostream * os)707   static void Print(const char* str, ::std::ostream* os) {
708     if (str == NULL) {
709       *os << "NULL";
710     } else {
711       UniversalPrint(string(str), os);
712     }
713   }
714 };
715 template <>
716 class UniversalTersePrinter<char*> {
717  public:
Print(char * str,::std::ostream * os)718   static void Print(char* str, ::std::ostream* os) {
719     UniversalTersePrinter<const char*>::Print(str, os);
720   }
721 };
722 
723 #if GTEST_HAS_STD_WSTRING
724 template <>
725 class UniversalTersePrinter<const wchar_t*> {
726  public:
Print(const wchar_t * str,::std::ostream * os)727   static void Print(const wchar_t* str, ::std::ostream* os) {
728     if (str == NULL) {
729       *os << "NULL";
730     } else {
731       UniversalPrint(::std::wstring(str), os);
732     }
733   }
734 };
735 #endif
736 
737 template <>
738 class UniversalTersePrinter<wchar_t*> {
739  public:
Print(wchar_t * str,::std::ostream * os)740   static void Print(wchar_t* str, ::std::ostream* os) {
741     UniversalTersePrinter<const wchar_t*>::Print(str, os);
742   }
743 };
744 
745 template <typename T>
UniversalTersePrint(const T & value,::std::ostream * os)746 void UniversalTersePrint(const T& value, ::std::ostream* os) {
747   UniversalTersePrinter<T>::Print(value, os);
748 }
749 
750 // Prints a value using the type inferred by the compiler.  The
751 // difference between this and UniversalTersePrint() is that for a
752 // (const) char pointer, this prints both the pointer and the
753 // NUL-terminated string.
754 template <typename T>
UniversalPrint(const T & value,::std::ostream * os)755 void UniversalPrint(const T& value, ::std::ostream* os) {
756   // A workarond for the bug in VC++ 7.1 that prevents us from instantiating
757   // UniversalPrinter with T directly.
758   typedef T T1;
759   UniversalPrinter<T1>::Print(value, os);
760 }
761 
762 typedef ::std::vector<string> Strings;
763 
764 // TuplePolicy<TupleT> must provide:
765 // - tuple_size
766 //     size of tuple TupleT.
767 // - get<size_t I>(const TupleT& t)
768 //     static function extracting element I of tuple TupleT.
769 // - tuple_element<size_t I>::type
770 //     type of element I of tuple TupleT.
771 template <typename TupleT>
772 struct TuplePolicy;
773 
774 #if GTEST_HAS_TR1_TUPLE
775 template <typename TupleT>
776 struct TuplePolicy {
777   typedef TupleT Tuple;
778   static const size_t tuple_size = ::std::tr1::tuple_size<Tuple>::value;
779 
780   template <size_t I>
781   struct tuple_element : ::std::tr1::tuple_element<I, Tuple> {};
782 
783   template <size_t I>
784   static typename AddReference<
getTuplePolicy785       const typename ::std::tr1::tuple_element<I, Tuple>::type>::type get(
786       const Tuple& tuple) {
787     return ::std::tr1::get<I>(tuple);
788   }
789 };
790 template <typename TupleT>
791 const size_t TuplePolicy<TupleT>::tuple_size;
792 #endif  // GTEST_HAS_TR1_TUPLE
793 
794 #if GTEST_HAS_STD_TUPLE_
795 template <typename... Types>
796 struct TuplePolicy< ::std::tuple<Types...> > {
797   typedef ::std::tuple<Types...> Tuple;
798   static const size_t tuple_size = ::std::tuple_size<Tuple>::value;
799 
800   template <size_t I>
801   struct tuple_element : ::std::tuple_element<I, Tuple> {};
802 
803   template <size_t I>
804   static const typename ::std::tuple_element<I, Tuple>::type& get(
805       const Tuple& tuple) {
806     return ::std::get<I>(tuple);
807   }
808 };
809 template <typename... Types>
810 const size_t TuplePolicy< ::std::tuple<Types...> >::tuple_size;
811 #endif  // GTEST_HAS_STD_TUPLE_
812 
813 #if GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_
814 // This helper template allows PrintTo() for tuples and
815 // UniversalTersePrintTupleFieldsToStrings() to be defined by
816 // induction on the number of tuple fields.  The idea is that
817 // TuplePrefixPrinter<N>::PrintPrefixTo(t, os) prints the first N
818 // fields in tuple t, and can be defined in terms of
819 // TuplePrefixPrinter<N - 1>.
820 //
821 // The inductive case.
822 template <size_t N>
823 struct TuplePrefixPrinter {
824   // Prints the first N fields of a tuple.
825   template <typename Tuple>
826   static void PrintPrefixTo(const Tuple& t, ::std::ostream* os) {
827     TuplePrefixPrinter<N - 1>::PrintPrefixTo(t, os);
828     GTEST_INTENTIONAL_CONST_COND_PUSH_()
829     if (N > 1) {
830     GTEST_INTENTIONAL_CONST_COND_POP_()
831       *os << ", ";
832     }
833     UniversalPrinter<
834         typename TuplePolicy<Tuple>::template tuple_element<N - 1>::type>
835         ::Print(TuplePolicy<Tuple>::template get<N - 1>(t), os);
836   }
837 
838   // Tersely prints the first N fields of a tuple to a string vector,
839   // one element for each field.
840   template <typename Tuple>
841   static void TersePrintPrefixToStrings(const Tuple& t, Strings* strings) {
842     TuplePrefixPrinter<N - 1>::TersePrintPrefixToStrings(t, strings);
843     ::std::stringstream ss;
844     UniversalTersePrint(TuplePolicy<Tuple>::template get<N - 1>(t), &ss);
845     strings->push_back(ss.str());
846   }
847 };
848 
849 // Base case.
850 template <>
851 struct TuplePrefixPrinter<0> {
852   template <typename Tuple>
853   static void PrintPrefixTo(const Tuple&, ::std::ostream*) {}
854 
855   template <typename Tuple>
856   static void TersePrintPrefixToStrings(const Tuple&, Strings*) {}
857 };
858 
859 // Helper function for printing a tuple.
860 // Tuple must be either std::tr1::tuple or std::tuple type.
861 template <typename Tuple>
862 void PrintTupleTo(const Tuple& t, ::std::ostream* os) {
863   *os << "(";
864   TuplePrefixPrinter<TuplePolicy<Tuple>::tuple_size>::PrintPrefixTo(t, os);
865   *os << ")";
866 }
867 
868 // Prints the fields of a tuple tersely to a string vector, one
869 // element for each field.  See the comment before
870 // UniversalTersePrint() for how we define "tersely".
871 template <typename Tuple>
872 Strings UniversalTersePrintTupleFieldsToStrings(const Tuple& value) {
873   Strings result;
874   TuplePrefixPrinter<TuplePolicy<Tuple>::tuple_size>::
875       TersePrintPrefixToStrings(value, &result);
876   return result;
877 }
878 #endif  // GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_
879 
880 }  // namespace internal
881 
882 template <typename T>
883 ::std::string PrintToString(const T& value) {
884   ::std::stringstream ss;
885   internal::UniversalTersePrinter<T>::Print(value, &ss);
886   return ss.str();
887 }
888 
889 }  // namespace testing
890 
891 #endif  // GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
892