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