blob: 759aa34739ea3ae6aaf826eb772b66974c544c0e [file] [log] [blame]
shiqiane35fdd92008-12-10 05:08:54 +00001// 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 Mock - a framework for writing C++ mock classes.
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. If both are defined, PrintTo() takes precedence.
44// When T is a reference type, the address of the value is also
45// printed.
46//
47// We also provide a convenient wrapper
48//
49// string ::testing::internal::UniversalPrinter<T>::PrintAsString(value);
50
51#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_PRINTERS_H_
52#define GMOCK_INCLUDE_GMOCK_GMOCK_PRINTERS_H_
53
54#include <ostream> // NOLINT
55#include <string>
56#include <utility>
57
58#include <gmock/internal/gmock-internal-utils.h>
59#include <gmock/internal/gmock-port.h>
60#include <gtest/gtest.h>
61
62// Makes sure there is at least one << operator declared in the global
63// namespace. This has no implementation and won't be called
64// anywhere. We just need the declaration such that we can say "using
65// ::operator <<;" in the definition of PrintTo() below.
66void operator<<(::testing::internal::Unused, int);
67
68namespace testing {
69
70// Definitions in the 'internal' and 'internal2' name spaces are
71// subject to change without notice. DO NOT USE THEM IN USER CODE!
72namespace internal2 {
73
74// Prints the given number of bytes in the given object to the given
75// ostream.
76void PrintBytesInObjectTo(const unsigned char* obj_bytes,
77 size_t count,
78 ::std::ostream* os);
79
80// TypeWithoutFormatter<T, kIsProto>::PrintValue(value, os) is called
81// by the universal printer to print a value of type T when neither
82// operator<< nor PrintTo() is defined for type T. When T is
83// ProtocolMessage, proto2::Message, or a subclass of those, kIsProto
84// will be true and the short debug string of the protocol message
85// value will be printed; otherwise kIsProto will be false and the
86// bytes in the value will be printed.
87template <typename T, bool kIsProto>
88class TypeWithoutFormatter {
89 public:
90 static void PrintValue(const T& value, ::std::ostream* os) {
91 PrintBytesInObjectTo(reinterpret_cast<const unsigned char*>(&value),
92 sizeof(value), os);
93 }
94};
95template <typename T>
96class TypeWithoutFormatter<T, true> {
97 public:
98 static void PrintValue(const T& value, ::std::ostream* os) {
99 // Both ProtocolMessage and proto2::Message have the
100 // ShortDebugString() method, so the same implementation works for
101 // both.
102 ::std::operator<<(*os, "<" + value.ShortDebugString() + ">");
103 }
104};
105
106// Prints the given value to the given ostream. If the value is a
107// protocol message, its short debug string is printed; otherwise the
108// bytes in the value are printed. This is what
109// UniversalPrinter<T>::Print() does when it knows nothing about type
110// T and T has no << operator.
111//
112// A user can override this behavior for a class type Foo by defining
113// a << operator in the namespace where Foo is defined.
114//
115// We put this operator in namespace 'internal2' instead of 'internal'
116// to simplify the implementation, as much code in 'internal' needs to
117// use << in STL, which would conflict with our own << were it defined
118// in 'internal'.
zhanyong.wan2f0849f2009-02-11 18:06:37 +0000119//
120// Note that this operator<< takes a generic std::basic_ostream<Char,
121// CharTraits> type instead of the more restricted std::ostream. If
122// we define it to take an std::ostream instead, we'll get an
123// "ambiguous overloads" compiler error when trying to print a type
124// Foo that supports streaming to std::basic_ostream<Char,
125// CharTraits>, as the compiler cannot tell whether
126// operator<<(std::ostream&, const T&) or
127// operator<<(std::basic_stream<Char, CharTraits>, const Foo&) is more
128// specific.
129template <typename Char, typename CharTraits, typename T>
130::std::basic_ostream<Char, CharTraits>& operator<<(
131 ::std::basic_ostream<Char, CharTraits>& os, const T& x) {
shiqiane35fdd92008-12-10 05:08:54 +0000132 TypeWithoutFormatter<T, ::testing::internal::IsAProtocolMessage<T>::value>::
133 PrintValue(x, &os);
134 return os;
135}
136
137} // namespace internal2
138
139namespace internal {
140
141// UniversalPrinter<T>::Print(value, ostream_ptr) prints the given
142// value to the given ostream. The caller must ensure that
143// 'ostream_ptr' is not NULL, or the behavior is undefined.
144//
145// We define UniversalPrinter as a class template (as opposed to a
146// function template), as we need to partially specialize it for
147// reference types, which cannot be done with function templates.
148template <typename T>
149class UniversalPrinter;
150
151// Used to print an STL-style container when the user doesn't define
152// a PrintTo() for it.
153template <typename C>
154void DefaultPrintTo(IsContainer, const C& container, ::std::ostream* os) {
155 const size_t kMaxCount = 32; // The maximum number of elements to print.
156 *os << '{';
157 size_t count = 0;
158 for (typename C::const_iterator it = container.begin();
159 it != container.end(); ++it, ++count) {
160 if (count > 0) {
161 *os << ',';
162 if (count == kMaxCount) { // Enough has been printed.
163 *os << " ...";
164 break;
165 }
166 }
167 *os << ' ';
168 PrintTo(*it, os);
169 }
170
171 if (count > 0) {
172 *os << ' ';
173 }
174 *os << '}';
175}
176
177// Used to print a value when the user doesn't define PrintTo() for it.
178template <typename T>
179void DefaultPrintTo(IsNotContainer, const T& value, ::std::ostream* os) {
180 // If T has its << operator defined in the global namespace, which
181 // is not recommended but sometimes unavoidable (as in
182 // util/gtl/stl_logging-inl.h), the following statement makes it
183 // visible in this function.
184 //
185 // Without the statement, << in the global namespace would be hidden
186 // by the one in ::testing::internal2, due to the next using
187 // statement.
188 using ::operator <<;
189
190 // When T doesn't come with a << operator, we want to fall back to
191 // the one defined in ::testing::internal2, which prints the bytes in
192 // the value.
193 using ::testing::internal2::operator <<;
194
195 // Thanks to Koenig look-up, if type T has its own << operator
196 // defined in its namespace, which is the recommended way, that
197 // operator will be visible here. Since it is more specific than
198 // the generic one, it will be picked by the compiler in the
199 // following statement - exactly what we want.
200 *os << value;
201}
202
203// Prints the given value using the << operator if it has one;
204// otherwise prints the bytes in it. This is what
205// UniversalPrinter<T>::Print() does when PrintTo() is not specialized
206// or overloaded for type T.
207//
208// A user can override this behavior for a class type Foo by defining
209// an overload of PrintTo() in the namespace where Foo is defined. We
210// give the user this option as sometimes defining a << operator for
211// Foo is not desirable (e.g. the coding style may prevent doing it,
212// or there is already a << operator but it doesn't do what the user
213// wants).
214template <typename T>
215void PrintTo(const T& value, ::std::ostream* os) {
216 // DefaultPrintTo() is overloaded. The type of its first argument
217 // determines which version will be picked. If T is an STL-style
218 // container, the version for container will be called. Otherwise
219 // the generic version will be called.
220 //
221 // Note that we check for container types here, prior to we check
222 // for protocol message types in our operator<<. The rationale is:
223 //
224 // For protocol messages, we want to give people a chance to
225 // override Google Mock's format by defining a PrintTo() or
226 // operator<<. For STL containers, we believe the Google Mock's
227 // format is superior to what util/gtl/stl-logging.h offers.
228 // Therefore we don't want it to be accidentally overridden by the
229 // latter (even if the user includes stl-logging.h through other
230 // headers indirectly, Google Mock's format will still be used).
231 DefaultPrintTo(IsContainerTest<T>(0), value, os);
232}
233
234// The following list of PrintTo() overloads tells
235// UniversalPrinter<T>::Print() how to print standard types (built-in
236// types, strings, plain arrays, and pointers).
237
238// Overloads for various char types.
239void PrintCharTo(char c, int char_code, ::std::ostream* os);
240inline void PrintTo(unsigned char c, ::std::ostream* os) {
241 PrintCharTo(c, c, os);
242}
243inline void PrintTo(signed char c, ::std::ostream* os) {
244 PrintCharTo(c, c, os);
245}
246inline void PrintTo(char c, ::std::ostream* os) {
247 // When printing a plain char, we always treat it as unsigned. This
248 // way, the output won't be affected by whether the compiler thinks
249 // char is signed or not.
250 PrintTo(static_cast<unsigned char>(c), os);
251}
252
253// Overloads for other simple built-in types.
254inline void PrintTo(bool x, ::std::ostream* os) {
255 *os << (x ? "true" : "false");
256}
257
258// Overload for wchar_t type.
259// Prints a wchar_t as a symbol if it is printable or as its internal
260// code otherwise and also as its decimal code (except for L'\0').
261// The L'\0' char is printed as "L'\\0'". The decimal code is printed
262// as signed integer when wchar_t is implemented by the compiler
263// as a signed type and is printed as an unsigned integer when wchar_t
264// is implemented as an unsigned type.
265void PrintTo(wchar_t wc, ::std::ostream* os);
266
267// Overloads for C strings.
268void PrintTo(const char* s, ::std::ostream* os);
269inline void PrintTo(char* s, ::std::ostream* os) {
270 PrintTo(implicit_cast<const char*>(s), os);
271}
272
273// MSVC compiler can be configured to define whar_t as a typedef
274// of unsigned short. Defining an overload for const wchar_t* in that case
275// would cause pointers to unsigned shorts be printed as wide strings,
276// possibly accessing more memory than intended and causing invalid
277// memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
278// wchar_t is implemented as a native type.
279#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
280// Overloads for wide C strings
281void PrintTo(const wchar_t* s, ::std::ostream* os);
282inline void PrintTo(wchar_t* s, ::std::ostream* os) {
283 PrintTo(implicit_cast<const wchar_t*>(s), os);
284}
285#endif
286
287// Overload for pointers that are neither char pointers nor member
288// pointers. (A member variable pointer or member function pointer
289// doesn't really points to a location in the address space. Their
290// representation is implementation-defined. Therefore they will be
291// printed as raw bytes.)
292template <typename T>
293void PrintTo(T* p, ::std::ostream* os) {
294 if (p == NULL) {
295 *os << "NULL";
296 } else {
297 // We cannot use implicit_cast or static_cast here, as they don't
298 // work when p is a function pointer.
299 *os << reinterpret_cast<const void*>(p);
300 }
301}
302
303// Overload for C arrays. Multi-dimensional arrays are printed
304// properly.
305
306// Prints the given number of elements in an array, without printing
307// the curly braces.
308template <typename T>
309void PrintRawArrayTo(const T a[], size_t count, ::std::ostream* os) {
310 UniversalPrinter<T>::Print(a[0], os);
311 for (size_t i = 1; i != count; i++) {
312 *os << ", ";
313 UniversalPrinter<T>::Print(a[i], os);
314 }
315}
316
317// Overloads for ::string and ::std::string.
318#if GTEST_HAS_GLOBAL_STRING
319void PrintStringTo(const ::string&s, ::std::ostream* os);
320inline void PrintTo(const ::string& s, ::std::ostream* os) {
321 PrintStringTo(s, os);
322}
323#endif // GTEST_HAS_GLOBAL_STRING
324
325#if GTEST_HAS_STD_STRING
326void PrintStringTo(const ::std::string&s, ::std::ostream* os);
327inline void PrintTo(const ::std::string& s, ::std::ostream* os) {
328 PrintStringTo(s, os);
329}
330#endif // GTEST_HAS_STD_STRING
331
332// Overloads for ::wstring and ::std::wstring.
333#if GTEST_HAS_GLOBAL_WSTRING
334void PrintWideStringTo(const ::wstring&s, ::std::ostream* os);
335inline void PrintTo(const ::wstring& s, ::std::ostream* os) {
336 PrintWideStringTo(s, os);
337}
338#endif // GTEST_HAS_GLOBAL_WSTRING
339
340#if GTEST_HAS_STD_WSTRING
341void PrintWideStringTo(const ::std::wstring&s, ::std::ostream* os);
342inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) {
343 PrintWideStringTo(s, os);
344}
345#endif // GTEST_HAS_STD_WSTRING
346
347// Overload for ::std::tr1::tuple. Needed for printing function
348// arguments, which are packed as tuples.
349
350// This helper template allows PrintTo() for tuples to be defined by
351// induction on the number of tuple fields. The idea is that
352// TuplePrefixPrinter<N>::PrintPrefixTo(t, os) prints the first N
353// fields in tuple t, and can be defined in terms of
354// TuplePrefixPrinter<N - 1>.
355template <size_t N>
356struct TuplePrefixPrinter {
357 template <typename Tuple>
358 static void PrintPrefixTo(const Tuple& t, ::std::ostream* os) {
359 TuplePrefixPrinter<N - 1>::PrintPrefixTo(t, os);
360 *os << ", ";
361 UniversalPrinter<typename ::std::tr1::tuple_element<N - 1, Tuple>::type>
362 ::Print(::std::tr1::get<N - 1>(t), os);
363 }
364};
365template <>
366struct TuplePrefixPrinter<0> {
367 template <typename Tuple>
368 static void PrintPrefixTo(const Tuple&, ::std::ostream*) {}
369};
370template <>
371struct TuplePrefixPrinter<1> {
372 template <typename Tuple>
373 static void PrintPrefixTo(const Tuple& t, ::std::ostream* os) {
374 UniversalPrinter<typename ::std::tr1::tuple_element<0, Tuple>::type>::
375 Print(::std::tr1::get<0>(t), os);
376 }
377};
378
shiqianc97f2f52008-12-11 17:22:59 +0000379// Helper function for printing a tuple. T must be instantiated with
380// a tuple type.
381template <typename T>
382void PrintTupleTo(const T& t, ::std::ostream* os) {
383 *os << "(";
384 TuplePrefixPrinter< ::std::tr1::tuple_size<T>::value>::
385 PrintPrefixTo(t, os);
386 *os << ")";
387}
388
389// Overloaded PrintTo() for tuples of various arities. We support
390// tuples of up-to 10 fields. The following implementation works
391// regardless of whether tr1::tuple is implemented using the
392// non-standard variadic template feature or not.
393
394inline void PrintTo(const ::std::tr1::tuple<>& t, ::std::ostream* os) {
395 PrintTupleTo(t, os);
396}
397
398template <typename T1>
399void PrintTo(const ::std::tr1::tuple<T1>& t, ::std::ostream* os) {
400 PrintTupleTo(t, os);
401}
402
403template <typename T1, typename T2>
404void PrintTo(const ::std::tr1::tuple<T1, T2>& t, ::std::ostream* os) {
405 PrintTupleTo(t, os);
406}
407
408template <typename T1, typename T2, typename T3>
409void PrintTo(const ::std::tr1::tuple<T1, T2, T3>& t, ::std::ostream* os) {
410 PrintTupleTo(t, os);
411}
412
413template <typename T1, typename T2, typename T3, typename T4>
414void PrintTo(const ::std::tr1::tuple<T1, T2, T3, T4>& t, ::std::ostream* os) {
415 PrintTupleTo(t, os);
416}
417
418template <typename T1, typename T2, typename T3, typename T4, typename T5>
419void PrintTo(const ::std::tr1::tuple<T1, T2, T3, T4, T5>& t,
420 ::std::ostream* os) {
421 PrintTupleTo(t, os);
422}
423
424template <typename T1, typename T2, typename T3, typename T4, typename T5,
425 typename T6>
426void PrintTo(const ::std::tr1::tuple<T1, T2, T3, T4, T5, T6>& t,
427 ::std::ostream* os) {
428 PrintTupleTo(t, os);
429}
430
431template <typename T1, typename T2, typename T3, typename T4, typename T5,
432 typename T6, typename T7>
433void PrintTo(const ::std::tr1::tuple<T1, T2, T3, T4, T5, T6, T7>& t,
434 ::std::ostream* os) {
435 PrintTupleTo(t, os);
436}
437
438template <typename T1, typename T2, typename T3, typename T4, typename T5,
439 typename T6, typename T7, typename T8>
440void PrintTo(const ::std::tr1::tuple<T1, T2, T3, T4, T5, T6, T7, T8>& t,
441 ::std::ostream* os) {
442 PrintTupleTo(t, os);
443}
444
445template <typename T1, typename T2, typename T3, typename T4, typename T5,
446 typename T6, typename T7, typename T8, typename T9>
447void PrintTo(const ::std::tr1::tuple<T1, T2, T3, T4, T5, T6, T7, T8, T9>& t,
448 ::std::ostream* os) {
449 PrintTupleTo(t, os);
450}
451
shiqiane35fdd92008-12-10 05:08:54 +0000452template <typename T1, typename T2, typename T3, typename T4, typename T5,
453 typename T6, typename T7, typename T8, typename T9, typename T10>
454void PrintTo(
455 const ::std::tr1::tuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>& t,
456 ::std::ostream* os) {
shiqianc97f2f52008-12-11 17:22:59 +0000457 PrintTupleTo(t, os);
shiqiane35fdd92008-12-10 05:08:54 +0000458}
459
460// Overload for std::pair.
461template <typename T1, typename T2>
462void PrintTo(const ::std::pair<T1, T2>& value, ::std::ostream* os) {
463 *os << '(';
464 UniversalPrinter<T1>::Print(value.first, os);
465 *os << ", ";
466 UniversalPrinter<T2>::Print(value.second, os);
467 *os << ')';
468}
469
470// Implements printing a non-reference type T by letting the compiler
471// pick the right overload of PrintTo() for T.
472template <typename T>
473class UniversalPrinter {
474 public:
475 // MSVC warns about adding const to a function type, so we want to
476 // disable the warning.
477#ifdef _MSC_VER
478#pragma warning(push) // Saves the current warning state.
479#pragma warning(disable:4180) // Temporarily disables warning 4180.
480#endif // _MSC_VER
481
482 // Note: we deliberately don't call this PrintTo(), as that name
483 // conflicts with ::testing::internal::PrintTo in the body of the
484 // function.
485 static void Print(const T& value, ::std::ostream* os) {
486 // By default, ::testing::internal::PrintTo() is used for printing
487 // the value.
488 //
489 // Thanks to Koenig look-up, if T is a class and has its own
490 // PrintTo() function defined in its namespace, that function will
491 // be visible here. Since it is more specific than the generic ones
492 // in ::testing::internal, it will be picked by the compiler in the
493 // following statement - exactly what we want.
494 PrintTo(value, os);
495 }
496
497 // A convenient wrapper for Print() that returns the print-out as a
498 // string.
499 static string PrintAsString(const T& value) {
500 ::std::stringstream ss;
501 Print(value, &ss);
502 return ss.str();
503 }
504
505#ifdef _MSC_VER
506#pragma warning(pop) // Restores the warning state.
507#endif // _MSC_VER
508};
509
510// Implements printing an array type T[N].
511template <typename T, size_t N>
512class UniversalPrinter<T[N]> {
513 public:
514 // Prints the given array, omitting some elements when there are too
515 // many.
516 static void Print(const T (&a)[N], ::std::ostream* os) {
517 // Prints a char array as a C string. Note that we compare 'const
518 // T' with 'const char' instead of comparing T with char, in case
519 // that T is already a const type.
520 if (internal::type_equals<const T, const char>::value) {
521 UniversalPrinter<const T*>::Print(a, os);
522 return;
523 }
524
525 if (N == 0) {
526 *os << "{}";
527 } else {
528 *os << "{ ";
529 const size_t kThreshold = 18;
530 const size_t kChunkSize = 8;
531 // If the array has more than kThreshold elements, we'll have to
532 // omit some details by printing only the first and the last
533 // kChunkSize elements.
534 // TODO(wan): let the user control the threshold using a flag.
535 if (N <= kThreshold) {
536 PrintRawArrayTo(a, N, os);
537 } else {
538 PrintRawArrayTo(a, kChunkSize, os);
539 *os << ", ..., ";
540 PrintRawArrayTo(a + N - kChunkSize, kChunkSize, os);
541 }
542 *os << " }";
543 }
544 }
545
546 // A convenient wrapper for Print() that returns the print-out as a
547 // string.
548 static string PrintAsString(const T (&a)[N]) {
549 ::std::stringstream ss;
550 Print(a, &ss);
551 return ss.str();
552 }
553};
554
555// Implements printing a reference type T&.
556template <typename T>
557class UniversalPrinter<T&> {
558 public:
559 // MSVC warns about adding const to a function type, so we want to
560 // disable the warning.
561#ifdef _MSC_VER
562#pragma warning(push) // Saves the current warning state.
563#pragma warning(disable:4180) // Temporarily disables warning 4180.
564#endif // _MSC_VER
565
566 static void Print(const T& value, ::std::ostream* os) {
567 // Prints the address of the value. We use reinterpret_cast here
568 // as static_cast doesn't compile when T is a function type.
569 *os << "@" << reinterpret_cast<const void*>(&value) << " ";
570
571 // Then prints the value itself.
572 UniversalPrinter<T>::Print(value, os);
573 }
574
575 // A convenient wrapper for Print() that returns the print-out as a
576 // string.
577 static string PrintAsString(const T& value) {
578 ::std::stringstream ss;
579 Print(value, &ss);
580 return ss.str();
581 }
582
583#ifdef _MSC_VER
584#pragma warning(pop) // Restores the warning state.
585#endif // _MSC_VER
586};
587
588} // namespace internal
589} // namespace testing
590
591#endif // GMOCK_INCLUDE_GMOCK_GMOCK_PRINTERS_H_