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 tests the universal value printer.
33
34#include <algorithm>
35#include <cctype>
36#include <cstdint>
37#include <cstring>
38#include <deque>
39#include <forward_list>
40#include <functional>
41#include <limits>
42#include <list>
43#include <map>
44#include <memory>
45#include <ostream>
46#include <set>
47#include <sstream>
48#include <string>
49#include <tuple>
50#include <unordered_map>
51#include <unordered_set>
52#include <utility>
53#include <vector>
54
55#include "gtest/gtest-printers.h"
56#include "gtest/gtest.h"
57
58#ifdef GTEST_HAS_ABSL
59#include "absl/strings/str_format.h"
60#endif
61
62// Some user-defined types for testing the universal value printer.
63
64// An anonymous enum type.
65enum AnonymousEnum { kAE1 = -1, kAE2 = 1 };
66
67// An enum without a user-defined printer.
68enum EnumWithoutPrinter { kEWP1 = -2, kEWP2 = 42 };
69
70// An enum with a << operator.
71enum EnumWithStreaming { kEWS1 = 10 };
72
73std::ostream& operator<<(std::ostream& os, EnumWithStreaming e) {
74  return os << (e == kEWS1 ? "kEWS1" : "invalid");
75}
76
77// An enum with a PrintTo() function.
78enum EnumWithPrintTo { kEWPT1 = 1 };
79
80void PrintTo(EnumWithPrintTo e, std::ostream* os) {
81  *os << (e == kEWPT1 ? "kEWPT1" : "invalid");
82}
83
84// A class implicitly convertible to BiggestInt.
85class BiggestIntConvertible {
86 public:
87  operator ::testing::internal::BiggestInt() const { return 42; }
88};
89
90// A parent class with two child classes. The parent and one of the kids have
91// stream operators.
92class ParentClass {};
93class ChildClassWithStreamOperator : public ParentClass {};
94class ChildClassWithoutStreamOperator : public ParentClass {};
95static void operator<<(std::ostream& os, const ParentClass&) {
96  os << "ParentClass";
97}
98static void operator<<(std::ostream& os, const ChildClassWithStreamOperator&) {
99  os << "ChildClassWithStreamOperator";
100}
101
102// A user-defined unprintable class template in the global namespace.
103template <typename T>
104class UnprintableTemplateInGlobal {
105 public:
106  UnprintableTemplateInGlobal() : value_() {}
107
108 private:
109  T value_;
110};
111
112// A user-defined streamable type in the global namespace.
113class StreamableInGlobal {
114 public:
115  virtual ~StreamableInGlobal() = default;
116};
117
118inline void operator<<(::std::ostream& os, const StreamableInGlobal& /* x */) {
119  os << "StreamableInGlobal";
120}
121
122void operator<<(::std::ostream& os, const StreamableInGlobal* /* x */) {
123  os << "StreamableInGlobal*";
124}
125
126#ifdef GTEST_HAS_ABSL
127// A user-defined type with AbslStringify
128struct Point {
129  template <typename Sink>
130  friend void AbslStringify(Sink& sink, const Point& p) {
131    absl::Format(&sink, "(%d, %d)", p.x, p.y);
132  }
133
134  int x = 10;
135  int y = 20;
136};
137#endif
138
139namespace foo {
140
141// A user-defined unprintable type in a user namespace.
142class UnprintableInFoo {
143 public:
144  UnprintableInFoo() : z_(0) { memcpy(xy_, "\xEF\x12\x0\x0\x34\xAB\x0\x0", 8); }
145  double z() const { return z_; }
146
147 private:
148  char xy_[8];
149  double z_;
150};
151
152// A user-defined printable type in a user-chosen namespace.
153struct PrintableViaPrintTo {
154  PrintableViaPrintTo() : value() {}
155  int value;
156};
157
158void PrintTo(const PrintableViaPrintTo& x, ::std::ostream* os) {
159  *os << "PrintableViaPrintTo: " << x.value;
160}
161
162// A type with a user-defined << for printing its pointer.
163struct PointerPrintable {};
164
165::std::ostream& operator<<(::std::ostream& os,
166                           const PointerPrintable* /* x */) {
167  return os << "PointerPrintable*";
168}
169
170// A user-defined printable class template in a user-chosen namespace.
171template <typename T>
172class PrintableViaPrintToTemplate {
173 public:
174  explicit PrintableViaPrintToTemplate(const T& a_value) : value_(a_value) {}
175
176  const T& value() const { return value_; }
177
178 private:
179  T value_;
180};
181
182template <typename T>
183void PrintTo(const PrintableViaPrintToTemplate<T>& x, ::std::ostream* os) {
184  *os << "PrintableViaPrintToTemplate: " << x.value();
185}
186
187// A user-defined streamable class template in a user namespace.
188template <typename T>
189class StreamableTemplateInFoo {
190 public:
191  StreamableTemplateInFoo() : value_() {}
192
193  const T& value() const { return value_; }
194
195 private:
196  T value_;
197};
198
199template <typename T>
200inline ::std::ostream& operator<<(::std::ostream& os,
201                                  const StreamableTemplateInFoo<T>& x) {
202  return os << "StreamableTemplateInFoo: " << x.value();
203}
204
205// A user-defined streamable type in a user namespace whose operator<< is
206// templated on the type of the output stream.
207struct TemplatedStreamableInFoo {};
208
209template <typename OutputStream>
210OutputStream& operator<<(OutputStream& os,
211                         const TemplatedStreamableInFoo& /*ts*/) {
212  os << "TemplatedStreamableInFoo";
213  return os;
214}
215
216struct StreamableInLocal {};
217void operator<<(::std::ostream& os, const StreamableInLocal& /* x */) {
218  os << "StreamableInLocal";
219}
220
221// A user-defined streamable but recursively-defined container type in
222// a user namespace, it mimics therefore std::filesystem::path or
223// boost::filesystem::path.
224class PathLike {
225 public:
226  struct iterator {
227    typedef PathLike value_type;
228
229    iterator& operator++();
230    PathLike& operator*();
231  };
232
233  using value_type = char;
234  using const_iterator = iterator;
235
236  PathLike() = default;
237
238  iterator begin() const { return iterator(); }
239  iterator end() const { return iterator(); }
240
241  friend ::std::ostream& operator<<(::std::ostream& os, const PathLike&) {
242    return os << "Streamable-PathLike";
243  }
244};
245
246}  // namespace foo
247
248namespace testing {
249namespace {
250template <typename T>
251class Wrapper {
252 public:
253  explicit Wrapper(T&& value) : value_(std::forward<T>(value)) {}
254
255  const T& value() const { return value_; }
256
257 private:
258  T value_;
259};
260
261}  // namespace
262
263namespace internal {
264template <typename T>
265class UniversalPrinter<Wrapper<T>> {
266 public:
267  static void Print(const Wrapper<T>& w, ::std::ostream* os) {
268    *os << "Wrapper(";
269    UniversalPrint(w.value(), os);
270    *os << ')';
271  }
272};
273}  // namespace internal
274
275namespace gtest_printers_test {
276
277using ::std::deque;
278using ::std::list;
279using ::std::make_pair;
280using ::std::map;
281using ::std::multimap;
282using ::std::multiset;
283using ::std::pair;
284using ::std::set;
285using ::std::vector;
286using ::testing::PrintToString;
287using ::testing::internal::FormatForComparisonFailureMessage;
288using ::testing::internal::NativeArray;
289using ::testing::internal::RelationToSourceReference;
290using ::testing::internal::Strings;
291using ::testing::internal::UniversalPrint;
292using ::testing::internal::UniversalPrinter;
293using ::testing::internal::UniversalTersePrint;
294using ::testing::internal::UniversalTersePrintTupleFieldsToStrings;
295
296// Prints a value to a string using the universal value printer.  This
297// is a helper for testing UniversalPrinter<T>::Print() for various types.
298template <typename T>
299std::string Print(const T& value) {
300  ::std::stringstream ss;
301  UniversalPrinter<T>::Print(value, &ss);
302  return ss.str();
303}
304
305// Prints a value passed by reference to a string, using the universal
306// value printer.  This is a helper for testing
307// UniversalPrinter<T&>::Print() for various types.
308template <typename T>
309std::string PrintByRef(const T& value) {
310  ::std::stringstream ss;
311  UniversalPrinter<T&>::Print(value, &ss);
312  return ss.str();
313}
314
315// Tests printing various enum types.
316
317TEST(PrintEnumTest, AnonymousEnum) {
318  EXPECT_EQ("-1", Print(kAE1));
319  EXPECT_EQ("1", Print(kAE2));
320}
321
322TEST(PrintEnumTest, EnumWithoutPrinter) {
323  EXPECT_EQ("-2", Print(kEWP1));
324  EXPECT_EQ("42", Print(kEWP2));
325}
326
327TEST(PrintEnumTest, EnumWithStreaming) {
328  EXPECT_EQ("kEWS1", Print(kEWS1));
329  EXPECT_EQ("invalid", Print(static_cast<EnumWithStreaming>(0)));
330}
331
332TEST(PrintEnumTest, EnumWithPrintTo) {
333  EXPECT_EQ("kEWPT1", Print(kEWPT1));
334  EXPECT_EQ("invalid", Print(static_cast<EnumWithPrintTo>(0)));
335}
336
337#ifdef GTEST_HAS_ABSL
338// Tests printing a class that defines AbslStringify
339TEST(PrintClassTest, AbslStringify) { EXPECT_EQ("(10, 20)", Print(Point())); }
340#endif
341
342// Tests printing a class implicitly convertible to BiggestInt.
343
344TEST(PrintClassTest, BiggestIntConvertible) {
345  EXPECT_EQ("42", Print(BiggestIntConvertible()));
346}
347
348// Tests printing various char types.
349
350// char.
351TEST(PrintCharTest, PlainChar) {
352  EXPECT_EQ("'\\0'", Print('\0'));
353  EXPECT_EQ("'\\'' (39, 0x27)", Print('\''));
354  EXPECT_EQ("'\"' (34, 0x22)", Print('"'));
355  EXPECT_EQ("'?' (63, 0x3F)", Print('?'));
356  EXPECT_EQ("'\\\\' (92, 0x5C)", Print('\\'));
357  EXPECT_EQ("'\\a' (7)", Print('\a'));
358  EXPECT_EQ("'\\b' (8)", Print('\b'));
359  EXPECT_EQ("'\\f' (12, 0xC)", Print('\f'));
360  EXPECT_EQ("'\\n' (10, 0xA)", Print('\n'));
361  EXPECT_EQ("'\\r' (13, 0xD)", Print('\r'));
362  EXPECT_EQ("'\\t' (9)", Print('\t'));
363  EXPECT_EQ("'\\v' (11, 0xB)", Print('\v'));
364  EXPECT_EQ("'\\x7F' (127)", Print('\x7F'));
365  EXPECT_EQ("'\\xFF' (255)", Print('\xFF'));
366  EXPECT_EQ("' ' (32, 0x20)", Print(' '));
367  EXPECT_EQ("'a' (97, 0x61)", Print('a'));
368}
369
370// signed char.
371TEST(PrintCharTest, SignedChar) {
372  EXPECT_EQ("'\\0'", Print(static_cast<signed char>('\0')));
373  EXPECT_EQ("'\\xCE' (-50)", Print(static_cast<signed char>(-50)));
374}
375
376// unsigned char.
377TEST(PrintCharTest, UnsignedChar) {
378  EXPECT_EQ("'\\0'", Print(static_cast<unsigned char>('\0')));
379  EXPECT_EQ("'b' (98, 0x62)", Print(static_cast<unsigned char>('b')));
380}
381
382TEST(PrintCharTest, Char16) { EXPECT_EQ("U+0041", Print(u'A')); }
383
384TEST(PrintCharTest, Char32) { EXPECT_EQ("U+0041", Print(U'A')); }
385
386#ifdef __cpp_lib_char8_t
387TEST(PrintCharTest, Char8) { EXPECT_EQ("U+0041", Print(u8'A')); }
388#endif
389
390// Tests printing other simple, built-in types.
391
392// bool.
393TEST(PrintBuiltInTypeTest, Bool) {
394  EXPECT_EQ("false", Print(false));
395  EXPECT_EQ("true", Print(true));
396}
397
398// wchar_t.
399TEST(PrintBuiltInTypeTest, Wchar_t) {
400  EXPECT_EQ("L'\\0'", Print(L'\0'));
401  EXPECT_EQ("L'\\'' (39, 0x27)", Print(L'\''));
402  EXPECT_EQ("L'\"' (34, 0x22)", Print(L'"'));
403  EXPECT_EQ("L'?' (63, 0x3F)", Print(L'?'));
404  EXPECT_EQ("L'\\\\' (92, 0x5C)", Print(L'\\'));
405  EXPECT_EQ("L'\\a' (7)", Print(L'\a'));
406  EXPECT_EQ("L'\\b' (8)", Print(L'\b'));
407  EXPECT_EQ("L'\\f' (12, 0xC)", Print(L'\f'));
408  EXPECT_EQ("L'\\n' (10, 0xA)", Print(L'\n'));
409  EXPECT_EQ("L'\\r' (13, 0xD)", Print(L'\r'));
410  EXPECT_EQ("L'\\t' (9)", Print(L'\t'));
411  EXPECT_EQ("L'\\v' (11, 0xB)", Print(L'\v'));
412  EXPECT_EQ("L'\\x7F' (127)", Print(L'\x7F'));
413  EXPECT_EQ("L'\\xFF' (255)", Print(L'\xFF'));
414  EXPECT_EQ("L' ' (32, 0x20)", Print(L' '));
415  EXPECT_EQ("L'a' (97, 0x61)", Print(L'a'));
416  EXPECT_EQ("L'\\x576' (1398)", Print(static_cast<wchar_t>(0x576)));
417  EXPECT_EQ("L'\\xC74D' (51021)", Print(static_cast<wchar_t>(0xC74D)));
418}
419
420// Test that int64_t provides more storage than wchar_t.
421TEST(PrintTypeSizeTest, Wchar_t) {
422  EXPECT_LT(sizeof(wchar_t), sizeof(int64_t));
423}
424
425// Various integer types.
426TEST(PrintBuiltInTypeTest, Integer) {
427  EXPECT_EQ("'\\xFF' (255)", Print(static_cast<unsigned char>(255)));  // uint8
428  EXPECT_EQ("'\\x80' (-128)", Print(static_cast<signed char>(-128)));  // int8
429  EXPECT_EQ("65535", Print(std::numeric_limits<uint16_t>::max()));     // uint16
430  EXPECT_EQ("-32768", Print(std::numeric_limits<int16_t>::min()));     // int16
431  EXPECT_EQ("4294967295",
432            Print(std::numeric_limits<uint32_t>::max()));  // uint32
433  EXPECT_EQ("-2147483648",
434            Print(std::numeric_limits<int32_t>::min()));  // int32
435  EXPECT_EQ("18446744073709551615",
436            Print(std::numeric_limits<uint64_t>::max()));  // uint64
437  EXPECT_EQ("-9223372036854775808",
438            Print(std::numeric_limits<int64_t>::min()));  // int64
439#ifdef __cpp_lib_char8_t
440  EXPECT_EQ("U+0000",
441            Print(std::numeric_limits<char8_t>::min()));  // char8_t
442  EXPECT_EQ("U+00FF",
443            Print(std::numeric_limits<char8_t>::max()));  // char8_t
444#endif
445  EXPECT_EQ("U+0000",
446            Print(std::numeric_limits<char16_t>::min()));  // char16_t
447  EXPECT_EQ("U+FFFF",
448            Print(std::numeric_limits<char16_t>::max()));  // char16_t
449  EXPECT_EQ("U+0000",
450            Print(std::numeric_limits<char32_t>::min()));  // char32_t
451  EXPECT_EQ("U+FFFFFFFF",
452            Print(std::numeric_limits<char32_t>::max()));  // char32_t
453}
454
455// Size types.
456TEST(PrintBuiltInTypeTest, Size_t) {
457  EXPECT_EQ("1", Print(sizeof('a')));  // size_t.
458#ifndef GTEST_OS_WINDOWS
459  // Windows has no ssize_t type.
460  EXPECT_EQ("-2", Print(static_cast<ssize_t>(-2)));  // ssize_t.
461#endif                                               // !GTEST_OS_WINDOWS
462}
463
464// gcc/clang __{u,}int128_t values.
465#if defined(__SIZEOF_INT128__)
466TEST(PrintBuiltInTypeTest, Int128) {
467  // Small ones
468  EXPECT_EQ("0", Print(__int128_t{0}));
469  EXPECT_EQ("0", Print(__uint128_t{0}));
470  EXPECT_EQ("12345", Print(__int128_t{12345}));
471  EXPECT_EQ("12345", Print(__uint128_t{12345}));
472  EXPECT_EQ("-12345", Print(__int128_t{-12345}));
473
474  // Large ones
475  EXPECT_EQ("340282366920938463463374607431768211455", Print(~__uint128_t{}));
476  __int128_t max_128 = static_cast<__int128_t>(~__uint128_t{} / 2);
477  EXPECT_EQ("-170141183460469231731687303715884105728", Print(~max_128));
478  EXPECT_EQ("170141183460469231731687303715884105727", Print(max_128));
479}
480#endif  // __SIZEOF_INT128__
481
482// Floating-points.
483TEST(PrintBuiltInTypeTest, FloatingPoints) {
484  // float (32-bit precision)
485  EXPECT_EQ("1.5", Print(1.5f));
486
487  EXPECT_EQ("1.0999999", Print(1.09999990f));
488  EXPECT_EQ("1.1", Print(1.10000002f));
489  EXPECT_EQ("1.10000014", Print(1.10000014f));
490  EXPECT_EQ("9e+09", Print(9e9f));
491
492  // double
493  EXPECT_EQ("-2.5", Print(-2.5));  // double
494}
495
496#if GTEST_HAS_RTTI
497TEST(PrintBuiltInTypeTest, TypeInfo) {
498  struct MyStruct {};
499  auto res = Print(typeid(MyStruct{}));
500  // We can't guarantee that we can demangle the name, but either name should
501  // contain the substring "MyStruct".
502  EXPECT_NE(res.find("MyStruct"), res.npos) << res;
503}
504#endif  // GTEST_HAS_RTTI
505
506// Since ::std::stringstream::operator<<(const void *) formats the pointer
507// output differently with different compilers, we have to create the expected
508// output first and use it as our expectation.
509static std::string PrintPointer(const void* p) {
510  ::std::stringstream expected_result_stream;
511  expected_result_stream << p;
512  return expected_result_stream.str();
513}
514
515// Tests printing C strings.
516
517// const char*.
518TEST(PrintCStringTest, Const) {
519  const char* p = "World";
520  EXPECT_EQ(PrintPointer(p) + " pointing to \"World\"", Print(p));
521}
522
523// char*.
524TEST(PrintCStringTest, NonConst) {
525  char p[] = "Hi";
526  EXPECT_EQ(PrintPointer(p) + " pointing to \"Hi\"",
527            Print(static_cast<char*>(p)));
528}
529
530// NULL C string.
531TEST(PrintCStringTest, Null) {
532  const char* p = nullptr;
533  EXPECT_EQ("NULL", Print(p));
534}
535
536// Tests that C strings are escaped properly.
537TEST(PrintCStringTest, EscapesProperly) {
538  const char* p = "'\"?\\\a\b\f\n\r\t\v\x7F\xFF a";
539  EXPECT_EQ(PrintPointer(p) +
540                " pointing to \"'\\\"?\\\\\\a\\b\\f"
541                "\\n\\r\\t\\v\\x7F\\xFF a\"",
542            Print(p));
543}
544
545#ifdef __cpp_lib_char8_t
546// const char8_t*.
547TEST(PrintU8StringTest, Const) {
548  const char8_t* p = u8"���";
549  EXPECT_EQ(PrintPointer(p) + " pointing to u8\"\\xE7\\x95\\x8C\"", Print(p));
550}
551
552// char8_t*.
553TEST(PrintU8StringTest, NonConst) {
554  char8_t p[] = u8"���";
555  EXPECT_EQ(PrintPointer(p) + " pointing to u8\"\\xE4\\xB8\\x96\"",
556            Print(static_cast<char8_t*>(p)));
557}
558
559// NULL u8 string.
560TEST(PrintU8StringTest, Null) {
561  const char8_t* p = nullptr;
562  EXPECT_EQ("NULL", Print(p));
563}
564
565// Tests that u8 strings are escaped properly.
566TEST(PrintU8StringTest, EscapesProperly) {
567  const char8_t* p = u8"'\"?\\\a\b\f\n\r\t\v\x7F\xFF hello ������";
568  EXPECT_EQ(PrintPointer(p) +
569                " pointing to u8\"'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\x7F\\xFF "
570                "hello \\xE4\\xB8\\x96\\xE7\\x95\\x8C\"",
571            Print(p));
572}
573#endif
574
575// const char16_t*.
576TEST(PrintU16StringTest, Const) {
577  const char16_t* p = u"���";
578  EXPECT_EQ(PrintPointer(p) + " pointing to u\"\\x754C\"", Print(p));
579}
580
581// char16_t*.
582TEST(PrintU16StringTest, NonConst) {
583  char16_t p[] = u"���";
584  EXPECT_EQ(PrintPointer(p) + " pointing to u\"\\x4E16\"",
585            Print(static_cast<char16_t*>(p)));
586}
587
588// NULL u16 string.
589TEST(PrintU16StringTest, Null) {
590  const char16_t* p = nullptr;
591  EXPECT_EQ("NULL", Print(p));
592}
593
594// Tests that u16 strings are escaped properly.
595TEST(PrintU16StringTest, EscapesProperly) {
596  const char16_t* p = u"'\"?\\\a\b\f\n\r\t\v\x7F\xFF hello ������";
597  EXPECT_EQ(PrintPointer(p) +
598                " pointing to u\"'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\x7F\\xFF "
599                "hello \\x4E16\\x754C\"",
600            Print(p));
601}
602
603// const char32_t*.
604TEST(PrintU32StringTest, Const) {
605  const char32_t* p = U"�������";
606  EXPECT_EQ(PrintPointer(p) + " pointing to U\"\\x1F5FA\\xFE0F\"", Print(p));
607}
608
609// char32_t*.
610TEST(PrintU32StringTest, NonConst) {
611  char32_t p[] = U"����";
612  EXPECT_EQ(PrintPointer(p) + " pointing to U\"\\x1F30C\"",
613            Print(static_cast<char32_t*>(p)));
614}
615
616// NULL u32 string.
617TEST(PrintU32StringTest, Null) {
618  const char32_t* p = nullptr;
619  EXPECT_EQ("NULL", Print(p));
620}
621
622// Tests that u32 strings are escaped properly.
623TEST(PrintU32StringTest, EscapesProperly) {
624  const char32_t* p = U"'\"?\\\a\b\f\n\r\t\v\x7F\xFF hello �������";
625  EXPECT_EQ(PrintPointer(p) +
626                " pointing to U\"'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\x7F\\xFF "
627                "hello \\x1F5FA\\xFE0F\"",
628            Print(p));
629}
630
631// MSVC compiler can be configured to define whar_t as a typedef
632// of unsigned short. Defining an overload for const wchar_t* in that case
633// would cause pointers to unsigned shorts be printed as wide strings,
634// possibly accessing more memory than intended and causing invalid
635// memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when
636// wchar_t is implemented as a native type.
637#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)
638
639// const wchar_t*.
640TEST(PrintWideCStringTest, Const) {
641  const wchar_t* p = L"World";
642  EXPECT_EQ(PrintPointer(p) + " pointing to L\"World\"", Print(p));
643}
644
645// wchar_t*.
646TEST(PrintWideCStringTest, NonConst) {
647  wchar_t p[] = L"Hi";
648  EXPECT_EQ(PrintPointer(p) + " pointing to L\"Hi\"",
649            Print(static_cast<wchar_t*>(p)));
650}
651
652// NULL wide C string.
653TEST(PrintWideCStringTest, Null) {
654  const wchar_t* p = nullptr;
655  EXPECT_EQ("NULL", Print(p));
656}
657
658// Tests that wide C strings are escaped properly.
659TEST(PrintWideCStringTest, EscapesProperly) {
660  const wchar_t s[] = {'\'',  '"',   '?',    '\\', '\a', '\b',
661                       '\f',  '\n',  '\r',   '\t', '\v', 0xD3,
662                       0x576, 0x8D3, 0xC74D, ' ',  'a',  '\0'};
663  EXPECT_EQ(PrintPointer(s) +
664                " pointing to L\"'\\\"?\\\\\\a\\b\\f"
665                "\\n\\r\\t\\v\\xD3\\x576\\x8D3\\xC74D a\"",
666            Print(static_cast<const wchar_t*>(s)));
667}
668#endif  // native wchar_t
669
670// Tests printing pointers to other char types.
671
672// signed char*.
673TEST(PrintCharPointerTest, SignedChar) {
674  signed char* p = reinterpret_cast<signed char*>(0x1234);
675  EXPECT_EQ(PrintPointer(p), Print(p));
676  p = nullptr;
677  EXPECT_EQ("NULL", Print(p));
678}
679
680// const signed char*.
681TEST(PrintCharPointerTest, ConstSignedChar) {
682  signed char* p = reinterpret_cast<signed char*>(0x1234);
683  EXPECT_EQ(PrintPointer(p), Print(p));
684  p = nullptr;
685  EXPECT_EQ("NULL", Print(p));
686}
687
688// unsigned char*.
689TEST(PrintCharPointerTest, UnsignedChar) {
690  unsigned char* p = reinterpret_cast<unsigned char*>(0x1234);
691  EXPECT_EQ(PrintPointer(p), Print(p));
692  p = nullptr;
693  EXPECT_EQ("NULL", Print(p));
694}
695
696// const unsigned char*.
697TEST(PrintCharPointerTest, ConstUnsignedChar) {
698  const unsigned char* p = reinterpret_cast<const unsigned char*>(0x1234);
699  EXPECT_EQ(PrintPointer(p), Print(p));
700  p = nullptr;
701  EXPECT_EQ("NULL", Print(p));
702}
703
704// Tests printing pointers to simple, built-in types.
705
706// bool*.
707TEST(PrintPointerToBuiltInTypeTest, Bool) {
708  bool* p = reinterpret_cast<bool*>(0xABCD);
709  EXPECT_EQ(PrintPointer(p), Print(p));
710  p = nullptr;
711  EXPECT_EQ("NULL", Print(p));
712}
713
714// void*.
715TEST(PrintPointerToBuiltInTypeTest, Void) {
716  void* p = reinterpret_cast<void*>(0xABCD);
717  EXPECT_EQ(PrintPointer(p), Print(p));
718  p = nullptr;
719  EXPECT_EQ("NULL", Print(p));
720}
721
722// const void*.
723TEST(PrintPointerToBuiltInTypeTest, ConstVoid) {
724  const void* p = reinterpret_cast<const void*>(0xABCD);
725  EXPECT_EQ(PrintPointer(p), Print(p));
726  p = nullptr;
727  EXPECT_EQ("NULL", Print(p));
728}
729
730// Tests printing pointers to pointers.
731TEST(PrintPointerToPointerTest, IntPointerPointer) {
732  int** p = reinterpret_cast<int**>(0xABCD);
733  EXPECT_EQ(PrintPointer(p), Print(p));
734  p = nullptr;
735  EXPECT_EQ("NULL", Print(p));
736}
737
738// Tests printing (non-member) function pointers.
739
740void MyFunction(int /* n */) {}
741
742TEST(PrintPointerTest, NonMemberFunctionPointer) {
743  // We cannot directly cast &MyFunction to const void* because the
744  // standard disallows casting between pointers to functions and
745  // pointers to objects, and some compilers (e.g. GCC 3.4) enforce
746  // this limitation.
747  EXPECT_EQ(PrintPointer(reinterpret_cast<const void*>(
748                reinterpret_cast<internal::BiggestInt>(&MyFunction))),
749            Print(&MyFunction));
750  int (*p)(bool) = NULL;  // NOLINT
751  EXPECT_EQ("NULL", Print(p));
752}
753
754// An assertion predicate determining whether a one string is a prefix for
755// another.
756template <typename StringType>
757AssertionResult HasPrefix(const StringType& str, const StringType& prefix) {
758  if (str.find(prefix, 0) == 0) return AssertionSuccess();
759
760  const bool is_wide_string = sizeof(prefix[0]) > 1;
761  const char* const begin_string_quote = is_wide_string ? "L\"" : "\"";
762  return AssertionFailure()
763         << begin_string_quote << prefix << "\" is not a prefix of "
764         << begin_string_quote << str << "\"\n";
765}
766
767// Tests printing member variable pointers.  Although they are called
768// pointers, they don't point to a location in the address space.
769// Their representation is implementation-defined.  Thus they will be
770// printed as raw bytes.
771
772struct Foo {
773 public:
774  virtual ~Foo() = default;
775  int MyMethod(char x) { return x + 1; }
776  virtual char MyVirtualMethod(int /* n */) { return 'a'; }
777
778  int value;
779};
780
781TEST(PrintPointerTest, MemberVariablePointer) {
782  EXPECT_TRUE(HasPrefix(Print(&Foo::value),
783                        Print(sizeof(&Foo::value)) + "-byte object "));
784  int Foo::*p = NULL;  // NOLINT
785  EXPECT_TRUE(HasPrefix(Print(p), Print(sizeof(p)) + "-byte object "));
786}
787
788// Tests printing member function pointers.  Although they are called
789// pointers, they don't point to a location in the address space.
790// Their representation is implementation-defined.  Thus they will be
791// printed as raw bytes.
792TEST(PrintPointerTest, MemberFunctionPointer) {
793  EXPECT_TRUE(HasPrefix(Print(&Foo::MyMethod),
794                        Print(sizeof(&Foo::MyMethod)) + "-byte object "));
795  EXPECT_TRUE(
796      HasPrefix(Print(&Foo::MyVirtualMethod),
797                Print(sizeof((&Foo::MyVirtualMethod))) + "-byte object "));
798  int (Foo::*p)(char) = NULL;  // NOLINT
799  EXPECT_TRUE(HasPrefix(Print(p), Print(sizeof(p)) + "-byte object "));
800}
801
802// Tests printing C arrays.
803
804// The difference between this and Print() is that it ensures that the
805// argument is a reference to an array.
806template <typename T, size_t N>
807std::string PrintArrayHelper(T (&a)[N]) {
808  return Print(a);
809}
810
811// One-dimensional array.
812TEST(PrintArrayTest, OneDimensionalArray) {
813  int a[5] = {1, 2, 3, 4, 5};
814  EXPECT_EQ("{ 1, 2, 3, 4, 5 }", PrintArrayHelper(a));
815}
816
817// Two-dimensional array.
818TEST(PrintArrayTest, TwoDimensionalArray) {
819  int a[2][5] = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 0}};
820  EXPECT_EQ("{ { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 0 } }", PrintArrayHelper(a));
821}
822
823// Array of const elements.
824TEST(PrintArrayTest, ConstArray) {
825  const bool a[1] = {false};
826  EXPECT_EQ("{ false }", PrintArrayHelper(a));
827}
828
829// char array without terminating NUL.
830TEST(PrintArrayTest, CharArrayWithNoTerminatingNul) {
831  // Array a contains '\0' in the middle and doesn't end with '\0'.
832  char a[] = {'H', '\0', 'i'};
833  EXPECT_EQ("\"H\\0i\" (no terminating NUL)", PrintArrayHelper(a));
834}
835
836// char array with terminating NUL.
837TEST(PrintArrayTest, CharArrayWithTerminatingNul) {
838  const char a[] = "\0Hi";
839  EXPECT_EQ("\"\\0Hi\"", PrintArrayHelper(a));
840}
841
842#ifdef __cpp_lib_char8_t
843// char_t array without terminating NUL.
844TEST(PrintArrayTest, Char8ArrayWithNoTerminatingNul) {
845  // Array a contains '\0' in the middle and doesn't end with '\0'.
846  const char8_t a[] = {u8'H', u8'\0', u8'i'};
847  EXPECT_EQ("u8\"H\\0i\" (no terminating NUL)", PrintArrayHelper(a));
848}
849
850// char8_t array with terminating NUL.
851TEST(PrintArrayTest, Char8ArrayWithTerminatingNul) {
852  const char8_t a[] = u8"\0������";
853  EXPECT_EQ("u8\"\\0\\xE4\\xB8\\x96\\xE7\\x95\\x8C\"", PrintArrayHelper(a));
854}
855#endif
856
857// const char16_t array without terminating NUL.
858TEST(PrintArrayTest, Char16ArrayWithNoTerminatingNul) {
859  // Array a contains '\0' in the middle and doesn't end with '\0'.
860  const char16_t a[] = {u'���', u'\0', u'���', u'���', u'���', u'���'};
861  EXPECT_EQ("u\"\\x3053\\0\\x3093\\x306B\\x3061\\x306F\" (no terminating NUL)",
862            PrintArrayHelper(a));
863}
864
865// char16_t array with terminating NUL.
866TEST(PrintArrayTest, Char16ArrayWithTerminatingNul) {
867  const char16_t a[] = u"\0���������������";
868  EXPECT_EQ("u\"\\0\\x3053\\x3093\\x306B\\x3061\\x306F\"", PrintArrayHelper(a));
869}
870
871// char32_t array without terminating NUL.
872TEST(PrintArrayTest, Char32ArrayWithNoTerminatingNul) {
873  // Array a contains '\0' in the middle and doesn't end with '\0'.
874  const char32_t a[] = {U'����', U'\0', U'����'};
875  EXPECT_EQ("U\"\\x1F44B\\0\\x1F30C\" (no terminating NUL)",
876            PrintArrayHelper(a));
877}
878
879// char32_t array with terminating NUL.
880TEST(PrintArrayTest, Char32ArrayWithTerminatingNul) {
881  const char32_t a[] = U"\0��������";
882  EXPECT_EQ("U\"\\0\\x1F44B\\x1F30C\"", PrintArrayHelper(a));
883}
884
885// wchar_t array without terminating NUL.
886TEST(PrintArrayTest, WCharArrayWithNoTerminatingNul) {
887  // Array a contains '\0' in the middle and doesn't end with '\0'.
888  const wchar_t a[] = {L'H', L'\0', L'i'};
889  EXPECT_EQ("L\"H\\0i\" (no terminating NUL)", PrintArrayHelper(a));
890}
891
892// wchar_t array with terminating NUL.
893TEST(PrintArrayTest, WCharArrayWithTerminatingNul) {
894  const wchar_t a[] = L"\0Hi";
895  EXPECT_EQ("L\"\\0Hi\"", PrintArrayHelper(a));
896}
897
898// Array of objects.
899TEST(PrintArrayTest, ObjectArray) {
900  std::string a[3] = {"Hi", "Hello", "Ni hao"};
901  EXPECT_EQ("{ \"Hi\", \"Hello\", \"Ni hao\" }", PrintArrayHelper(a));
902}
903
904// Array with many elements.
905TEST(PrintArrayTest, BigArray) {
906  int a[100] = {1, 2, 3};
907  EXPECT_EQ("{ 1, 2, 3, 0, 0, 0, 0, 0, ..., 0, 0, 0, 0, 0, 0, 0, 0 }",
908            PrintArrayHelper(a));
909}
910
911// Tests printing ::string and ::std::string.
912
913// ::std::string.
914TEST(PrintStringTest, StringInStdNamespace) {
915  const char s[] = "'\"?\\\a\b\f\n\0\r\t\v\x7F\xFF a";
916  const ::std::string str(s, sizeof(s));
917  EXPECT_EQ("\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v\\x7F\\xFF a\\0\"",
918            Print(str));
919}
920
921TEST(PrintStringTest, StringAmbiguousHex) {
922  // "\x6BANANA" is ambiguous, it can be interpreted as starting with either of:
923  // '\x6', '\x6B', or '\x6BA'.
924
925  // a hex escaping sequence following by a decimal digit
926  EXPECT_EQ("\"0\\x12\" \"3\"", Print(::std::string("0\x12"
927                                                    "3")));
928  // a hex escaping sequence following by a hex digit (lower-case)
929  EXPECT_EQ("\"mm\\x6\" \"bananas\"", Print(::std::string("mm\x6"
930                                                          "bananas")));
931  // a hex escaping sequence following by a hex digit (upper-case)
932  EXPECT_EQ("\"NOM\\x6\" \"BANANA\"", Print(::std::string("NOM\x6"
933                                                          "BANANA")));
934  // a hex escaping sequence following by a non-xdigit
935  EXPECT_EQ("\"!\\x5-!\"", Print(::std::string("!\x5-!")));
936}
937
938// Tests printing ::std::wstring.
939#if GTEST_HAS_STD_WSTRING
940// ::std::wstring.
941TEST(PrintWideStringTest, StringInStdNamespace) {
942  const wchar_t s[] = L"'\"?\\\a\b\f\n\0\r\t\v\xD3\x576\x8D3\xC74D a";
943  const ::std::wstring str(s, sizeof(s) / sizeof(wchar_t));
944  EXPECT_EQ(
945      "L\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v"
946      "\\xD3\\x576\\x8D3\\xC74D a\\0\"",
947      Print(str));
948}
949
950TEST(PrintWideStringTest, StringAmbiguousHex) {
951  // same for wide strings.
952  EXPECT_EQ("L\"0\\x12\" L\"3\"", Print(::std::wstring(L"0\x12"
953                                                       L"3")));
954  EXPECT_EQ("L\"mm\\x6\" L\"bananas\"", Print(::std::wstring(L"mm\x6"
955                                                             L"bananas")));
956  EXPECT_EQ("L\"NOM\\x6\" L\"BANANA\"", Print(::std::wstring(L"NOM\x6"
957                                                             L"BANANA")));
958  EXPECT_EQ("L\"!\\x5-!\"", Print(::std::wstring(L"!\x5-!")));
959}
960#endif  // GTEST_HAS_STD_WSTRING
961
962#ifdef __cpp_lib_char8_t
963TEST(PrintStringTest, U8String) {
964  std::u8string str = u8"Hello, ������";
965  EXPECT_EQ(str, str);  // Verify EXPECT_EQ compiles with this type.
966  EXPECT_EQ("u8\"Hello, \\xE4\\xB8\\x96\\xE7\\x95\\x8C\"", Print(str));
967}
968#endif
969
970TEST(PrintStringTest, U16String) {
971  std::u16string str = u"Hello, ������";
972  EXPECT_EQ(str, str);  // Verify EXPECT_EQ compiles with this type.
973  EXPECT_EQ("u\"Hello, \\x4E16\\x754C\"", Print(str));
974}
975
976TEST(PrintStringTest, U32String) {
977  std::u32string str = U"Hello, �������";
978  EXPECT_EQ(str, str);  // Verify EXPECT_EQ compiles with this type
979  EXPECT_EQ("U\"Hello, \\x1F5FA\\xFE0F\"", Print(str));
980}
981
982// Tests printing types that support generic streaming (i.e. streaming
983// to std::basic_ostream<Char, CharTraits> for any valid Char and
984// CharTraits types).
985
986// Tests printing a non-template type that supports generic streaming.
987
988class AllowsGenericStreaming {};
989
990template <typename Char, typename CharTraits>
991std::basic_ostream<Char, CharTraits>& operator<<(
992    std::basic_ostream<Char, CharTraits>& os,
993    const AllowsGenericStreaming& /* a */) {
994  return os << "AllowsGenericStreaming";
995}
996
997TEST(PrintTypeWithGenericStreamingTest, NonTemplateType) {
998  AllowsGenericStreaming a;
999  EXPECT_EQ("AllowsGenericStreaming", Print(a));
1000}
1001
1002// Tests printing a template type that supports generic streaming.
1003
1004template <typename T>
1005class AllowsGenericStreamingTemplate {};
1006
1007template <typename Char, typename CharTraits, typename T>
1008std::basic_ostream<Char, CharTraits>& operator<<(
1009    std::basic_ostream<Char, CharTraits>& os,
1010    const AllowsGenericStreamingTemplate<T>& /* a */) {
1011  return os << "AllowsGenericStreamingTemplate";
1012}
1013
1014TEST(PrintTypeWithGenericStreamingTest, TemplateType) {
1015  AllowsGenericStreamingTemplate<int> a;
1016  EXPECT_EQ("AllowsGenericStreamingTemplate", Print(a));
1017}
1018
1019// Tests printing a type that supports generic streaming and can be
1020// implicitly converted to another printable type.
1021
1022template <typename T>
1023class AllowsGenericStreamingAndImplicitConversionTemplate {
1024 public:
1025  operator bool() const { return false; }
1026};
1027
1028template <typename Char, typename CharTraits, typename T>
1029std::basic_ostream<Char, CharTraits>& operator<<(
1030    std::basic_ostream<Char, CharTraits>& os,
1031    const AllowsGenericStreamingAndImplicitConversionTemplate<T>& /* a */) {
1032  return os << "AllowsGenericStreamingAndImplicitConversionTemplate";
1033}
1034
1035TEST(PrintTypeWithGenericStreamingTest, TypeImplicitlyConvertible) {
1036  AllowsGenericStreamingAndImplicitConversionTemplate<int> a;
1037  EXPECT_EQ("AllowsGenericStreamingAndImplicitConversionTemplate", Print(a));
1038}
1039
1040#if GTEST_INTERNAL_HAS_STRING_VIEW
1041
1042// Tests printing internal::StringView.
1043
1044TEST(PrintStringViewTest, SimpleStringView) {
1045  const internal::StringView sp = "Hello";
1046  EXPECT_EQ("\"Hello\"", Print(sp));
1047}
1048
1049TEST(PrintStringViewTest, UnprintableCharacters) {
1050  const char str[] = "NUL (\0) and \r\t";
1051  const internal::StringView sp(str, sizeof(str) - 1);
1052  EXPECT_EQ("\"NUL (\\0) and \\r\\t\"", Print(sp));
1053}
1054
1055#endif  // GTEST_INTERNAL_HAS_STRING_VIEW
1056
1057// Tests printing STL containers.
1058
1059TEST(PrintStlContainerTest, EmptyDeque) {
1060  deque<char> empty;
1061  EXPECT_EQ("{}", Print(empty));
1062}
1063
1064TEST(PrintStlContainerTest, NonEmptyDeque) {
1065  deque<int> non_empty;
1066  non_empty.push_back(1);
1067  non_empty.push_back(3);
1068  EXPECT_EQ("{ 1, 3 }", Print(non_empty));
1069}
1070
1071TEST(PrintStlContainerTest, OneElementHashMap) {
1072  ::std::unordered_map<int, char> map1;
1073  map1[1] = 'a';
1074  EXPECT_EQ("{ (1, 'a' (97, 0x61)) }", Print(map1));
1075}
1076
1077TEST(PrintStlContainerTest, HashMultiMap) {
1078  ::std::unordered_multimap<int, bool> map1;
1079  map1.insert(make_pair(5, true));
1080  map1.insert(make_pair(5, false));
1081
1082  // Elements of hash_multimap can be printed in any order.
1083  const std::string result = Print(map1);
1084  EXPECT_TRUE(result == "{ (5, true), (5, false) }" ||
1085              result == "{ (5, false), (5, true) }")
1086      << " where Print(map1) returns \"" << result << "\".";
1087}
1088
1089TEST(PrintStlContainerTest, HashSet) {
1090  ::std::unordered_set<int> set1;
1091  set1.insert(1);
1092  EXPECT_EQ("{ 1 }", Print(set1));
1093}
1094
1095TEST(PrintStlContainerTest, HashMultiSet) {
1096  const int kSize = 5;
1097  int a[kSize] = {1, 1, 2, 5, 1};
1098  ::std::unordered_multiset<int> set1(a, a + kSize);
1099
1100  // Elements of hash_multiset can be printed in any order.
1101  const std::string result = Print(set1);
1102  const std::string expected_pattern = "{ d, d, d, d, d }";  // d means a digit.
1103
1104  // Verifies the result matches the expected pattern; also extracts
1105  // the numbers in the result.
1106  ASSERT_EQ(expected_pattern.length(), result.length());
1107  std::vector<int> numbers;
1108  for (size_t i = 0; i != result.length(); i++) {
1109    if (expected_pattern[i] == 'd') {
1110      ASSERT_NE(isdigit(static_cast<unsigned char>(result[i])), 0);
1111      numbers.push_back(result[i] - '0');
1112    } else {
1113      EXPECT_EQ(expected_pattern[i], result[i])
1114          << " where result is " << result;
1115    }
1116  }
1117
1118  // Makes sure the result contains the right numbers.
1119  std::sort(numbers.begin(), numbers.end());
1120  std::sort(a, a + kSize);
1121  EXPECT_TRUE(std::equal(a, a + kSize, numbers.begin()));
1122}
1123
1124TEST(PrintStlContainerTest, List) {
1125  const std::string a[] = {"hello", "world"};
1126  const list<std::string> strings(a, a + 2);
1127  EXPECT_EQ("{ \"hello\", \"world\" }", Print(strings));
1128}
1129
1130TEST(PrintStlContainerTest, Map) {
1131  map<int, bool> map1;
1132  map1[1] = true;
1133  map1[5] = false;
1134  map1[3] = true;
1135  EXPECT_EQ("{ (1, true), (3, true), (5, false) }", Print(map1));
1136}
1137
1138TEST(PrintStlContainerTest, MultiMap) {
1139  multimap<bool, int> map1;
1140  // The make_pair template function would deduce the type as
1141  // pair<bool, int> here, and since the key part in a multimap has to
1142  // be constant, without a templated ctor in the pair class (as in
1143  // libCstd on Solaris), make_pair call would fail to compile as no
1144  // implicit conversion is found.  Thus explicit typename is used
1145  // here instead.
1146  map1.insert(pair<const bool, int>(true, 0));
1147  map1.insert(pair<const bool, int>(true, 1));
1148  map1.insert(pair<const bool, int>(false, 2));
1149  EXPECT_EQ("{ (false, 2), (true, 0), (true, 1) }", Print(map1));
1150}
1151
1152TEST(PrintStlContainerTest, Set) {
1153  const unsigned int a[] = {3, 0, 5};
1154  set<unsigned int> set1(a, a + 3);
1155  EXPECT_EQ("{ 0, 3, 5 }", Print(set1));
1156}
1157
1158TEST(PrintStlContainerTest, MultiSet) {
1159  const int a[] = {1, 1, 2, 5, 1};
1160  multiset<int> set1(a, a + 5);
1161  EXPECT_EQ("{ 1, 1, 1, 2, 5 }", Print(set1));
1162}
1163
1164TEST(PrintStlContainerTest, SinglyLinkedList) {
1165  int a[] = {9, 2, 8};
1166  const std::forward_list<int> ints(a, a + 3);
1167  EXPECT_EQ("{ 9, 2, 8 }", Print(ints));
1168}
1169
1170TEST(PrintStlContainerTest, Pair) {
1171  pair<const bool, int> p(true, 5);
1172  EXPECT_EQ("(true, 5)", Print(p));
1173}
1174
1175TEST(PrintStlContainerTest, Vector) {
1176  vector<int> v;
1177  v.push_back(1);
1178  v.push_back(2);
1179  EXPECT_EQ("{ 1, 2 }", Print(v));
1180}
1181
1182TEST(PrintStlContainerTest, LongSequence) {
1183  const int a[100] = {1, 2, 3};
1184  const vector<int> v(a, a + 100);
1185  EXPECT_EQ(
1186      "{ 1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "
1187      "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ... }",
1188      Print(v));
1189}
1190
1191TEST(PrintStlContainerTest, NestedContainer) {
1192  const int a1[] = {1, 2};
1193  const int a2[] = {3, 4, 5};
1194  const list<int> l1(a1, a1 + 2);
1195  const list<int> l2(a2, a2 + 3);
1196
1197  vector<list<int>> v;
1198  v.push_back(l1);
1199  v.push_back(l2);
1200  EXPECT_EQ("{ { 1, 2 }, { 3, 4, 5 } }", Print(v));
1201}
1202
1203TEST(PrintStlContainerTest, OneDimensionalNativeArray) {
1204  const int a[3] = {1, 2, 3};
1205  NativeArray<int> b(a, 3, RelationToSourceReference());
1206  EXPECT_EQ("{ 1, 2, 3 }", Print(b));
1207}
1208
1209TEST(PrintStlContainerTest, TwoDimensionalNativeArray) {
1210  const int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
1211  NativeArray<int[3]> b(a, 2, RelationToSourceReference());
1212  EXPECT_EQ("{ { 1, 2, 3 }, { 4, 5, 6 } }", Print(b));
1213}
1214
1215// Tests that a class named iterator isn't treated as a container.
1216
1217struct iterator {
1218  char x;
1219};
1220
1221TEST(PrintStlContainerTest, Iterator) {
1222  iterator it = {};
1223  EXPECT_EQ("1-byte object <00>", Print(it));
1224}
1225
1226// Tests that a class named const_iterator isn't treated as a container.
1227
1228struct const_iterator {
1229  char x;
1230};
1231
1232TEST(PrintStlContainerTest, ConstIterator) {
1233  const_iterator it = {};
1234  EXPECT_EQ("1-byte object <00>", Print(it));
1235}
1236
1237// Tests printing ::std::tuples.
1238
1239// Tuples of various arities.
1240TEST(PrintStdTupleTest, VariousSizes) {
1241  ::std::tuple<> t0;
1242  EXPECT_EQ("()", Print(t0));
1243
1244  ::std::tuple<int> t1(5);
1245  EXPECT_EQ("(5)", Print(t1));
1246
1247  ::std::tuple<char, bool> t2('a', true);
1248  EXPECT_EQ("('a' (97, 0x61), true)", Print(t2));
1249
1250  ::std::tuple<bool, int, int> t3(false, 2, 3);
1251  EXPECT_EQ("(false, 2, 3)", Print(t3));
1252
1253  ::std::tuple<bool, int, int, int> t4(false, 2, 3, 4);
1254  EXPECT_EQ("(false, 2, 3, 4)", Print(t4));
1255
1256  const char* const str = "8";
1257  ::std::tuple<bool, char, short, int32_t, int64_t, float, double,  // NOLINT
1258               const char*, void*, std::string>
1259      t10(false, 'a', static_cast<short>(3), 4, 5, 1.5F, -2.5, str,  // NOLINT
1260          nullptr, "10");
1261  EXPECT_EQ("(false, 'a' (97, 0x61), 3, 4, 5, 1.5, -2.5, " + PrintPointer(str) +
1262                " pointing to \"8\", NULL, \"10\")",
1263            Print(t10));
1264}
1265
1266// Nested tuples.
1267TEST(PrintStdTupleTest, NestedTuple) {
1268  ::std::tuple<::std::tuple<int, bool>, char> nested(::std::make_tuple(5, true),
1269                                                     'a');
1270  EXPECT_EQ("((5, true), 'a' (97, 0x61))", Print(nested));
1271}
1272
1273TEST(PrintNullptrT, Basic) { EXPECT_EQ("(nullptr)", Print(nullptr)); }
1274
1275TEST(PrintReferenceWrapper, Printable) {
1276  int x = 5;
1277  EXPECT_EQ("@" + PrintPointer(&x) + " 5", Print(std::ref(x)));
1278  EXPECT_EQ("@" + PrintPointer(&x) + " 5", Print(std::cref(x)));
1279}
1280
1281TEST(PrintReferenceWrapper, Unprintable) {
1282  ::foo::UnprintableInFoo up;
1283  EXPECT_EQ(
1284      "@" + PrintPointer(&up) +
1285          " 16-byte object <EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>",
1286      Print(std::ref(up)));
1287  EXPECT_EQ(
1288      "@" + PrintPointer(&up) +
1289          " 16-byte object <EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>",
1290      Print(std::cref(up)));
1291}
1292
1293// Tests printing user-defined unprintable types.
1294
1295// Unprintable types in the global namespace.
1296TEST(PrintUnprintableTypeTest, InGlobalNamespace) {
1297  EXPECT_EQ("1-byte object <00>", Print(UnprintableTemplateInGlobal<char>()));
1298}
1299
1300// Unprintable types in a user namespace.
1301TEST(PrintUnprintableTypeTest, InUserNamespace) {
1302  EXPECT_EQ("16-byte object <EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>",
1303            Print(::foo::UnprintableInFoo()));
1304}
1305
1306// Unprintable types are that too big to be printed completely.
1307
1308struct Big {
1309  Big() { memset(array, 0, sizeof(array)); }
1310  char array[257];
1311};
1312
1313TEST(PrintUnpritableTypeTest, BigObject) {
1314  EXPECT_EQ(
1315      "257-byte object <00-00 00-00 00-00 00-00 00-00 00-00 "
1316      "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
1317      "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
1318      "00-00 00-00 00-00 00-00 00-00 00-00 ... 00-00 00-00 00-00 "
1319      "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
1320      "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 "
1321      "00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00>",
1322      Print(Big()));
1323}
1324
1325// Tests printing user-defined streamable types.
1326
1327// Streamable types in the global namespace.
1328TEST(PrintStreamableTypeTest, InGlobalNamespace) {
1329  StreamableInGlobal x;
1330  EXPECT_EQ("StreamableInGlobal", Print(x));
1331  EXPECT_EQ("StreamableInGlobal*", Print(&x));
1332}
1333
1334// Printable template types in a user namespace.
1335TEST(PrintStreamableTypeTest, TemplateTypeInUserNamespace) {
1336  EXPECT_EQ("StreamableTemplateInFoo: 0",
1337            Print(::foo::StreamableTemplateInFoo<int>()));
1338}
1339
1340TEST(PrintStreamableTypeTest, TypeInUserNamespaceWithTemplatedStreamOperator) {
1341  EXPECT_EQ("TemplatedStreamableInFoo",
1342            Print(::foo::TemplatedStreamableInFoo()));
1343}
1344
1345TEST(PrintStreamableTypeTest, SubclassUsesSuperclassStreamOperator) {
1346  ParentClass parent;
1347  ChildClassWithStreamOperator child_stream;
1348  ChildClassWithoutStreamOperator child_no_stream;
1349  EXPECT_EQ("ParentClass", Print(parent));
1350  EXPECT_EQ("ChildClassWithStreamOperator", Print(child_stream));
1351  EXPECT_EQ("ParentClass", Print(child_no_stream));
1352}
1353
1354// Tests printing a user-defined recursive container type that has a <<
1355// operator.
1356TEST(PrintStreamableTypeTest, PathLikeInUserNamespace) {
1357  ::foo::PathLike x;
1358  EXPECT_EQ("Streamable-PathLike", Print(x));
1359  const ::foo::PathLike cx;
1360  EXPECT_EQ("Streamable-PathLike", Print(cx));
1361}
1362
1363// Tests printing user-defined types that have a PrintTo() function.
1364TEST(PrintPrintableTypeTest, InUserNamespace) {
1365  EXPECT_EQ("PrintableViaPrintTo: 0", Print(::foo::PrintableViaPrintTo()));
1366}
1367
1368// Tests printing a pointer to a user-defined type that has a <<
1369// operator for its pointer.
1370TEST(PrintPrintableTypeTest, PointerInUserNamespace) {
1371  ::foo::PointerPrintable x;
1372  EXPECT_EQ("PointerPrintable*", Print(&x));
1373}
1374
1375// Tests printing user-defined class template that have a PrintTo() function.
1376TEST(PrintPrintableTypeTest, TemplateInUserNamespace) {
1377  EXPECT_EQ("PrintableViaPrintToTemplate: 5",
1378            Print(::foo::PrintableViaPrintToTemplate<int>(5)));
1379}
1380
1381// Tests that the universal printer prints both the address and the
1382// value of a reference.
1383TEST(PrintReferenceTest, PrintsAddressAndValue) {
1384  int n = 5;
1385  EXPECT_EQ("@" + PrintPointer(&n) + " 5", PrintByRef(n));
1386
1387  int a[2][3] = {{0, 1, 2}, {3, 4, 5}};
1388  EXPECT_EQ("@" + PrintPointer(a) + " { { 0, 1, 2 }, { 3, 4, 5 } }",
1389            PrintByRef(a));
1390
1391  const ::foo::UnprintableInFoo x;
1392  EXPECT_EQ("@" + PrintPointer(&x) +
1393                " 16-byte object "
1394                "<EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>",
1395            PrintByRef(x));
1396}
1397
1398// Tests that the universal printer prints a function pointer passed by
1399// reference.
1400TEST(PrintReferenceTest, HandlesFunctionPointer) {
1401  void (*fp)(int n) = &MyFunction;
1402  const std::string fp_pointer_string =
1403      PrintPointer(reinterpret_cast<const void*>(&fp));
1404  // We cannot directly cast &MyFunction to const void* because the
1405  // standard disallows casting between pointers to functions and
1406  // pointers to objects, and some compilers (e.g. GCC 3.4) enforce
1407  // this limitation.
1408  const std::string fp_string = PrintPointer(reinterpret_cast<const void*>(
1409      reinterpret_cast<internal::BiggestInt>(fp)));
1410  EXPECT_EQ("@" + fp_pointer_string + " " + fp_string, PrintByRef(fp));
1411}
1412
1413// Tests that the universal printer prints a member function pointer
1414// passed by reference.
1415TEST(PrintReferenceTest, HandlesMemberFunctionPointer) {
1416  int (Foo::*p)(char ch) = &Foo::MyMethod;
1417  EXPECT_TRUE(HasPrefix(PrintByRef(p),
1418                        "@" + PrintPointer(reinterpret_cast<const void*>(&p)) +
1419                            " " + Print(sizeof(p)) + "-byte object "));
1420
1421  char (Foo::*p2)(int n) = &Foo::MyVirtualMethod;
1422  EXPECT_TRUE(HasPrefix(PrintByRef(p2),
1423                        "@" + PrintPointer(reinterpret_cast<const void*>(&p2)) +
1424                            " " + Print(sizeof(p2)) + "-byte object "));
1425}
1426
1427// Tests that the universal printer prints a member variable pointer
1428// passed by reference.
1429TEST(PrintReferenceTest, HandlesMemberVariablePointer) {
1430  int Foo::*p = &Foo::value;  // NOLINT
1431  EXPECT_TRUE(HasPrefix(PrintByRef(p), "@" + PrintPointer(&p) + " " +
1432                                           Print(sizeof(p)) + "-byte object "));
1433}
1434
1435// Tests that FormatForComparisonFailureMessage(), which is used to print
1436// an operand in a comparison assertion (e.g. ASSERT_EQ) when the assertion
1437// fails, formats the operand in the desired way.
1438
1439// scalar
1440TEST(FormatForComparisonFailureMessageTest, WorksForScalar) {
1441  EXPECT_STREQ("123", FormatForComparisonFailureMessage(123, 124).c_str());
1442}
1443
1444// non-char pointer
1445TEST(FormatForComparisonFailureMessageTest, WorksForNonCharPointer) {
1446  int n = 0;
1447  EXPECT_EQ(PrintPointer(&n),
1448            FormatForComparisonFailureMessage(&n, &n).c_str());
1449}
1450
1451// non-char array
1452TEST(FormatForComparisonFailureMessageTest, FormatsNonCharArrayAsPointer) {
1453  // In expression 'array == x', 'array' is compared by pointer.
1454  // Therefore we want to print an array operand as a pointer.
1455  int n[] = {1, 2, 3};
1456  EXPECT_EQ(PrintPointer(n), FormatForComparisonFailureMessage(n, n).c_str());
1457}
1458
1459// Tests formatting a char pointer when it's compared with another pointer.
1460// In this case we want to print it as a raw pointer, as the comparison is by
1461// pointer.
1462
1463// char pointer vs pointer
1464TEST(FormatForComparisonFailureMessageTest, WorksForCharPointerVsPointer) {
1465  // In expression 'p == x', where 'p' and 'x' are (const or not) char
1466  // pointers, the operands are compared by pointer.  Therefore we
1467  // want to print 'p' as a pointer instead of a C string (we don't
1468  // even know if it's supposed to point to a valid C string).
1469
1470  // const char*
1471  const char* s = "hello";
1472  EXPECT_EQ(PrintPointer(s), FormatForComparisonFailureMessage(s, s).c_str());
1473
1474  // char*
1475  char ch = 'a';
1476  EXPECT_EQ(PrintPointer(&ch),
1477            FormatForComparisonFailureMessage(&ch, &ch).c_str());
1478}
1479
1480// wchar_t pointer vs pointer
1481TEST(FormatForComparisonFailureMessageTest, WorksForWCharPointerVsPointer) {
1482  // In expression 'p == x', where 'p' and 'x' are (const or not) char
1483  // pointers, the operands are compared by pointer.  Therefore we
1484  // want to print 'p' as a pointer instead of a wide C string (we don't
1485  // even know if it's supposed to point to a valid wide C string).
1486
1487  // const wchar_t*
1488  const wchar_t* s = L"hello";
1489  EXPECT_EQ(PrintPointer(s), FormatForComparisonFailureMessage(s, s).c_str());
1490
1491  // wchar_t*
1492  wchar_t ch = L'a';
1493  EXPECT_EQ(PrintPointer(&ch),
1494            FormatForComparisonFailureMessage(&ch, &ch).c_str());
1495}
1496
1497// Tests formatting a char pointer when it's compared to a string object.
1498// In this case we want to print the char pointer as a C string.
1499
1500// char pointer vs std::string
1501TEST(FormatForComparisonFailureMessageTest, WorksForCharPointerVsStdString) {
1502  const char* s = "hello \"world";
1503  EXPECT_STREQ("\"hello \\\"world\"",  // The string content should be escaped.
1504               FormatForComparisonFailureMessage(s, ::std::string()).c_str());
1505
1506  // char*
1507  char str[] = "hi\1";
1508  char* p = str;
1509  EXPECT_STREQ("\"hi\\x1\"",  // The string content should be escaped.
1510               FormatForComparisonFailureMessage(p, ::std::string()).c_str());
1511}
1512
1513#if GTEST_HAS_STD_WSTRING
1514// wchar_t pointer vs std::wstring
1515TEST(FormatForComparisonFailureMessageTest, WorksForWCharPointerVsStdWString) {
1516  const wchar_t* s = L"hi \"world";
1517  EXPECT_STREQ("L\"hi \\\"world\"",  // The string content should be escaped.
1518               FormatForComparisonFailureMessage(s, ::std::wstring()).c_str());
1519
1520  // wchar_t*
1521  wchar_t str[] = L"hi\1";
1522  wchar_t* p = str;
1523  EXPECT_STREQ("L\"hi\\x1\"",  // The string content should be escaped.
1524               FormatForComparisonFailureMessage(p, ::std::wstring()).c_str());
1525}
1526#endif
1527
1528// Tests formatting a char array when it's compared with a pointer or array.
1529// In this case we want to print the array as a row pointer, as the comparison
1530// is by pointer.
1531
1532// char array vs pointer
1533TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsPointer) {
1534  char str[] = "hi \"world\"";
1535  char* p = nullptr;
1536  EXPECT_EQ(PrintPointer(str),
1537            FormatForComparisonFailureMessage(str, p).c_str());
1538}
1539
1540// char array vs char array
1541TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsCharArray) {
1542  const char str[] = "hi \"world\"";
1543  EXPECT_EQ(PrintPointer(str),
1544            FormatForComparisonFailureMessage(str, str).c_str());
1545}
1546
1547// wchar_t array vs pointer
1548TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsPointer) {
1549  wchar_t str[] = L"hi \"world\"";
1550  wchar_t* p = nullptr;
1551  EXPECT_EQ(PrintPointer(str),
1552            FormatForComparisonFailureMessage(str, p).c_str());
1553}
1554
1555// wchar_t array vs wchar_t array
1556TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsWCharArray) {
1557  const wchar_t str[] = L"hi \"world\"";
1558  EXPECT_EQ(PrintPointer(str),
1559            FormatForComparisonFailureMessage(str, str).c_str());
1560}
1561
1562// Tests formatting a char array when it's compared with a string object.
1563// In this case we want to print the array as a C string.
1564
1565// char array vs std::string
1566TEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsStdString) {
1567  const char str[] = "hi \"world\"";
1568  EXPECT_STREQ("\"hi \\\"world\\\"\"",  // The content should be escaped.
1569               FormatForComparisonFailureMessage(str, ::std::string()).c_str());
1570}
1571
1572#if GTEST_HAS_STD_WSTRING
1573// wchar_t array vs std::wstring
1574TEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsStdWString) {
1575  const wchar_t str[] = L"hi \"w\0rld\"";
1576  EXPECT_STREQ(
1577      "L\"hi \\\"w\"",  // The content should be escaped.
1578                        // Embedded NUL terminates the string.
1579      FormatForComparisonFailureMessage(str, ::std::wstring()).c_str());
1580}
1581#endif
1582
1583// Useful for testing PrintToString().  We cannot use EXPECT_EQ()
1584// there as its implementation uses PrintToString().  The caller must
1585// ensure that 'value' has no side effect.
1586#define EXPECT_PRINT_TO_STRING_(value, expected_string)  \
1587  EXPECT_TRUE(PrintToString(value) == (expected_string)) \
1588      << " where " #value " prints as " << (PrintToString(value))
1589
1590TEST(PrintToStringTest, WorksForScalar) { EXPECT_PRINT_TO_STRING_(123, "123"); }
1591
1592TEST(PrintToStringTest, WorksForPointerToConstChar) {
1593  const char* p = "hello";
1594  EXPECT_PRINT_TO_STRING_(p, "\"hello\"");
1595}
1596
1597TEST(PrintToStringTest, WorksForPointerToNonConstChar) {
1598  char s[] = "hello";
1599  char* p = s;
1600  EXPECT_PRINT_TO_STRING_(p, "\"hello\"");
1601}
1602
1603TEST(PrintToStringTest, EscapesForPointerToConstChar) {
1604  const char* p = "hello\n";
1605  EXPECT_PRINT_TO_STRING_(p, "\"hello\\n\"");
1606}
1607
1608TEST(PrintToStringTest, EscapesForPointerToNonConstChar) {
1609  char s[] = "hello\1";
1610  char* p = s;
1611  EXPECT_PRINT_TO_STRING_(p, "\"hello\\x1\"");
1612}
1613
1614TEST(PrintToStringTest, WorksForArray) {
1615  int n[3] = {1, 2, 3};
1616  EXPECT_PRINT_TO_STRING_(n, "{ 1, 2, 3 }");
1617}
1618
1619TEST(PrintToStringTest, WorksForCharArray) {
1620  char s[] = "hello";
1621  EXPECT_PRINT_TO_STRING_(s, "\"hello\"");
1622}
1623
1624TEST(PrintToStringTest, WorksForCharArrayWithEmbeddedNul) {
1625  const char str_with_nul[] = "hello\0 world";
1626  EXPECT_PRINT_TO_STRING_(str_with_nul, "\"hello\\0 world\"");
1627
1628  char mutable_str_with_nul[] = "hello\0 world";
1629  EXPECT_PRINT_TO_STRING_(mutable_str_with_nul, "\"hello\\0 world\"");
1630}
1631
1632TEST(PrintToStringTest, ContainsNonLatin) {
1633  // Test with valid UTF-8. Prints both in hex and as text.
1634  std::string non_ascii_str = ::std::string("������ 4:30");
1635  EXPECT_PRINT_TO_STRING_(non_ascii_str,
1636                          "\"\\xEC\\x98\\xA4\\xEC\\xA0\\x84 4:30\"\n"
1637                          "    As Text: \"������ 4:30\"");
1638  non_ascii_str = ::std::string("From �� ��� ���");
1639  EXPECT_PRINT_TO_STRING_(non_ascii_str,
1640                          "\"From \\xC3\\xA4 \\xE2\\x80\\x94 \\xE1\\xBA\\x91\""
1641                          "\n    As Text: \"From �� ��� ���\"");
1642}
1643
1644TEST(PrintToStringTest, PrintStreamableInLocal) {
1645  EXPECT_STREQ("StreamableInLocal",
1646               PrintToString(foo::StreamableInLocal()).c_str());
1647}
1648
1649TEST(PrintToStringTest, PrintReferenceToStreamableInLocal) {
1650  foo::StreamableInLocal s;
1651  std::reference_wrapper<foo::StreamableInLocal> r(s);
1652  EXPECT_STREQ("StreamableInLocal", PrintToString(r).c_str());
1653}
1654
1655TEST(PrintToStringTest, PrintReferenceToStreamableInGlobal) {
1656  StreamableInGlobal s;
1657  std::reference_wrapper<StreamableInGlobal> r(s);
1658  EXPECT_STREQ("StreamableInGlobal", PrintToString(r).c_str());
1659}
1660
1661#ifdef GTEST_HAS_ABSL
1662TEST(PrintToStringTest, AbslStringify) {
1663  EXPECT_PRINT_TO_STRING_(Point(), "(10, 20)");
1664}
1665#endif
1666
1667TEST(IsValidUTF8Test, IllFormedUTF8) {
1668  // The following test strings are ill-formed UTF-8 and are printed
1669  // as hex only (or ASCII, in case of ASCII bytes) because IsValidUTF8() is
1670  // expected to fail, thus output does not contain "As Text:".
1671
1672  static const char* const kTestdata[][2] = {
1673      // 2-byte lead byte followed by a single-byte character.
1674      {"\xC3\x74", "\"\\xC3t\""},
1675      // Valid 2-byte character followed by an orphan trail byte.
1676      {"\xC3\x84\xA4", "\"\\xC3\\x84\\xA4\""},
1677      // Lead byte without trail byte.
1678      {"abc\xC3", "\"abc\\xC3\""},
1679      // 3-byte lead byte, single-byte character, orphan trail byte.
1680      {"x\xE2\x70\x94", "\"x\\xE2p\\x94\""},
1681      // Truncated 3-byte character.
1682      {"\xE2\x80", "\"\\xE2\\x80\""},
1683      // Truncated 3-byte character followed by valid 2-byte char.
1684      {"\xE2\x80\xC3\x84", "\"\\xE2\\x80\\xC3\\x84\""},
1685      // Truncated 3-byte character followed by a single-byte character.
1686      {"\xE2\x80\x7A", "\"\\xE2\\x80z\""},
1687      // 3-byte lead byte followed by valid 3-byte character.
1688      {"\xE2\xE2\x80\x94", "\"\\xE2\\xE2\\x80\\x94\""},
1689      // 4-byte lead byte followed by valid 3-byte character.
1690      {"\xF0\xE2\x80\x94", "\"\\xF0\\xE2\\x80\\x94\""},
1691      // Truncated 4-byte character.
1692      {"\xF0\xE2\x80", "\"\\xF0\\xE2\\x80\""},
1693      // Invalid UTF-8 byte sequences embedded in other chars.
1694      {"abc\xE2\x80\x94\xC3\x74xyc", "\"abc\\xE2\\x80\\x94\\xC3txyc\""},
1695      {"abc\xC3\x84\xE2\x80\xC3\x84xyz",
1696       "\"abc\\xC3\\x84\\xE2\\x80\\xC3\\x84xyz\""},
1697      // Non-shortest UTF-8 byte sequences are also ill-formed.
1698      // The classics: xC0, xC1 lead byte.
1699      {"\xC0\x80", "\"\\xC0\\x80\""},
1700      {"\xC1\x81", "\"\\xC1\\x81\""},
1701      // Non-shortest sequences.
1702      {"\xE0\x80\x80", "\"\\xE0\\x80\\x80\""},
1703      {"\xf0\x80\x80\x80", "\"\\xF0\\x80\\x80\\x80\""},
1704      // Last valid code point before surrogate range, should be printed as
1705      // text,
1706      // too.
1707      {"\xED\x9F\xBF", "\"\\xED\\x9F\\xBF\"\n    As Text: \"���\""},
1708      // Start of surrogate lead. Surrogates are not printed as text.
1709      {"\xED\xA0\x80", "\"\\xED\\xA0\\x80\""},
1710      // Last non-private surrogate lead.
1711      {"\xED\xAD\xBF", "\"\\xED\\xAD\\xBF\""},
1712      // First private-use surrogate lead.
1713      {"\xED\xAE\x80", "\"\\xED\\xAE\\x80\""},
1714      // Last private-use surrogate lead.
1715      {"\xED\xAF\xBF", "\"\\xED\\xAF\\xBF\""},
1716      // Mid-point of surrogate trail.
1717      {"\xED\xB3\xBF", "\"\\xED\\xB3\\xBF\""},
1718      // First valid code point after surrogate range, should be printed as
1719      // text,
1720      // too.
1721      {"\xEE\x80\x80", "\"\\xEE\\x80\\x80\"\n    As Text: \"���\""}};
1722
1723  for (int i = 0; i < int(sizeof(kTestdata) / sizeof(kTestdata[0])); ++i) {
1724    EXPECT_PRINT_TO_STRING_(kTestdata[i][0], kTestdata[i][1]);
1725  }
1726}
1727
1728#undef EXPECT_PRINT_TO_STRING_
1729
1730TEST(UniversalTersePrintTest, WorksForNonReference) {
1731  ::std::stringstream ss;
1732  UniversalTersePrint(123, &ss);
1733  EXPECT_EQ("123", ss.str());
1734}
1735
1736TEST(UniversalTersePrintTest, WorksForReference) {
1737  const int& n = 123;
1738  ::std::stringstream ss;
1739  UniversalTersePrint(n, &ss);
1740  EXPECT_EQ("123", ss.str());
1741}
1742
1743TEST(UniversalTersePrintTest, WorksForCString) {
1744  const char* s1 = "abc";
1745  ::std::stringstream ss1;
1746  UniversalTersePrint(s1, &ss1);
1747  EXPECT_EQ("\"abc\"", ss1.str());
1748
1749  char* s2 = const_cast<char*>(s1);
1750  ::std::stringstream ss2;
1751  UniversalTersePrint(s2, &ss2);
1752  EXPECT_EQ("\"abc\"", ss2.str());
1753
1754  const char* s3 = nullptr;
1755  ::std::stringstream ss3;
1756  UniversalTersePrint(s3, &ss3);
1757  EXPECT_EQ("NULL", ss3.str());
1758}
1759
1760TEST(UniversalPrintTest, WorksForNonReference) {
1761  ::std::stringstream ss;
1762  UniversalPrint(123, &ss);
1763  EXPECT_EQ("123", ss.str());
1764}
1765
1766TEST(UniversalPrintTest, WorksForReference) {
1767  const int& n = 123;
1768  ::std::stringstream ss;
1769  UniversalPrint(n, &ss);
1770  EXPECT_EQ("123", ss.str());
1771}
1772
1773TEST(UniversalPrintTest, WorksForPairWithConst) {
1774  std::pair<const Wrapper<std::string>, int> p(Wrapper<std::string>("abc"), 1);
1775  ::std::stringstream ss;
1776  UniversalPrint(p, &ss);
1777  EXPECT_EQ("(Wrapper(\"abc\"), 1)", ss.str());
1778}
1779
1780TEST(UniversalPrintTest, WorksForCString) {
1781  const char* s1 = "abc";
1782  ::std::stringstream ss1;
1783  UniversalPrint(s1, &ss1);
1784  EXPECT_EQ(PrintPointer(s1) + " pointing to \"abc\"", std::string(ss1.str()));
1785
1786  char* s2 = const_cast<char*>(s1);
1787  ::std::stringstream ss2;
1788  UniversalPrint(s2, &ss2);
1789  EXPECT_EQ(PrintPointer(s2) + " pointing to \"abc\"", std::string(ss2.str()));
1790
1791  const char* s3 = nullptr;
1792  ::std::stringstream ss3;
1793  UniversalPrint(s3, &ss3);
1794  EXPECT_EQ("NULL", ss3.str());
1795}
1796
1797TEST(UniversalPrintTest, WorksForCharArray) {
1798  const char str[] = "\"Line\0 1\"\nLine 2";
1799  ::std::stringstream ss1;
1800  UniversalPrint(str, &ss1);
1801  EXPECT_EQ("\"\\\"Line\\0 1\\\"\\nLine 2\"", ss1.str());
1802
1803  const char mutable_str[] = "\"Line\0 1\"\nLine 2";
1804  ::std::stringstream ss2;
1805  UniversalPrint(mutable_str, &ss2);
1806  EXPECT_EQ("\"\\\"Line\\0 1\\\"\\nLine 2\"", ss2.str());
1807}
1808
1809TEST(UniversalPrintTest, IncompleteType) {
1810  struct Incomplete;
1811  char some_object = 0;
1812  EXPECT_EQ("(incomplete type)",
1813            PrintToString(reinterpret_cast<Incomplete&>(some_object)));
1814}
1815
1816TEST(UniversalPrintTest, SmartPointers) {
1817  EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<int>()));
1818  std::unique_ptr<int> p(new int(17));
1819  EXPECT_EQ("(ptr = " + PrintPointer(p.get()) + ", value = 17)",
1820            PrintToString(p));
1821  std::unique_ptr<int[]> p2(new int[2]);
1822  EXPECT_EQ("(" + PrintPointer(p2.get()) + ")", PrintToString(p2));
1823
1824  EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<int>()));
1825  std::shared_ptr<int> p3(new int(1979));
1826  EXPECT_EQ("(ptr = " + PrintPointer(p3.get()) + ", value = 1979)",
1827            PrintToString(p3));
1828#if defined(__cpp_lib_shared_ptr_arrays) && \
1829    (__cpp_lib_shared_ptr_arrays >= 201611L)
1830  std::shared_ptr<int[]> p4(new int[2]);
1831  EXPECT_EQ("(" + PrintPointer(p4.get()) + ")", PrintToString(p4));
1832#endif
1833
1834  // modifiers
1835  EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<int>()));
1836  EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<const int>()));
1837  EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<volatile int>()));
1838  EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<volatile const int>()));
1839  EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<int[]>()));
1840  EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<const int[]>()));
1841  EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<volatile int[]>()));
1842  EXPECT_EQ("(nullptr)",
1843            PrintToString(std::unique_ptr<volatile const int[]>()));
1844  EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<int>()));
1845  EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<const int>()));
1846  EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<volatile int>()));
1847  EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<volatile const int>()));
1848#if defined(__cpp_lib_shared_ptr_arrays) && \
1849    (__cpp_lib_shared_ptr_arrays >= 201611L)
1850  EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<int[]>()));
1851  EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<const int[]>()));
1852  EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<volatile int[]>()));
1853  EXPECT_EQ("(nullptr)",
1854            PrintToString(std::shared_ptr<volatile const int[]>()));
1855#endif
1856
1857  // void
1858  EXPECT_EQ("(nullptr)", PrintToString(std::unique_ptr<void, void (*)(void*)>(
1859                             nullptr, nullptr)));
1860  EXPECT_EQ("(" + PrintPointer(p.get()) + ")",
1861            PrintToString(
1862                std::unique_ptr<void, void (*)(void*)>(p.get(), [](void*) {})));
1863  EXPECT_EQ("(nullptr)", PrintToString(std::shared_ptr<void>()));
1864  EXPECT_EQ("(" + PrintPointer(p.get()) + ")",
1865            PrintToString(std::shared_ptr<void>(p.get(), [](void*) {})));
1866}
1867
1868TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsEmptyTuple) {
1869  Strings result = UniversalTersePrintTupleFieldsToStrings(::std::make_tuple());
1870  EXPECT_EQ(0u, result.size());
1871}
1872
1873TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsOneTuple) {
1874  Strings result =
1875      UniversalTersePrintTupleFieldsToStrings(::std::make_tuple(1));
1876  ASSERT_EQ(1u, result.size());
1877  EXPECT_EQ("1", result[0]);
1878}
1879
1880TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsTwoTuple) {
1881  Strings result =
1882      UniversalTersePrintTupleFieldsToStrings(::std::make_tuple(1, 'a'));
1883  ASSERT_EQ(2u, result.size());
1884  EXPECT_EQ("1", result[0]);
1885  EXPECT_EQ("'a' (97, 0x61)", result[1]);
1886}
1887
1888TEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsTersely) {
1889  const int n = 1;
1890  Strings result = UniversalTersePrintTupleFieldsToStrings(
1891      ::std::tuple<const int&, const char*>(n, "a"));
1892  ASSERT_EQ(2u, result.size());
1893  EXPECT_EQ("1", result[0]);
1894  EXPECT_EQ("\"a\"", result[1]);
1895}
1896
1897#if GTEST_INTERNAL_HAS_ANY
1898class PrintAnyTest : public ::testing::Test {
1899 protected:
1900  template <typename T>
1901  static std::string ExpectedTypeName() {
1902#if GTEST_HAS_RTTI
1903    return internal::GetTypeName<T>();
1904#else
1905    return "<unknown_type>";
1906#endif  // GTEST_HAS_RTTI
1907  }
1908};
1909
1910TEST_F(PrintAnyTest, Empty) {
1911  internal::Any any;
1912  EXPECT_EQ("no value", PrintToString(any));
1913}
1914
1915TEST_F(PrintAnyTest, NonEmpty) {
1916  internal::Any any;
1917  constexpr int val1 = 10;
1918  const std::string val2 = "content";
1919
1920  any = val1;
1921  EXPECT_EQ("value of type " + ExpectedTypeName<int>(), PrintToString(any));
1922
1923  any = val2;
1924  EXPECT_EQ("value of type " + ExpectedTypeName<std::string>(),
1925            PrintToString(any));
1926}
1927#endif  // GTEST_INTERNAL_HAS_ANY
1928
1929#if GTEST_INTERNAL_HAS_OPTIONAL
1930TEST(PrintOptionalTest, Basic) {
1931  EXPECT_EQ("(nullopt)", PrintToString(internal::Nullopt()));
1932  internal::Optional<int> value;
1933  EXPECT_EQ("(nullopt)", PrintToString(value));
1934  value = {7};
1935  EXPECT_EQ("(7)", PrintToString(value));
1936  EXPECT_EQ("(1.1)", PrintToString(internal::Optional<double>{1.1}));
1937  EXPECT_EQ("(\"A\")", PrintToString(internal::Optional<std::string>{"A"}));
1938}
1939#endif  // GTEST_INTERNAL_HAS_OPTIONAL
1940
1941#if GTEST_INTERNAL_HAS_VARIANT
1942struct NonPrintable {
1943  unsigned char contents = 17;
1944};
1945
1946TEST(PrintOneofTest, Basic) {
1947  using Type = internal::Variant<int, StreamableInGlobal, NonPrintable>;
1948  EXPECT_EQ("('int(index = 0)' with value 7)", PrintToString(Type(7)));
1949  EXPECT_EQ("('StreamableInGlobal(index = 1)' with value StreamableInGlobal)",
1950            PrintToString(Type(StreamableInGlobal{})));
1951  EXPECT_EQ(
1952      "('testing::gtest_printers_test::NonPrintable(index = 2)' with value "
1953      "1-byte object <11>)",
1954      PrintToString(Type(NonPrintable{})));
1955}
1956#endif  // GTEST_INTERNAL_HAS_VARIANT
1957namespace {
1958class string_ref;
1959
1960/**
1961 * This is a synthetic pointer to a fixed size string.
1962 */
1963class string_ptr {
1964 public:
1965  string_ptr(const char* data, size_t size) : data_(data), size_(size) {}
1966
1967  string_ptr& operator++() noexcept {
1968    data_ += size_;
1969    return *this;
1970  }
1971
1972  string_ref operator*() const noexcept;
1973
1974 private:
1975  const char* data_;
1976  size_t size_;
1977};
1978
1979/**
1980 * This is a synthetic reference of a fixed size string.
1981 */
1982class string_ref {
1983 public:
1984  string_ref(const char* data, size_t size) : data_(data), size_(size) {}
1985
1986  string_ptr operator&() const noexcept { return {data_, size_}; }  // NOLINT
1987
1988  bool operator==(const char* s) const noexcept {
1989    if (size_ > 0 && data_[size_ - 1] != 0) {
1990      return std::string(data_, size_) == std::string(s);
1991    } else {
1992      return std::string(data_) == std::string(s);
1993    }
1994  }
1995
1996 private:
1997  const char* data_;
1998  size_t size_;
1999};
2000
2001string_ref string_ptr::operator*() const noexcept { return {data_, size_}; }
2002
2003TEST(string_ref, compare) {
2004  const char* s = "alex\0davidjohn\0";
2005  string_ptr ptr(s, 5);
2006  EXPECT_EQ(*ptr, "alex");
2007  EXPECT_TRUE(*ptr == "alex");
2008  ++ptr;
2009  EXPECT_EQ(*ptr, "david");
2010  EXPECT_TRUE(*ptr == "david");
2011  ++ptr;
2012  EXPECT_EQ(*ptr, "john");
2013}
2014
2015}  // namespace
2016
2017}  // namespace gtest_printers_test
2018}  // namespace testing
2019