blob: 628fc744ba55d8aa147f5cc2739d4f2899cf311b [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
368// We support tuples of up-to 10 fields. Note that an N-tuple type is
369// just an (N + 1)-tuple type where the last field has a special,
370// unused type.
371template <typename T1, typename T2, typename T3, typename T4, typename T5,
372 typename T6, typename T7, typename T8, typename T9, typename T10>
373void PrintTo(
374 const ::std::tr1::tuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>& t,
375 ::std::ostream* os) {
376 typedef ::std::tr1::tuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> Tuple;
377 *os << "(";
378 TuplePrefixPrinter< ::std::tr1::tuple_size<Tuple>::value>::
379 PrintPrefixTo(t, os);
380 *os << ")";
381}
382
383// Overload for std::pair.
384template <typename T1, typename T2>
385void PrintTo(const ::std::pair<T1, T2>& value, ::std::ostream* os) {
386 *os << '(';
387 UniversalPrinter<T1>::Print(value.first, os);
388 *os << ", ";
389 UniversalPrinter<T2>::Print(value.second, os);
390 *os << ')';
391}
392
393// Implements printing a non-reference type T by letting the compiler
394// pick the right overload of PrintTo() for T.
395template <typename T>
396class UniversalPrinter {
397 public:
398 // MSVC warns about adding const to a function type, so we want to
399 // disable the warning.
400#ifdef _MSC_VER
401#pragma warning(push) // Saves the current warning state.
402#pragma warning(disable:4180) // Temporarily disables warning 4180.
403#endif // _MSC_VER
404
405 // Note: we deliberately don't call this PrintTo(), as that name
406 // conflicts with ::testing::internal::PrintTo in the body of the
407 // function.
408 static void Print(const T& value, ::std::ostream* os) {
409 // By default, ::testing::internal::PrintTo() is used for printing
410 // the value.
411 //
412 // Thanks to Koenig look-up, if T is a class and has its own
413 // PrintTo() function defined in its namespace, that function will
414 // be visible here. Since it is more specific than the generic ones
415 // in ::testing::internal, it will be picked by the compiler in the
416 // following statement - exactly what we want.
417 PrintTo(value, os);
418 }
419
420 // A convenient wrapper for Print() that returns the print-out as a
421 // string.
422 static string PrintAsString(const T& value) {
423 ::std::stringstream ss;
424 Print(value, &ss);
425 return ss.str();
426 }
427
428#ifdef _MSC_VER
429#pragma warning(pop) // Restores the warning state.
430#endif // _MSC_VER
431};
432
433// Implements printing an array type T[N].
434template <typename T, size_t N>
435class UniversalPrinter<T[N]> {
436 public:
437 // Prints the given array, omitting some elements when there are too
438 // many.
439 static void Print(const T (&a)[N], ::std::ostream* os) {
440 // Prints a char array as a C string. Note that we compare 'const
441 // T' with 'const char' instead of comparing T with char, in case
442 // that T is already a const type.
443 if (internal::type_equals<const T, const char>::value) {
444 UniversalPrinter<const T*>::Print(a, os);
445 return;
446 }
447
448 if (N == 0) {
449 *os << "{}";
450 } else {
451 *os << "{ ";
452 const size_t kThreshold = 18;
453 const size_t kChunkSize = 8;
454 // If the array has more than kThreshold elements, we'll have to
455 // omit some details by printing only the first and the last
456 // kChunkSize elements.
457 // TODO(wan): let the user control the threshold using a flag.
458 if (N <= kThreshold) {
459 PrintRawArrayTo(a, N, os);
460 } else {
461 PrintRawArrayTo(a, kChunkSize, os);
462 *os << ", ..., ";
463 PrintRawArrayTo(a + N - kChunkSize, kChunkSize, os);
464 }
465 *os << " }";
466 }
467 }
468
469 // A convenient wrapper for Print() that returns the print-out as a
470 // string.
471 static string PrintAsString(const T (&a)[N]) {
472 ::std::stringstream ss;
473 Print(a, &ss);
474 return ss.str();
475 }
476};
477
478// Implements printing a reference type T&.
479template <typename T>
480class UniversalPrinter<T&> {
481 public:
482 // MSVC warns about adding const to a function type, so we want to
483 // disable the warning.
484#ifdef _MSC_VER
485#pragma warning(push) // Saves the current warning state.
486#pragma warning(disable:4180) // Temporarily disables warning 4180.
487#endif // _MSC_VER
488
489 static void Print(const T& value, ::std::ostream* os) {
490 // Prints the address of the value. We use reinterpret_cast here
491 // as static_cast doesn't compile when T is a function type.
492 *os << "@" << reinterpret_cast<const void*>(&value) << " ";
493
494 // Then prints the value itself.
495 UniversalPrinter<T>::Print(value, os);
496 }
497
498 // A convenient wrapper for Print() that returns the print-out as a
499 // string.
500 static string PrintAsString(const T& value) {
501 ::std::stringstream ss;
502 Print(value, &ss);
503 return ss.str();
504 }
505
506#ifdef _MSC_VER
507#pragma warning(pop) // Restores the warning state.
508#endif // _MSC_VER
509};
510
511} // namespace internal
512} // namespace testing
513
514#endif // GMOCK_INCLUDE_GMOCK_GMOCK_PRINTERS_H_