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// Google Test - The Google C++ Testing and Mocking Framework
31//
32// This file implements a universal value printer that can print a
33// value of any type T:
34//
35// void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);
36//
37// A user can teach this function how to print a class type T by
38// defining either operator<<() or PrintTo() in the namespace that
39// defines T. More specifically, the FIRST defined function in the
40// following list will be used (assuming T is defined in namespace
41// foo):
42//
43// 1. foo::PrintTo(const T&, ostream*)
44// 2. operator<<(ostream&, const T&) defined in either foo or the
45// global namespace.
46// * Prefer AbslStringify(..) to operator<<(..), per https://abseil.io/tips/215.
47// * Define foo::PrintTo(..) if the type already has AbslStringify(..), but an
48// alternative presentation in test results is of interest.
49//
50// However if T is an STL-style container then it is printed element-wise
51// unless foo::PrintTo(const T&, ostream*) is defined. Note that
52// operator<<() is ignored for container types.
53//
54// If none of the above is defined, it will print the debug string of
55// the value if it is a protocol buffer, or print the raw bytes in the
56// value otherwise.
57//
58// To aid debugging: when T is a reference type, the address of the
59// value is also printed; when T is a (const) char pointer, both the
60// pointer value and the NUL-terminated string it points to are
61// printed.
62//
63// We also provide some convenient wrappers:
64//
65// // Prints a value to a string. For a (const or not) char
66// // pointer, the NUL-terminated string (but not the pointer) is
67// // printed.
68// std::string ::testing::PrintToString(const T& value);
69//
70// // Prints a value tersely: for a reference type, the referenced
71// // value (but not the address) is printed; for a (const or not) char
72// // pointer, the NUL-terminated string (but not the pointer) is
73// // printed.
74// void ::testing::internal::UniversalTersePrint(const T& value, ostream*);
75//
76// // Prints value using the type inferred by the compiler. The difference
77// // from UniversalTersePrint() is that this function prints both the
78// // pointer and the NUL-terminated string for a (const or not) char pointer.
79// void ::testing::internal::UniversalPrint(const T& value, ostream*);
80//
81// // Prints the fields of a tuple tersely to a string vector, one
82// // element for each field. Tuple support must be enabled in
83// // gtest-port.h.
84// std::vector<string> UniversalTersePrintTupleFieldsToStrings(
85// const Tuple& value);
86//
87// Known limitation:
88//
89// The print primitives print the elements of an STL-style container
90// using the compiler-inferred type of *iter where iter is a
91// const_iterator of the container. When const_iterator is an input
92// iterator but not a forward iterator, this inferred type may not
93// match value_type, and the print output may be incorrect. In
94// practice, this is rarely a problem as for most containers
95// const_iterator is a forward iterator. We'll fix this if there's an
96// actual need for it. Note that this fix cannot rely on value_type
97// being defined as many user-defined container types don't have
98// value_type.
99
100// IWYU pragma: private, include "gtest/gtest.h"
101// IWYU pragma: friend gtest/.*
102// IWYU pragma: friend gmock/.*
103
104#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
105#define GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
106
107#include <functional>
108#include <memory>
109#include <ostream> // NOLINT
110#include <sstream>
111#include <string>
112#include <tuple>
113#include <type_traits>
114#include <typeinfo>
115#include <utility>
116#include <vector>
117
118#ifdef GTEST_HAS_ABSL
119#include "absl/strings/internal/has_absl_stringify.h"
120#include "absl/strings/str_cat.h"
121#endif // GTEST_HAS_ABSL
122#include "gtest/internal/gtest-internal.h"
123#include "gtest/internal/gtest-port.h"
124
125namespace testing {
126
127// Definitions in the internal* namespaces are subject to change without notice.
128// DO NOT USE THEM IN USER CODE!
129namespace internal {
130
131template <typename T>
132void UniversalPrint(const T& value, ::std::ostream* os);
133
134// Used to print an STL-style container when the user doesn't define
135// a PrintTo() for it.
136struct ContainerPrinter {
137 template <typename T,
138 typename = typename std::enable_if<
139 (sizeof(IsContainerTest<T>(0)) == sizeof(IsContainer)) &&
140 !IsRecursiveContainer<T>::value>::type>
141 static void PrintValue(const T& container, std::ostream* os) {
142 const size_t kMaxCount = 32; // The maximum number of elements to print.
143 *os << '{';
144 size_t count = 0;
145 for (auto&& elem : container) {
146 if (count > 0) {
147 *os << ',';
148 if (count == kMaxCount) { // Enough has been printed.
149 *os << " ...";
150 break;
151 }
152 }
153 *os << ' ';
154 // We cannot call PrintTo(elem, os) here as PrintTo() doesn't
155 // handle `elem` being a native array.
156 internal::UniversalPrint(elem, os);
157 ++count;
158 }
159
160 if (count > 0) {
161 *os << ' ';
162 }
163 *os << '}';
164 }
165};
166
167// Used to print a pointer that is neither a char pointer nor a member
168// pointer, when the user doesn't define PrintTo() for it. (A member
169// variable pointer or member function pointer doesn't really point to
170// a location in the address space. Their representation is
171// implementation-defined. Therefore they will be printed as raw
172// bytes.)
173struct FunctionPointerPrinter {
174 template <typename T, typename = typename std::enable_if<
175 std::is_function<T>::value>::type>
176 static void PrintValue(T* p, ::std::ostream* os) {
177 if (p == nullptr) {
178 *os << "NULL";
179 } else {
180 // T is a function type, so '*os << p' doesn't do what we want
181 // (it just prints p as bool). We want to print p as a const
182 // void*.
183 *os << reinterpret_cast<const void*>(p);
184 }
185 }
186};
187
188struct PointerPrinter {
189 template <typename T>
190 static void PrintValue(T* p, ::std::ostream* os) {
191 if (p == nullptr) {
192 *os << "NULL";
193 } else {
194 // T is not a function type. We just call << to print p,
195 // relying on ADL to pick up user-defined << for their pointer
196 // types, if any.
197 *os << p;
198 }
199 }
200};
201
202namespace internal_stream_operator_without_lexical_name_lookup {
203
204// The presence of an operator<< here will terminate lexical scope lookup
205// straight away (even though it cannot be a match because of its argument
206// types). Thus, the two operator<< calls in StreamPrinter will find only ADL
207// candidates.
208struct LookupBlocker {};
209void operator<<(LookupBlocker, LookupBlocker);
210
211struct StreamPrinter {
212 template <typename T,
213 // Don't accept member pointers here. We'd print them via implicit
214 // conversion to bool, which isn't useful.
215 typename = typename std::enable_if<
216 !std::is_member_pointer<T>::value>::type>
217 // Only accept types for which we can find a streaming operator via
218 // ADL (possibly involving implicit conversions).
219 // (Use SFINAE via return type, because it seems GCC < 12 doesn't handle name
220 // lookup properly when we do it in the template parameter list.)
221
222 // LLVM local change to support llvm printables.
223 //
224 // static auto PrintValue(const T& value, ::std::ostream* os)
225 // -> decltype((void)(*os << value)) {
226 // // Call streaming operator found by ADL, possibly with implicit conversions
227 // // of the arguments.
228 // // LLVM local change to support llvm printables.
229 // //
230 // *os << value;
231 // // LLVM local change end.
232 // }
233 static auto PrintValue(const T& value, ::std::ostream* os)
234 -> decltype((void)(*os << ::llvm_gtest::printable(value))) {
235 // Call streaming operator found by ADL, possibly with implicit conversions
236 // of the arguments.
237 // LLVM local change to support llvm printables.
238 //
239 *os << ::llvm_gtest::printable(value);
240 // LLVM local change end.
241 }
242};
243
244} // namespace internal_stream_operator_without_lexical_name_lookup
245
246struct ProtobufPrinter {
247 // We print a protobuf using its ShortDebugString() when the string
248 // doesn't exceed this many characters; otherwise we print it using
249 // DebugString() for better readability.
250 static const size_t kProtobufOneLinerMaxLength = 50;
251
252 template <typename T,
253 typename = typename std::enable_if<
254 internal::HasDebugStringAndShortDebugString<T>::value>::type>
255 static void PrintValue(const T& value, ::std::ostream* os) {
256 std::string pretty_str = value.ShortDebugString();
257 if (pretty_str.length() > kProtobufOneLinerMaxLength) {
258 pretty_str = "\n" + value.DebugString();
259 }
260 *os << ("<" + pretty_str + ">");
261 }
262};
263
264struct ConvertibleToIntegerPrinter {
265 // Since T has no << operator or PrintTo() but can be implicitly
266 // converted to BiggestInt, we print it as a BiggestInt.
267 //
268 // Most likely T is an enum type (either named or unnamed), in which
269 // case printing it as an integer is the desired behavior. In case
270 // T is not an enum, printing it as an integer is the best we can do
271 // given that it has no user-defined printer.
272 static void PrintValue(internal::BiggestInt value, ::std::ostream* os) {
273 *os << value;
274 }
275};
276
277struct ConvertibleToStringViewPrinter {
278#if GTEST_INTERNAL_HAS_STRING_VIEW
279 static void PrintValue(internal::StringView value, ::std::ostream* os) {
280 internal::UniversalPrint(value, os);
281 }
282#endif
283};
284
285#ifdef GTEST_HAS_ABSL
286struct ConvertibleToAbslStringifyPrinter {
287 template <
288 typename T,
289 typename = typename std::enable_if<
290 absl::strings_internal::HasAbslStringify<T>::value>::type> // NOLINT
291 static void PrintValue(const T& value, ::std::ostream* os) {
292 *os << absl::StrCat(value);
293 }
294};
295#endif // GTEST_HAS_ABSL
296
297// Prints the given number of bytes in the given object to the given
298// ostream.
299GTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes,
300 size_t count, ::std::ostream* os);
301struct RawBytesPrinter {
302 // SFINAE on `sizeof` to make sure we have a complete type.
303 template <typename T, size_t = sizeof(T)>
304 static void PrintValue(const T& value, ::std::ostream* os) {
305 PrintBytesInObjectTo(
306 obj_bytes: static_cast<const unsigned char*>(
307 // Load bearing cast to void* to support iOS
308 reinterpret_cast<const void*>(std::addressof(value))),
309 count: sizeof(value), os);
310 }
311};
312
313struct FallbackPrinter {
314 template <typename T>
315 static void PrintValue(const T&, ::std::ostream* os) {
316 *os << "(incomplete type)";
317 }
318};
319
320// Try every printer in order and return the first one that works.
321template <typename T, typename E, typename Printer, typename... Printers>
322struct FindFirstPrinter : FindFirstPrinter<T, E, Printers...> {};
323
324template <typename T, typename Printer, typename... Printers>
325struct FindFirstPrinter<
326 T, decltype(Printer::PrintValue(std::declval<const T&>(), nullptr)),
327 Printer, Printers...> {
328 using type = Printer;
329};
330
331// Select the best printer in the following order:
332// - Print containers (they have begin/end/etc).
333// - Print function pointers.
334// - Print object pointers.
335// - Print protocol buffers.
336// - Use the stream operator, if available.
337// - Print types convertible to BiggestInt.
338// - Print types convertible to StringView, if available.
339// - Fallback to printing the raw bytes of the object.
340template <typename T>
341void PrintWithFallback(const T& value, ::std::ostream* os) {
342 using Printer = typename FindFirstPrinter<
343 T, void, ContainerPrinter, FunctionPointerPrinter, PointerPrinter,
344 ProtobufPrinter,
345#ifdef GTEST_HAS_ABSL
346 ConvertibleToAbslStringifyPrinter,
347#endif // GTEST_HAS_ABSL
348 internal_stream_operator_without_lexical_name_lookup::StreamPrinter,
349 ConvertibleToIntegerPrinter, ConvertibleToStringViewPrinter,
350 RawBytesPrinter, FallbackPrinter>::type;
351 Printer::PrintValue(value, os);
352}
353
354// FormatForComparison<ToPrint, OtherOperand>::Format(value) formats a
355// value of type ToPrint that is an operand of a comparison assertion
356// (e.g. ASSERT_EQ). OtherOperand is the type of the other operand in
357// the comparison, and is used to help determine the best way to
358// format the value. In particular, when the value is a C string
359// (char pointer) and the other operand is an STL string object, we
360// want to format the C string as a string, since we know it is
361// compared by value with the string object. If the value is a char
362// pointer but the other operand is not an STL string object, we don't
363// know whether the pointer is supposed to point to a NUL-terminated
364// string, and thus want to print it as a pointer to be safe.
365//
366// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
367
368// The default case.
369template <typename ToPrint, typename OtherOperand>
370class FormatForComparison {
371 public:
372 static ::std::string Format(const ToPrint& value) {
373 return ::testing::PrintToString(value);
374 }
375};
376
377// Array.
378template <typename ToPrint, size_t N, typename OtherOperand>
379class FormatForComparison<ToPrint[N], OtherOperand> {
380 public:
381 static ::std::string Format(const ToPrint* value) {
382 return FormatForComparison<const ToPrint*, OtherOperand>::Format(value);
383 }
384};
385
386// By default, print C string as pointers to be safe, as we don't know
387// whether they actually point to a NUL-terminated string.
388
389#define GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(CharType) \
390 template <typename OtherOperand> \
391 class FormatForComparison<CharType*, OtherOperand> { \
392 public: \
393 static ::std::string Format(CharType* value) { \
394 return ::testing::PrintToString(static_cast<const void*>(value)); \
395 } \
396 }
397
398GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char);
399GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char);
400GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(wchar_t);
401GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const wchar_t);
402#ifdef __cpp_lib_char8_t
403GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char8_t);
404GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char8_t);
405#endif
406GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char16_t);
407GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char16_t);
408GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char32_t);
409GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char32_t);
410
411#undef GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_
412
413// If a C string is compared with an STL string object, we know it's meant
414// to point to a NUL-terminated string, and thus can print it as a string.
415
416#define GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(CharType, OtherStringType) \
417 template <> \
418 class FormatForComparison<CharType*, OtherStringType> { \
419 public: \
420 static ::std::string Format(CharType* value) { \
421 return ::testing::PrintToString(value); \
422 } \
423 }
424
425GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::std::string);
426GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char, ::std::string);
427#ifdef __cpp_lib_char8_t
428GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char8_t, ::std::u8string);
429GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char8_t, ::std::u8string);
430#endif
431GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char16_t, ::std::u16string);
432GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char16_t, ::std::u16string);
433GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char32_t, ::std::u32string);
434GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char32_t, ::std::u32string);
435
436#if GTEST_HAS_STD_WSTRING
437GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(wchar_t, ::std::wstring);
438GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const wchar_t, ::std::wstring);
439#endif
440
441#undef GTEST_IMPL_FORMAT_C_STRING_AS_STRING_
442
443// Formats a comparison assertion (e.g. ASSERT_EQ, EXPECT_LT, and etc)
444// operand to be used in a failure message. The type (but not value)
445// of the other operand may affect the format. This allows us to
446// print a char* as a raw pointer when it is compared against another
447// char* or void*, and print it as a C string when it is compared
448// against an std::string object, for example.
449//
450// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
451template <typename T1, typename T2>
452std::string FormatForComparisonFailureMessage(const T1& value,
453 const T2& /* other_operand */) {
454 return FormatForComparison<T1, T2>::Format(value);
455}
456
457// UniversalPrinter<T>::Print(value, ostream_ptr) prints the given
458// value to the given ostream. The caller must ensure that
459// 'ostream_ptr' is not NULL, or the behavior is undefined.
460//
461// We define UniversalPrinter as a class template (as opposed to a
462// function template), as we need to partially specialize it for
463// reference types, which cannot be done with function templates.
464template <typename T>
465class UniversalPrinter;
466
467// Prints the given value using the << operator if it has one;
468// otherwise prints the bytes in it. This is what
469// UniversalPrinter<T>::Print() does when PrintTo() is not specialized
470// or overloaded for type T.
471//
472// A user can override this behavior for a class type Foo by defining
473// an overload of PrintTo() in the namespace where Foo is defined. We
474// give the user this option as sometimes defining a << operator for
475// Foo is not desirable (e.g. the coding style may prevent doing it,
476// or there is already a << operator but it doesn't do what the user
477// wants).
478template <typename T>
479void PrintTo(const T& value, ::std::ostream* os) {
480 internal::PrintWithFallback(value, os);
481}
482
483// The following list of PrintTo() overloads tells
484// UniversalPrinter<T>::Print() how to print standard types (built-in
485// types, strings, plain arrays, and pointers).
486
487// Overloads for various char types.
488GTEST_API_ void PrintTo(unsigned char c, ::std::ostream* os);
489GTEST_API_ void PrintTo(signed char c, ::std::ostream* os);
490inline void PrintTo(char c, ::std::ostream* os) {
491 // When printing a plain char, we always treat it as unsigned. This
492 // way, the output won't be affected by whether the compiler thinks
493 // char is signed or not.
494 PrintTo(c: static_cast<unsigned char>(c), os);
495}
496
497// Overloads for other simple built-in types.
498inline void PrintTo(bool x, ::std::ostream* os) {
499 *os << (x ? "true" : "false");
500}
501
502// Overload for wchar_t type.
503// Prints a wchar_t as a symbol if it is printable or as its internal
504// code otherwise and also as its decimal code (except for L'\0').
505// The L'\0' char is printed as "L'\\0'". The decimal code is printed
506// as signed integer when wchar_t is implemented by the compiler
507// as a signed type and is printed as an unsigned integer when wchar_t
508// is implemented as an unsigned type.
509GTEST_API_ void PrintTo(wchar_t wc, ::std::ostream* os);
510
511GTEST_API_ void PrintTo(char32_t c, ::std::ostream* os);
512inline void PrintTo(char16_t c, ::std::ostream* os) {
513 PrintTo(c: ImplicitCast_<char32_t>(x: c), os);
514}
515#ifdef __cpp_lib_char8_t
516inline void PrintTo(char8_t c, ::std::ostream* os) {
517 PrintTo(ImplicitCast_<char32_t>(c), os);
518}
519#endif
520
521// gcc/clang __{u,}int128_t
522#if defined(__SIZEOF_INT128__)
523GTEST_API_ void PrintTo(__uint128_t v, ::std::ostream* os);
524GTEST_API_ void PrintTo(__int128_t v, ::std::ostream* os);
525#endif // __SIZEOF_INT128__
526
527// The default resolution used to print floating-point values uses only
528// 6 digits, which can be confusing if a test compares two values whose
529// difference lies in the 7th digit. So we'd like to print out numbers
530// in full precision.
531// However if the value is something simple like 1.1, full will print a
532// long string like 1.100000001 due to floating-point numbers not using
533// a base of 10. This routiune returns an appropriate resolution for a
534// given floating-point number, that is, 6 if it will be accurate, or a
535// max_digits10 value (full precision) if it won't, for values between
536// 0.0001 and one million.
537// It does this by computing what those digits would be (by multiplying
538// by an appropriate power of 10), then dividing by that power again to
539// see if gets the original value back.
540// A similar algorithm applies for values larger than one million; note
541// that for those values, we must divide to get a six-digit number, and
542// then multiply to possibly get the original value again.
543template <typename FloatType>
544int AppropriateResolution(FloatType val) {
545 int full = std::numeric_limits<FloatType>::max_digits10;
546 if (val < 0) val = -val;
547
548 if (val < 1000000) {
549 FloatType mulfor6 = 1e10;
550 if (val >= 100000.0) { // 100,000 to 999,999
551 mulfor6 = 1.0;
552 } else if (val >= 10000.0) {
553 mulfor6 = 1e1;
554 } else if (val >= 1000.0) {
555 mulfor6 = 1e2;
556 } else if (val >= 100.0) {
557 mulfor6 = 1e3;
558 } else if (val >= 10.0) {
559 mulfor6 = 1e4;
560 } else if (val >= 1.0) {
561 mulfor6 = 1e5;
562 } else if (val >= 0.1) {
563 mulfor6 = 1e6;
564 } else if (val >= 0.01) {
565 mulfor6 = 1e7;
566 } else if (val >= 0.001) {
567 mulfor6 = 1e8;
568 } else if (val >= 0.0001) {
569 mulfor6 = 1e9;
570 }
571 if (static_cast<FloatType>(static_cast<int32_t>(val * mulfor6 + 0.5)) /
572 mulfor6 ==
573 val)
574 return 6;
575 } else if (val < 1e10) {
576 FloatType divfor6 = 1.0;
577 if (val >= 1e9) { // 1,000,000,000 to 9,999,999,999
578 divfor6 = 10000;
579 } else if (val >= 1e8) { // 100,000,000 to 999,999,999
580 divfor6 = 1000;
581 } else if (val >= 1e7) { // 10,000,000 to 99,999,999
582 divfor6 = 100;
583 } else if (val >= 1e6) { // 1,000,000 to 9,999,999
584 divfor6 = 10;
585 }
586 if (static_cast<FloatType>(static_cast<int32_t>(val / divfor6 + 0.5)) *
587 divfor6 ==
588 val)
589 return 6;
590 }
591 return full;
592}
593
594inline void PrintTo(float f, ::std::ostream* os) {
595 auto old_precision = os->precision();
596 os->precision(prec: AppropriateResolution(val: f));
597 *os << f;
598 os->precision(prec: old_precision);
599}
600
601inline void PrintTo(double d, ::std::ostream* os) {
602 auto old_precision = os->precision();
603 os->precision(prec: AppropriateResolution(val: d));
604 *os << d;
605 os->precision(prec: old_precision);
606}
607
608// Overloads for C strings.
609GTEST_API_ void PrintTo(const char* s, ::std::ostream* os);
610inline void PrintTo(char* s, ::std::ostream* os) {
611 PrintTo(s: ImplicitCast_<const char*>(x: s), os);
612}
613
614// signed/unsigned char is often used for representing binary data, so
615// we print pointers to it as void* to be safe.
616inline void PrintTo(const signed char* s, ::std::ostream* os) {
617 PrintTo(value: ImplicitCast_<const void*>(x: s), os);
618}
619inline void PrintTo(signed char* s, ::std::ostream* os) {
620 PrintTo(value: ImplicitCast_<const void*>(x: s), os);
621}
622inline void PrintTo(const unsigned char* s, ::std::ostream* os) {
623 PrintTo(value: ImplicitCast_<const void*>(x: s), os);
624}
625inline void PrintTo(unsigned char* s, ::std::ostream* os) {
626 PrintTo(value: ImplicitCast_<const void*>(x: s), os);
627}
628#ifdef __cpp_lib_char8_t
629// Overloads for u8 strings.
630GTEST_API_ void PrintTo(const char8_t* s, ::std::ostream* os);
631inline void PrintTo(char8_t* s, ::std::ostream* os) {
632 PrintTo(ImplicitCast_<const char8_t*>(s), os);
633}
634#endif
635// Overloads for u16 strings.
636GTEST_API_ void PrintTo(const char16_t* s, ::std::ostream* os);
637inline void PrintTo(char16_t* s, ::std::ostream* os) {
638 PrintTo(s: ImplicitCast_<const char16_t*>(x: s), os);
639}
640// Overloads for u32 strings.
641GTEST_API_ void PrintTo(const char32_t* s, ::std::ostream* os);
642inline void PrintTo(char32_t* s, ::std::ostream* os) {
643 PrintTo(s: ImplicitCast_<const char32_t*>(x: s), os);
644}
645
646// MSVC can be configured to define wchar_t as a typedef of unsigned
647// short. It defines _NATIVE_WCHAR_T_DEFINED when wchar_t is a native
648// type. When wchar_t is a typedef, defining an overload for const
649// wchar_t* would cause unsigned short* be printed as a wide string,
650// possibly causing invalid memory accesses.
651#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
652// Overloads for wide C strings
653GTEST_API_ void PrintTo(const wchar_t* s, ::std::ostream* os);
654inline void PrintTo(wchar_t* s, ::std::ostream* os) {
655 PrintTo(s: ImplicitCast_<const wchar_t*>(x: s), os);
656}
657#endif
658
659// Overload for C arrays. Multi-dimensional arrays are printed
660// properly.
661
662// Prints the given number of elements in an array, without printing
663// the curly braces.
664template <typename T>
665void PrintRawArrayTo(const T a[], size_t count, ::std::ostream* os) {
666 UniversalPrint(a[0], os);
667 for (size_t i = 1; i != count; i++) {
668 *os << ", ";
669 UniversalPrint(a[i], os);
670 }
671}
672
673// Overloads for ::std::string.
674GTEST_API_ void PrintStringTo(const ::std::string& s, ::std::ostream* os);
675inline void PrintTo(const ::std::string& s, ::std::ostream* os) {
676 PrintStringTo(s, os);
677}
678
679// Overloads for ::std::u8string
680#ifdef __cpp_lib_char8_t
681GTEST_API_ void PrintU8StringTo(const ::std::u8string& s, ::std::ostream* os);
682inline void PrintTo(const ::std::u8string& s, ::std::ostream* os) {
683 PrintU8StringTo(s, os);
684}
685#endif
686
687// Overloads for ::std::u16string
688GTEST_API_ void PrintU16StringTo(const ::std::u16string& s, ::std::ostream* os);
689inline void PrintTo(const ::std::u16string& s, ::std::ostream* os) {
690 PrintU16StringTo(s, os);
691}
692
693// Overloads for ::std::u32string
694GTEST_API_ void PrintU32StringTo(const ::std::u32string& s, ::std::ostream* os);
695inline void PrintTo(const ::std::u32string& s, ::std::ostream* os) {
696 PrintU32StringTo(s, os);
697}
698
699// Overloads for ::std::wstring.
700#if GTEST_HAS_STD_WSTRING
701GTEST_API_ void PrintWideStringTo(const ::std::wstring& s, ::std::ostream* os);
702inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) {
703 PrintWideStringTo(s, os);
704}
705#endif // GTEST_HAS_STD_WSTRING
706
707#if GTEST_INTERNAL_HAS_STRING_VIEW
708// Overload for internal::StringView.
709inline void PrintTo(internal::StringView sp, ::std::ostream* os) {
710 PrintTo(s: ::std::string(sp), os);
711}
712#endif // GTEST_INTERNAL_HAS_STRING_VIEW
713
714inline void PrintTo(std::nullptr_t, ::std::ostream* os) { *os << "(nullptr)"; }
715
716#if GTEST_HAS_RTTI
717inline void PrintTo(const std::type_info& info, std::ostream* os) {
718 *os << internal::GetTypeName(info);
719}
720#endif // GTEST_HAS_RTTI
721
722template <typename T>
723void PrintTo(std::reference_wrapper<T> ref, ::std::ostream* os) {
724 UniversalPrinter<T&>::Print(ref.get(), os);
725}
726
727inline const void* VoidifyPointer(const void* p) { return p; }
728inline const void* VoidifyPointer(volatile const void* p) {
729 return const_cast<const void*>(p);
730}
731
732template <typename T, typename Ptr>
733void PrintSmartPointer(const Ptr& ptr, std::ostream* os, char) {
734 if (ptr == nullptr) {
735 *os << "(nullptr)";
736 } else {
737 // We can't print the value. Just print the pointer..
738 *os << "(" << (VoidifyPointer)(ptr.get()) << ")";
739 }
740}
741template <typename T, typename Ptr,
742 typename = typename std::enable_if<!std::is_void<T>::value &&
743 !std::is_array<T>::value>::type>
744void PrintSmartPointer(const Ptr& ptr, std::ostream* os, int) {
745 if (ptr == nullptr) {
746 *os << "(nullptr)";
747 } else {
748 *os << "(ptr = " << (VoidifyPointer)(ptr.get()) << ", value = ";
749 UniversalPrinter<T>::Print(*ptr, os);
750 *os << ")";
751 }
752}
753
754template <typename T, typename D>
755void PrintTo(const std::unique_ptr<T, D>& ptr, std::ostream* os) {
756 (PrintSmartPointer<T>)(ptr, os, 0);
757}
758
759template <typename T>
760void PrintTo(const std::shared_ptr<T>& ptr, std::ostream* os) {
761 (PrintSmartPointer<T>)(ptr, os, 0);
762}
763
764// Helper function for printing a tuple. T must be instantiated with
765// a tuple type.
766template <typename T>
767void PrintTupleTo(const T&, std::integral_constant<size_t, 0>,
768 ::std::ostream*) {}
769
770template <typename T, size_t I>
771void PrintTupleTo(const T& t, std::integral_constant<size_t, I>,
772 ::std::ostream* os) {
773 PrintTupleTo(t, std::integral_constant<size_t, I - 1>(), os);
774 GTEST_INTENTIONAL_CONST_COND_PUSH_()
775 if (I > 1) {
776 GTEST_INTENTIONAL_CONST_COND_POP_()
777 *os << ", ";
778 }
779 UniversalPrinter<typename std::tuple_element<I - 1, T>::type>::Print(
780 std::get<I - 1>(t), os);
781}
782
783template <typename... Types>
784void PrintTo(const ::std::tuple<Types...>& t, ::std::ostream* os) {
785 *os << "(";
786 PrintTupleTo(t, std::integral_constant<size_t, sizeof...(Types)>(), os);
787 *os << ")";
788}
789
790// Overload for std::pair.
791template <typename T1, typename T2>
792void PrintTo(const ::std::pair<T1, T2>& value, ::std::ostream* os) {
793 *os << '(';
794 // We cannot use UniversalPrint(value.first, os) here, as T1 may be
795 // a reference type. The same for printing value.second.
796 UniversalPrinter<T1>::Print(value.first, os);
797 *os << ", ";
798 UniversalPrinter<T2>::Print(value.second, os);
799 *os << ')';
800}
801
802// Implements printing a non-reference type T by letting the compiler
803// pick the right overload of PrintTo() for T.
804template <typename T>
805class UniversalPrinter {
806 public:
807 // MSVC warns about adding const to a function type, so we want to
808 // disable the warning.
809 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180)
810
811 // Note: we deliberately don't call this PrintTo(), as that name
812 // conflicts with ::testing::internal::PrintTo in the body of the
813 // function.
814 static void Print(const T& value, ::std::ostream* os) {
815 // By default, ::testing::internal::PrintTo() is used for printing
816 // the value.
817 //
818 // Thanks to Koenig look-up, if T is a class and has its own
819 // PrintTo() function defined in its namespace, that function will
820 // be visible here. Since it is more specific than the generic ones
821 // in ::testing::internal, it will be picked by the compiler in the
822 // following statement - exactly what we want.
823 PrintTo(value, os);
824 }
825
826 GTEST_DISABLE_MSC_WARNINGS_POP_()
827};
828
829// Remove any const-qualifiers before passing a type to UniversalPrinter.
830template <typename T>
831class UniversalPrinter<const T> : public UniversalPrinter<T> {};
832
833#if GTEST_INTERNAL_HAS_ANY
834
835// Printer for std::any / absl::any
836
837template <>
838class UniversalPrinter<Any> {
839 public:
840 static void Print(const Any& value, ::std::ostream* os) {
841 if (value.has_value()) {
842 *os << "value of type " << GetTypeName(value);
843 } else {
844 *os << "no value";
845 }
846 }
847
848 private:
849 static std::string GetTypeName(const Any& value) {
850#if GTEST_HAS_RTTI
851 return internal::GetTypeName(value.type());
852#else
853 static_cast<void>(value); // possibly unused
854 return "<unknown_type>";
855#endif // GTEST_HAS_RTTI
856 }
857};
858
859#endif // GTEST_INTERNAL_HAS_ANY
860
861#if GTEST_INTERNAL_HAS_OPTIONAL
862
863// Printer for std::optional / absl::optional
864
865template <typename T>
866class UniversalPrinter<Optional<T>> {
867 public:
868 static void Print(const Optional<T>& value, ::std::ostream* os) {
869 *os << '(';
870 if (!value) {
871 *os << "nullopt";
872 } else {
873 UniversalPrint(*value, os);
874 }
875 *os << ')';
876 }
877};
878
879template <>
880class UniversalPrinter<decltype(Nullopt())> {
881 public:
882 static void Print(decltype(Nullopt()), ::std::ostream* os) {
883 *os << "(nullopt)";
884 }
885};
886
887#endif // GTEST_INTERNAL_HAS_OPTIONAL
888
889#if GTEST_INTERNAL_HAS_VARIANT
890
891// Printer for std::variant / absl::variant
892
893template <typename... T>
894class UniversalPrinter<Variant<T...>> {
895 public:
896 static void Print(const Variant<T...>& value, ::std::ostream* os) {
897 *os << '(';
898#ifdef GTEST_HAS_ABSL
899 absl::visit(Visitor{os, value.index()}, value);
900#else
901 std::visit(Visitor{os, value.index()}, value);
902#endif // GTEST_HAS_ABSL
903 *os << ')';
904 }
905
906 private:
907 struct Visitor {
908 template <typename U>
909 void operator()(const U& u) const {
910 *os << "'" << GetTypeName<U>() << "(index = " << index
911 << ")' with value ";
912 UniversalPrint(u, os);
913 }
914 ::std::ostream* os;
915 std::size_t index;
916 };
917};
918
919#endif // GTEST_INTERNAL_HAS_VARIANT
920
921// UniversalPrintArray(begin, len, os) prints an array of 'len'
922// elements, starting at address 'begin'.
923template <typename T>
924void UniversalPrintArray(const T* begin, size_t len, ::std::ostream* os) {
925 if (len == 0) {
926 *os << "{}";
927 } else {
928 *os << "{ ";
929 const size_t kThreshold = 18;
930 const size_t kChunkSize = 8;
931 // If the array has more than kThreshold elements, we'll have to
932 // omit some details by printing only the first and the last
933 // kChunkSize elements.
934 if (len <= kThreshold) {
935 PrintRawArrayTo(begin, len, os);
936 } else {
937 PrintRawArrayTo(begin, kChunkSize, os);
938 *os << ", ..., ";
939 PrintRawArrayTo(begin + len - kChunkSize, kChunkSize, os);
940 }
941 *os << " }";
942 }
943}
944// This overload prints a (const) char array compactly.
945GTEST_API_ void UniversalPrintArray(const char* begin, size_t len,
946 ::std::ostream* os);
947
948#ifdef __cpp_lib_char8_t
949// This overload prints a (const) char8_t array compactly.
950GTEST_API_ void UniversalPrintArray(const char8_t* begin, size_t len,
951 ::std::ostream* os);
952#endif
953
954// This overload prints a (const) char16_t array compactly.
955GTEST_API_ void UniversalPrintArray(const char16_t* begin, size_t len,
956 ::std::ostream* os);
957
958// This overload prints a (const) char32_t array compactly.
959GTEST_API_ void UniversalPrintArray(const char32_t* begin, size_t len,
960 ::std::ostream* os);
961
962// This overload prints a (const) wchar_t array compactly.
963GTEST_API_ void UniversalPrintArray(const wchar_t* begin, size_t len,
964 ::std::ostream* os);
965
966// Implements printing an array type T[N].
967template <typename T, size_t N>
968class UniversalPrinter<T[N]> {
969 public:
970 // Prints the given array, omitting some elements when there are too
971 // many.
972 static void Print(const T (&a)[N], ::std::ostream* os) {
973 UniversalPrintArray(a, N, os);
974 }
975};
976
977// Implements printing a reference type T&.
978template <typename T>
979class UniversalPrinter<T&> {
980 public:
981 // MSVC warns about adding const to a function type, so we want to
982 // disable the warning.
983 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180)
984
985 static void Print(const T& value, ::std::ostream* os) {
986 // Prints the address of the value. We use reinterpret_cast here
987 // as static_cast doesn't compile when T is a function type.
988 *os << "@" << reinterpret_cast<const void*>(&value) << " ";
989
990 // Then prints the value itself.
991 UniversalPrint(value, os);
992 }
993
994 GTEST_DISABLE_MSC_WARNINGS_POP_()
995};
996
997// Prints a value tersely: for a reference type, the referenced value
998// (but not the address) is printed; for a (const) char pointer, the
999// NUL-terminated string (but not the pointer) is printed.
1000
1001template <typename T>
1002class UniversalTersePrinter {
1003 public:
1004 static void Print(const T& value, ::std::ostream* os) {
1005 UniversalPrint(value, os);
1006 }
1007};
1008template <typename T>
1009class UniversalTersePrinter<T&> {
1010 public:
1011 static void Print(const T& value, ::std::ostream* os) {
1012 UniversalPrint(value, os);
1013 }
1014};
1015template <typename T>
1016class UniversalTersePrinter<std::reference_wrapper<T>> {
1017 public:
1018 static void Print(std::reference_wrapper<T> value, ::std::ostream* os) {
1019 UniversalTersePrinter<T>::Print(value.get(), os);
1020 }
1021};
1022template <typename T, size_t N>
1023class UniversalTersePrinter<T[N]> {
1024 public:
1025 static void Print(const T (&value)[N], ::std::ostream* os) {
1026 UniversalPrinter<T[N]>::Print(value, os);
1027 }
1028};
1029template <>
1030class UniversalTersePrinter<const char*> {
1031 public:
1032 static void Print(const char* str, ::std::ostream* os) {
1033 if (str == nullptr) {
1034 *os << "NULL";
1035 } else {
1036 UniversalPrint(value: std::string(str), os);
1037 }
1038 }
1039};
1040template <>
1041class UniversalTersePrinter<char*> : public UniversalTersePrinter<const char*> {
1042};
1043
1044#ifdef __cpp_lib_char8_t
1045template <>
1046class UniversalTersePrinter<const char8_t*> {
1047 public:
1048 static void Print(const char8_t* str, ::std::ostream* os) {
1049 if (str == nullptr) {
1050 *os << "NULL";
1051 } else {
1052 UniversalPrint(::std::u8string(str), os);
1053 }
1054 }
1055};
1056template <>
1057class UniversalTersePrinter<char8_t*>
1058 : public UniversalTersePrinter<const char8_t*> {};
1059#endif
1060
1061template <>
1062class UniversalTersePrinter<const char16_t*> {
1063 public:
1064 static void Print(const char16_t* str, ::std::ostream* os) {
1065 if (str == nullptr) {
1066 *os << "NULL";
1067 } else {
1068 UniversalPrint(value: ::std::u16string(str), os);
1069 }
1070 }
1071};
1072template <>
1073class UniversalTersePrinter<char16_t*>
1074 : public UniversalTersePrinter<const char16_t*> {};
1075
1076template <>
1077class UniversalTersePrinter<const char32_t*> {
1078 public:
1079 static void Print(const char32_t* str, ::std::ostream* os) {
1080 if (str == nullptr) {
1081 *os << "NULL";
1082 } else {
1083 UniversalPrint(value: ::std::u32string(str), os);
1084 }
1085 }
1086};
1087template <>
1088class UniversalTersePrinter<char32_t*>
1089 : public UniversalTersePrinter<const char32_t*> {};
1090
1091#if GTEST_HAS_STD_WSTRING
1092template <>
1093class UniversalTersePrinter<const wchar_t*> {
1094 public:
1095 static void Print(const wchar_t* str, ::std::ostream* os) {
1096 if (str == nullptr) {
1097 *os << "NULL";
1098 } else {
1099 UniversalPrint(value: ::std::wstring(str), os);
1100 }
1101 }
1102};
1103#endif
1104
1105template <>
1106class UniversalTersePrinter<wchar_t*> {
1107 public:
1108 static void Print(wchar_t* str, ::std::ostream* os) {
1109 UniversalTersePrinter<const wchar_t*>::Print(str, os);
1110 }
1111};
1112
1113template <typename T>
1114void UniversalTersePrint(const T& value, ::std::ostream* os) {
1115 UniversalTersePrinter<T>::Print(value, os);
1116}
1117
1118// Prints a value using the type inferred by the compiler. The
1119// difference between this and UniversalTersePrint() is that for a
1120// (const) char pointer, this prints both the pointer and the
1121// NUL-terminated string.
1122template <typename T>
1123void UniversalPrint(const T& value, ::std::ostream* os) {
1124 // A workarond for the bug in VC++ 7.1 that prevents us from instantiating
1125 // UniversalPrinter with T directly.
1126 typedef T T1;
1127 UniversalPrinter<T1>::Print(value, os);
1128}
1129
1130typedef ::std::vector<::std::string> Strings;
1131
1132// Tersely prints the first N fields of a tuple to a string vector,
1133// one element for each field.
1134template <typename Tuple>
1135void TersePrintPrefixToStrings(const Tuple&, std::integral_constant<size_t, 0>,
1136 Strings*) {}
1137template <typename Tuple, size_t I>
1138void TersePrintPrefixToStrings(const Tuple& t,
1139 std::integral_constant<size_t, I>,
1140 Strings* strings) {
1141 TersePrintPrefixToStrings(t, std::integral_constant<size_t, I - 1>(),
1142 strings);
1143 ::std::stringstream ss;
1144 UniversalTersePrint(std::get<I - 1>(t), &ss);
1145 strings->push_back(x: ss.str());
1146}
1147
1148// Prints the fields of a tuple tersely to a string vector, one
1149// element for each field. See the comment before
1150// UniversalTersePrint() for how we define "tersely".
1151template <typename Tuple>
1152Strings UniversalTersePrintTupleFieldsToStrings(const Tuple& value) {
1153 Strings result;
1154 TersePrintPrefixToStrings(
1155 value, std::integral_constant<size_t, std::tuple_size<Tuple>::value>(),
1156 &result);
1157 return result;
1158}
1159
1160} // namespace internal
1161
1162template <typename T>
1163::std::string PrintToString(const T& value) {
1164 ::std::stringstream ss;
1165 internal::UniversalTersePrinter<T>::Print(value, &ss);
1166 return ss.str();
1167}
1168
1169} // namespace testing
1170
1171// Include any custom printer added by the local installation.
1172// We must include this header at the end to make sure it can use the
1173// declarations from this file.
1174#include "gtest/internal/custom/gtest-printers.h"
1175
1176#endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
1177

source code of third-party/unittest/googletest/include/gtest/gtest-printers.h