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