Debian Codegraph @

third-party/unittest/googletest/include/gtest/gtest-printers.h

raw
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
125 namespace testing {
126
127 // Definitions in the internal* namespaces are subject to change without notice.
128 // DO NOT USE THEM IN USER CODE!
129 namespace internal {
130
131 template <typename T>
132 void 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.
136 struct 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.)
173 struct 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
188 struct 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
202 namespace 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.
208 struct LookupBlocker {};
209 void operator<<(LookupBlocker, LookupBlocker);
210
211 struct 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
246 struct 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
264 struct 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
277 struct 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
286 struct 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.
299 GTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes,
300 size_t count, ::std::ostream* os);
301 struct 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 static_cast<const unsigned char*>(
307 // Load bearing cast to void* to support iOS
308 reinterpret_cast<const void*>(std::addressof(value))),
309 sizeof(value), os);
310 }
311 };
312
313 struct 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.
321 template <typename T, typename E, typename Printer, typename... Printers>
322 struct FindFirstPrinter : FindFirstPrinter<T, E, Printers...> {};
323
324 template <typename T, typename Printer, typename... Printers>
325 struct 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.
340 template <typename T>
341 void 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.
369 template <typename ToPrint, typename OtherOperand>
370 class FormatForComparison {
371 public:
372 static ::std::string Format(const ToPrint& value) {
373 return ::testing::PrintToString(value);
374 }
375 };
376
377 // Array.
378 template <typename ToPrint, size_t N, typename OtherOperand>
379 class 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
398 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char);
399 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char);
400 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(wchar_t);
401 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const wchar_t);
402 #ifdef __cpp_lib_char8_t
403 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char8_t);
404 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char8_t);
405 #endif
406 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char16_t);
407 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char16_t);
408 GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char32_t);
409 GTEST_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
425 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::std::string);
426 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char, ::std::string);
427 #ifdef __cpp_lib_char8_t
428 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char8_t, ::std::u8string);
429 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char8_t, ::std::u8string);
430 #endif
431 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char16_t, ::std::u16string);
432 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char16_t, ::std::u16string);
433 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char32_t, ::std::u32string);
434 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char32_t, ::std::u32string);
435
436 #if GTEST_HAS_STD_WSTRING
437 GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(wchar_t, ::std::wstring);
438 GTEST_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.
451 template <typename T1, typename T2>
452 std::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.
464 template <typename T>
465 class 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).
478 template <typename T>
479 void 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.
488 GTEST_API_ void PrintTo(unsigned char c, ::std::ostream* os);
489 GTEST_API_ void PrintTo(signed char c, ::std::ostream* os);
490 inline 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(static_cast<unsigned char>(c), os);
495 }
496
497 // Overloads for other simple built-in types.
498 inline 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.
509 GTEST_API_ void PrintTo(wchar_t wc, ::std::ostream* os);
510
511 GTEST_API_ void PrintTo(char32_t c, ::std::ostream* os);
512 inline void PrintTo(char16_t c, ::std::ostream* os) {
513 // FIXME: the cast from char16_t to char32_t may be incorrect
514 // for a lone surrogate
515 PrintTo(static_cast<char32_t>(c), os);
516 }
517 #ifdef __cpp_lib_char8_t
518 inline void PrintTo(char8_t c, ::std::ostream* os) {
519 // FIXME: the cast from char8_t to char32_t may be incorrect
520 // for c > 0x7F
521 PrintTo(static_cast<char32_t>(c), os);
522 }
523 #endif
524
525 // gcc/clang __{u,}int128_t
526 #if defined(__SIZEOF_INT128__)
527 GTEST_API_ void PrintTo(__uint128_t v, ::std::ostream* os);
528 GTEST_API_ void PrintTo(__int128_t v, ::std::ostream* os);
529 #endif // __SIZEOF_INT128__
530
531 // The default resolution used to print floating-point values uses only
532 // 6 digits, which can be confusing if a test compares two values whose
533 // difference lies in the 7th digit. So we'd like to print out numbers
534 // in full precision.
535 // However if the value is something simple like 1.1, full will print a
536 // long string like 1.100000001 due to floating-point numbers not using
537 // a base of 10. This routiune returns an appropriate resolution for a
538 // given floating-point number, that is, 6 if it will be accurate, or a
539 // max_digits10 value (full precision) if it won't, for values between
540 // 0.0001 and one million.
541 // It does this by computing what those digits would be (by multiplying
542 // by an appropriate power of 10), then dividing by that power again to
543 // see if gets the original value back.
544 // A similar algorithm applies for values larger than one million; note
545 // that for those values, we must divide to get a six-digit number, and
546 // then multiply to possibly get the original value again.
547 template <typename FloatType>
548 int AppropriateResolution(FloatType val) {
549 int full = std::numeric_limits<FloatType>::max_digits10;
550 if (val < 0) val = -val;
551
552 if (val < 1000000) {
553 FloatType mulfor6 = 1e10;
554 if (val >= 100000.0) { // 100,000 to 999,999
555 mulfor6 = 1.0;
556 } else if (val >= 10000.0) {
557 mulfor6 = 1e1;
558 } else if (val >= 1000.0) {
559 mulfor6 = 1e2;
560 } else if (val >= 100.0) {
561 mulfor6 = 1e3;
562 } else if (val >= 10.0) {
563 mulfor6 = 1e4;
564 } else if (val >= 1.0) {
565 mulfor6 = 1e5;
566 } else if (val >= 0.1) {
567 mulfor6 = 1e6;
568 } else if (val >= 0.01) {
569 mulfor6 = 1e7;
570 } else if (val >= 0.001) {
571 mulfor6 = 1e8;
572 } else if (val >= 0.0001) {
573 mulfor6 = 1e9;
574 }
575 if (static_cast<FloatType>(static_cast<int32_t>(val * mulfor6 + 0.5)) /
576 mulfor6 ==
577 val)
578 return 6;
579 } else if (val < 1e10) {
580 FloatType divfor6 = 1.0;
581 if (val >= 1e9) { // 1,000,000,000 to 9,999,999,999
582 divfor6 = 10000;
583 } else if (val >= 1e8) { // 100,000,000 to 999,999,999
584 divfor6 = 1000;
585 } else if (val >= 1e7) { // 10,000,000 to 99,999,999
586 divfor6 = 100;
587 } else if (val >= 1e6) { // 1,000,000 to 9,999,999
588 divfor6 = 10;
589 }
590 if (static_cast<FloatType>(static_cast<int32_t>(val / divfor6 + 0.5)) *
591 divfor6 ==
592 val)
593 return 6;
594 }
595 return full;
596 }
597
598 inline void PrintTo(float f, ::std::ostream* os) {
599 auto old_precision = os->precision();
600 os->precision(AppropriateResolution(f));
601 *os << f;
602 os->precision(old_precision);
603 }
604
605 inline void PrintTo(double d, ::std::ostream* os) {
606 auto old_precision = os->precision();
607 os->precision(AppropriateResolution(d));
608 *os << d;
609 os->precision(old_precision);
610 }
611
612 // Overloads for C strings.
613 GTEST_API_ void PrintTo(const char* s, ::std::ostream* os);
614 inline void PrintTo(char* s, ::std::ostream* os) {
615 PrintTo(ImplicitCast_<const char*>(s), os);
616 }
617
618 // signed/unsigned char is often used for representing binary data, so
619 // we print pointers to it as void* to be safe.
620 inline void PrintTo(const signed char* s, ::std::ostream* os) {
621 PrintTo(ImplicitCast_<const void*>(s), os);
622 }
623 inline void PrintTo(signed char* s, ::std::ostream* os) {
624 PrintTo(ImplicitCast_<const void*>(s), os);
625 }
626 inline void PrintTo(const unsigned char* s, ::std::ostream* os) {
627 PrintTo(ImplicitCast_<const void*>(s), os);
628 }
629 inline void PrintTo(unsigned char* s, ::std::ostream* os) {
630 PrintTo(ImplicitCast_<const void*>(s), os);
631 }
632 #ifdef __cpp_lib_char8_t
633 // Overloads for u8 strings.
634 GTEST_API_ void PrintTo(const char8_t* s, ::std::ostream* os);
635 inline void PrintTo(char8_t* s, ::std::ostream* os) {
636 PrintTo(ImplicitCast_<const char8_t*>(s), os);
637 }
638 #endif
639 // Overloads for u16 strings.
640 GTEST_API_ void PrintTo(const char16_t* s, ::std::ostream* os);
641 inline void PrintTo(char16_t* s, ::std::ostream* os) {
642 PrintTo(ImplicitCast_<const char16_t*>(s), os);
643 }
644 // Overloads for u32 strings.
645 GTEST_API_ void PrintTo(const char32_t* s, ::std::ostream* os);
646 inline void PrintTo(char32_t* s, ::std::ostream* os) {
647 PrintTo(ImplicitCast_<const char32_t*>(s), os);
648 }
649
650 // MSVC can be configured to define wchar_t as a typedef of unsigned
651 // short. It defines _NATIVE_WCHAR_T_DEFINED when wchar_t is a native
652 // type. When wchar_t is a typedef, defining an overload for const
653 // wchar_t* would cause unsigned short* be printed as a wide string,
654 // possibly causing invalid memory accesses.
655 #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
656 // Overloads for wide C strings
657 GTEST_API_ void PrintTo(const wchar_t* s, ::std::ostream* os);
658 inline void PrintTo(wchar_t* s, ::std::ostream* os) {
659 PrintTo(ImplicitCast_<const wchar_t*>(s), os);
660 }
661 #endif
662
663 // Overload for C arrays. Multi-dimensional arrays are printed
664 // properly.
665
666 // Prints the given number of elements in an array, without printing
667 // the curly braces.
668 template <typename T>
669 void PrintRawArrayTo(const T a[], size_t count, ::std::ostream* os) {
670 UniversalPrint(a[0], os);
671 for (size_t i = 1; i != count; i++) {
672 *os << ", ";
673 UniversalPrint(a[i], os);
674 }
675 }
676
677 // Overloads for ::std::string.
678 GTEST_API_ void PrintStringTo(const ::std::string& s, ::std::ostream* os);
679 inline void PrintTo(const ::std::string& s, ::std::ostream* os) {
680 PrintStringTo(s, os);
681 }
682
683 // Overloads for ::std::u8string
684 #ifdef __cpp_lib_char8_t
685 GTEST_API_ void PrintU8StringTo(const ::std::u8string& s, ::std::ostream* os);
686 inline void PrintTo(const ::std::u8string& s, ::std::ostream* os) {
687 PrintU8StringTo(s, os);
688 }
689 #endif
690
691 // Overloads for ::std::u16string
692 GTEST_API_ void PrintU16StringTo(const ::std::u16string& s, ::std::ostream* os);
693 inline void PrintTo(const ::std::u16string& s, ::std::ostream* os) {
694 PrintU16StringTo(s, os);
695 }
696
697 // Overloads for ::std::u32string
698 GTEST_API_ void PrintU32StringTo(const ::std::u32string& s, ::std::ostream* os);
699 inline void PrintTo(const ::std::u32string& s, ::std::ostream* os) {
700 PrintU32StringTo(s, os);
701 }
702
703 // Overloads for ::std::wstring.
704 #if GTEST_HAS_STD_WSTRING
705 GTEST_API_ void PrintWideStringTo(const ::std::wstring& s, ::std::ostream* os);
706 inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) {
707 PrintWideStringTo(s, os);
708 }
709 #endif // GTEST_HAS_STD_WSTRING
710
711 #if GTEST_INTERNAL_HAS_STRING_VIEW
712 // Overload for internal::StringView.
713 inline void PrintTo(internal::StringView sp, ::std::ostream* os) {
714 PrintTo(::std::string(sp), os);
715 }
716 #endif // GTEST_INTERNAL_HAS_STRING_VIEW
717
718 inline void PrintTo(std::nullptr_t, ::std::ostream* os) { *os << "(nullptr)"; }
719
720 #if GTEST_HAS_RTTI
721 inline void PrintTo(const std::type_info& info, std::ostream* os) {
722 *os << internal::GetTypeName(info);
723 }
724 #endif // GTEST_HAS_RTTI
725
726 template <typename T>
727 void PrintTo(std::reference_wrapper<T> ref, ::std::ostream* os) {
728 UniversalPrinter<T&>::Print(ref.get(), os);
729 }
730
731 inline const void* VoidifyPointer(const void* p) { return p; }
732 inline const void* VoidifyPointer(volatile const void* p) {
733 return const_cast<const void*>(p);
734 }
735
736 template <typename T, typename Ptr>
737 void PrintSmartPointer(const Ptr& ptr, std::ostream* os, char) {
738 if (ptr == nullptr) {
739 *os << "(nullptr)";
740 } else {
741 // We can't print the value. Just print the pointer..
742 *os << "(" << (VoidifyPointer)(ptr.get()) << ")";
743 }
744 }
745 template <typename T, typename Ptr,
746 typename = typename std::enable_if<!std::is_void<T>::value &&
747 !std::is_array<T>::value>::type>
748 void PrintSmartPointer(const Ptr& ptr, std::ostream* os, int) {
749 if (ptr == nullptr) {
750 *os << "(nullptr)";
751 } else {
752 *os << "(ptr = " << (VoidifyPointer)(ptr.get()) << ", value = ";
753 UniversalPrinter<T>::Print(*ptr, os);
754 *os << ")";
755 }
756 }
757
758 template <typename T, typename D>
759 void PrintTo(const std::unique_ptr<T, D>& ptr, std::ostream* os) {
760 (PrintSmartPointer<T>)(ptr, os, 0);
761 }
762
763 template <typename T>
764 void PrintTo(const std::shared_ptr<T>& ptr, std::ostream* os) {
765 (PrintSmartPointer<T>)(ptr, os, 0);
766 }
767
768 // Helper function for printing a tuple. T must be instantiated with
769 // a tuple type.
770 template <typename T>
771 void PrintTupleTo(const T&, std::integral_constant<size_t, 0>,
772 ::std::ostream*) {}
773
774 template <typename T, size_t I>
775 void PrintTupleTo(const T& t, std::integral_constant<size_t, I>,
776 ::std::ostream* os) {
777 PrintTupleTo(t, std::integral_constant<size_t, I - 1>(), os);
778 GTEST_INTENTIONAL_CONST_COND_PUSH_()
779 if (I > 1) {
780 GTEST_INTENTIONAL_CONST_COND_POP_()
781 *os << ", ";
782 }
783 UniversalPrinter<typename std::tuple_element<I - 1, T>::type>::Print(
784 std::get<I - 1>(t), os);
785 }
786
787 template <typename... Types>
788 void PrintTo(const ::std::tuple<Types...>& t, ::std::ostream* os) {
789 *os << "(";
790 PrintTupleTo(t, std::integral_constant<size_t, sizeof...(Types)>(), os);
791 *os << ")";
792 }
793
794 // Overload for std::pair.
795 template <typename T1, typename T2>
796 void PrintTo(const ::std::pair<T1, T2>& value, ::std::ostream* os) {
797 *os << '(';
798 // We cannot use UniversalPrint(value.first, os) here, as T1 may be
799 // a reference type. The same for printing value.second.
800 UniversalPrinter<T1>::Print(value.first, os);
801 *os << ", ";
802 UniversalPrinter<T2>::Print(value.second, os);
803 *os << ')';
804 }
805
806 // Implements printing a non-reference type T by letting the compiler
807 // pick the right overload of PrintTo() for T.
808 template <typename T>
809 class UniversalPrinter {
810 public:
811 // MSVC warns about adding const to a function type, so we want to
812 // disable the warning.
813 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180)
814
815 // Note: we deliberately don't call this PrintTo(), as that name
816 // conflicts with ::testing::internal::PrintTo in the body of the
817 // function.
818 static void Print(const T& value, ::std::ostream* os) {
819 // By default, ::testing::internal::PrintTo() is used for printing
820 // the value.
821 //
822 // Thanks to Koenig look-up, if T is a class and has its own
823 // PrintTo() function defined in its namespace, that function will
824 // be visible here. Since it is more specific than the generic ones
825 // in ::testing::internal, it will be picked by the compiler in the
826 // following statement - exactly what we want.
827 PrintTo(value, os);
828 }
829
830 GTEST_DISABLE_MSC_WARNINGS_POP_()
831 };
832
833 // Remove any const-qualifiers before passing a type to UniversalPrinter.
834 template <typename T>
835 class UniversalPrinter<const T> : public UniversalPrinter<T> {};
836
837 #if GTEST_INTERNAL_HAS_ANY
838
839 // Printer for std::any / absl::any
840
841 template <>
842 class UniversalPrinter<Any> {
843 public:
844 static void Print(const Any& value, ::std::ostream* os) {
845 if (value.has_value()) {
846 *os << "value of type " << GetTypeName(value);
847 } else {
848 *os << "no value";
849 }
850 }
851
852 private:
853 static std::string GetTypeName(const Any& value) {
854 #if GTEST_HAS_RTTI
855 return internal::GetTypeName(value.type());
856 #else
857 static_cast<void>(value); // possibly unused
858 return "<unknown_type>";
859 #endif // GTEST_HAS_RTTI
860 }
861 };
862
863 #endif // GTEST_INTERNAL_HAS_ANY
864
865 #if GTEST_INTERNAL_HAS_OPTIONAL
866
867 // Printer for std::optional / absl::optional
868
869 template <typename T>
870 class UniversalPrinter<Optional<T>> {
871 public:
872 static void Print(const Optional<T>& value, ::std::ostream* os) {
873 *os << '(';
874 if (!value) {
875 *os << "nullopt";
876 } else {
877 UniversalPrint(*value, os);
878 }
879 *os << ')';
880 }
881 };
882
883 template <>
884 class UniversalPrinter<decltype(Nullopt())> {
885 public:
886 static void Print(decltype(Nullopt()), ::std::ostream* os) {
887 *os << "(nullopt)";
888 }
889 };
890
891 #endif // GTEST_INTERNAL_HAS_OPTIONAL
892
893 #if GTEST_INTERNAL_HAS_VARIANT
894
895 // Printer for std::variant / absl::variant
896
897 template <typename... T>
898 class UniversalPrinter<Variant<T...>> {
899 public:
900 static void Print(const Variant<T...>& value, ::std::ostream* os) {
901 *os << '(';
902 #ifdef GTEST_HAS_ABSL
903 absl::visit(Visitor{os, value.index()}, value);
904 #else
905 std::visit(Visitor{os, value.index()}, value);
906 #endif // GTEST_HAS_ABSL
907 *os << ')';
908 }
909
910 private:
911 struct Visitor {
912 template <typename U>
913 void operator()(const U& u) const {
914 *os << "'" << GetTypeName<U>() << "(index = " << index
915 << ")' with value ";
916 UniversalPrint(u, os);
917 }
918 ::std::ostream* os;
919 std::size_t index;
920 };
921 };
922
923 #endif // GTEST_INTERNAL_HAS_VARIANT
924
925 // UniversalPrintArray(begin, len, os) prints an array of 'len'
926 // elements, starting at address 'begin'.
927 template <typename T>
928 void UniversalPrintArray(const T* begin, size_t len, ::std::ostream* os) {
929 if (len == 0) {
930 *os << "{}";
931 } else {
932 *os << "{ ";
933 const size_t kThreshold = 18;
934 const size_t kChunkSize = 8;
935 // If the array has more than kThreshold elements, we'll have to
936 // omit some details by printing only the first and the last
937 // kChunkSize elements.
938 if (len <= kThreshold) {
939 PrintRawArrayTo(begin, len, os);
940 } else {
941 PrintRawArrayTo(begin, kChunkSize, os);
942 *os << ", ..., ";
943 PrintRawArrayTo(begin + len - kChunkSize, kChunkSize, os);
944 }
945 *os << " }";
946 }
947 }
948 // This overload prints a (const) char array compactly.
949 GTEST_API_ void UniversalPrintArray(const char* begin, size_t len,
950 ::std::ostream* os);
951
952 #ifdef __cpp_lib_char8_t
953 // This overload prints a (const) char8_t array compactly.
954 GTEST_API_ void UniversalPrintArray(const char8_t* begin, size_t len,
955 ::std::ostream* os);
956 #endif
957
958 // This overload prints a (const) char16_t array compactly.
959 GTEST_API_ void UniversalPrintArray(const char16_t* begin, size_t len,
960 ::std::ostream* os);
961
962 // This overload prints a (const) char32_t array compactly.
963 GTEST_API_ void UniversalPrintArray(const char32_t* begin, size_t len,
964 ::std::ostream* os);
965
966 // This overload prints a (const) wchar_t array compactly.
967 GTEST_API_ void UniversalPrintArray(const wchar_t* begin, size_t len,
968 ::std::ostream* os);
969
970 // Implements printing an array type T[N].
971 template <typename T, size_t N>
972 class UniversalPrinter<T[N]> {
973 public:
974 // Prints the given array, omitting some elements when there are too
975 // many.
976 static void Print(const T (&a)[N], ::std::ostream* os) {
977 UniversalPrintArray(a, N, os);
978 }
979 };
980
981 // Implements printing a reference type T&.
982 template <typename T>
983 class UniversalPrinter<T&> {
984 public:
985 // MSVC warns about adding const to a function type, so we want to
986 // disable the warning.
987 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180)
988
989 static void Print(const T& value, ::std::ostream* os) {
990 // Prints the address of the value. We use reinterpret_cast here
991 // as static_cast doesn't compile when T is a function type.
992 *os << "@" << reinterpret_cast<const void*>(&value) << " ";
993
994 // Then prints the value itself.
995 UniversalPrint(value, os);
996 }
997
998 GTEST_DISABLE_MSC_WARNINGS_POP_()
999 };
1000
1001 // Prints a value tersely: for a reference type, the referenced value
1002 // (but not the address) is printed; for a (const) char pointer, the
1003 // NUL-terminated string (but not the pointer) is printed.
1004
1005 template <typename T>
1006 class UniversalTersePrinter {
1007 public:
1008 static void Print(const T& value, ::std::ostream* os) {
1009 UniversalPrint(value, os);
1010 }
1011 };
1012 template <typename T>
1013 class UniversalTersePrinter<T&> {
1014 public:
1015 static void Print(const T& value, ::std::ostream* os) {
1016 UniversalPrint(value, os);
1017 }
1018 };
1019 template <typename T>
1020 class UniversalTersePrinter<std::reference_wrapper<T>> {
1021 public:
1022 static void Print(std::reference_wrapper<T> value, ::std::ostream* os) {
1023 UniversalTersePrinter<T>::Print(value.get(), os);
1024 }
1025 };
1026 template <typename T, size_t N>
1027 class UniversalTersePrinter<T[N]> {
1028 public:
1029 static void Print(const T (&value)[N], ::std::ostream* os) {
1030 UniversalPrinter<T[N]>::Print(value, os);
1031 }
1032 };
1033 template <>
1034 class UniversalTersePrinter<const char*> {
1035 public:
1036 static void Print(const char* str, ::std::ostream* os) {
1037 if (str == nullptr) {
1038 *os << "NULL";
1039 } else {
1040 UniversalPrint(std::string(str), os);
1041 }
1042 }
1043 };
1044 template <>
1045 class UniversalTersePrinter<char*> : public UniversalTersePrinter<const char*> {
1046 };
1047
1048 #ifdef __cpp_lib_char8_t
1049 template <>
1050 class UniversalTersePrinter<const char8_t*> {
1051 public:
1052 static void Print(const char8_t* str, ::std::ostream* os) {
1053 if (str == nullptr) {
1054 *os << "NULL";
1055 } else {
1056 UniversalPrint(::std::u8string(str), os);
1057 }
1058 }
1059 };
1060 template <>
1061 class UniversalTersePrinter<char8_t*>
1062 : public UniversalTersePrinter<const char8_t*> {};
1063 #endif
1064
1065 template <>
1066 class UniversalTersePrinter<const char16_t*> {
1067 public:
1068 static void Print(const char16_t* str, ::std::ostream* os) {
1069 if (str == nullptr) {
1070 *os << "NULL";
1071 } else {
1072 UniversalPrint(::std::u16string(str), os);
1073 }
1074 }
1075 };
1076 template <>
1077 class UniversalTersePrinter<char16_t*>
1078 : public UniversalTersePrinter<const char16_t*> {};
1079
1080 template <>
1081 class UniversalTersePrinter<const char32_t*> {
1082 public:
1083 static void Print(const char32_t* str, ::std::ostream* os) {
1084 if (str == nullptr) {
1085 *os << "NULL";
1086 } else {
1087 UniversalPrint(::std::u32string(str), os);
1088 }
1089 }
1090 };
1091 template <>
1092 class UniversalTersePrinter<char32_t*>
1093 : public UniversalTersePrinter<const char32_t*> {};
1094
1095 #if GTEST_HAS_STD_WSTRING
1096 template <>
1097 class UniversalTersePrinter<const wchar_t*> {
1098 public:
1099 static void Print(const wchar_t* str, ::std::ostream* os) {
1100 if (str == nullptr) {
1101 *os << "NULL";
1102 } else {
1103 UniversalPrint(::std::wstring(str), os);
1104 }
1105 }
1106 };
1107 #endif
1108
1109 template <>
1110 class UniversalTersePrinter<wchar_t*> {
1111 public:
1112 static void Print(wchar_t* str, ::std::ostream* os) {
1113 UniversalTersePrinter<const wchar_t*>::Print(str, os);
1114 }
1115 };
1116
1117 template <typename T>
1118 void UniversalTersePrint(const T& value, ::std::ostream* os) {
1119 UniversalTersePrinter<T>::Print(value, os);
1120 }
1121
1122 // Prints a value using the type inferred by the compiler. The
1123 // difference between this and UniversalTersePrint() is that for a
1124 // (const) char pointer, this prints both the pointer and the
1125 // NUL-terminated string.
1126 template <typename T>
1127 void UniversalPrint(const T& value, ::std::ostream* os) {
1128 // A workarond for the bug in VC++ 7.1 that prevents us from instantiating
1129 // UniversalPrinter with T directly.
1130 typedef T T1;
1131 UniversalPrinter<T1>::Print(value, os);
1132 }
1133
1134 typedef ::std::vector<::std::string> Strings;
1135
1136 // Tersely prints the first N fields of a tuple to a string vector,
1137 // one element for each field.
1138 template <typename Tuple>
1139 void TersePrintPrefixToStrings(const Tuple&, std::integral_constant<size_t, 0>,
1140 Strings*) {}
1141 template <typename Tuple, size_t I>
1142 void TersePrintPrefixToStrings(const Tuple& t,
1143 std::integral_constant<size_t, I>,
1144 Strings* strings) {
1145 TersePrintPrefixToStrings(t, std::integral_constant<size_t, I - 1>(),
1146 strings);
1147 ::std::stringstream ss;
1148 UniversalTersePrint(std::get<I - 1>(t), &ss);
1149 strings->push_back(ss.str());
1150 }
1151
1152 // Prints the fields of a tuple tersely to a string vector, one
1153 // element for each field. See the comment before
1154 // UniversalTersePrint() for how we define "tersely".
1155 template <typename Tuple>
1156 Strings UniversalTersePrintTupleFieldsToStrings(const Tuple& value) {
1157 Strings result;
1158 TersePrintPrefixToStrings(
1159 value, std::integral_constant<size_t, std::tuple_size<Tuple>::value>(),
1160 &result);
1161 return result;
1162 }
1163
1164 } // namespace internal
1165
1166 template <typename T>
1167 ::std::string PrintToString(const T& value) {
1168 ::std::stringstream ss;
1169 internal::UniversalTersePrinter<T>::Print(value, &ss);
1170 return ss.str();
1171 }
1172
1173 } // namespace testing
1174
1175 // Include any custom printer added by the local installation.
1176 // We must include this header at the end to make sure it can use the
1177 // declarations from this file.
1178 #include "gtest/internal/custom/gtest-printers.h"
1179
1180 #endif // GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_