Fix emulator build error
[platform/framework/web/chromium-efl.git] / base / functional / bind_unittest.cc
1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "base/functional/bind.h"
6
7 #include <functional>
8 #include <memory>
9 #include <string>
10 #include <utility>
11 #include <vector>
12
13 #include "base/allocator/partition_alloc_features.h"
14 #include "base/allocator/partition_alloc_support.h"
15 #include "base/allocator/partition_allocator/src/partition_alloc/dangling_raw_ptr_checks.h"
16 #include "base/allocator/partition_allocator/src/partition_alloc/partition_alloc_buildflags.h"
17 #include "base/allocator/partition_allocator/src/partition_alloc/partition_alloc_for_testing.h"
18 #include "base/allocator/partition_allocator/src/partition_alloc/partition_root.h"
19 #include "base/functional/callback.h"
20 #include "base/functional/disallow_unretained.h"
21 #include "base/memory/ptr_util.h"
22 #include "base/memory/raw_ptr.h"
23 #include "base/memory/raw_ref.h"
24 #include "base/memory/ref_counted.h"
25 #include "base/memory/weak_ptr.h"
26 #include "base/strings/string_number_conversions.h"
27 #include "base/test/bind.h"
28 #include "base/test/gtest_util.h"
29 #include "base/test/scoped_feature_list.h"
30 #include "build/build_config.h"
31 #include "testing/gmock/include/gmock/gmock.h"
32 #include "testing/gtest/include/gtest/gtest.h"
33
34 using ::testing::_;
35 using ::testing::AnyNumber;
36 using ::testing::ByMove;
37 using ::testing::Mock;
38 using ::testing::Return;
39 using ::testing::StrictMock;
40
41 namespace base {
42 namespace {
43
44 class AllowsUnretained {};
45
46 class BansUnretained {
47  public:
48   DISALLOW_UNRETAINED();
49 };
50
51 class BansUnretainedInPrivate {
52   DISALLOW_UNRETAINED();
53 };
54
55 class DerivedButBaseBansUnretained : public BansUnretained {};
56
57 static_assert(internal::TypeSupportsUnretainedV<AllowsUnretained>);
58 static_assert(!internal::TypeSupportsUnretainedV<BansUnretained>);
59 static_assert(!internal::TypeSupportsUnretainedV<BansUnretainedInPrivate>);
60 static_assert(!internal::TypeSupportsUnretainedV<DerivedButBaseBansUnretained>);
61
62 class NoRef {
63  public:
64   NoRef() = default;
65   NoRef(const NoRef&) = delete;
66   // Particularly important in this test to ensure no copies are made.
67   NoRef& operator=(const NoRef&) = delete;
68
69   MOCK_METHOD0(VoidMethod0, void());
70   MOCK_CONST_METHOD0(VoidConstMethod0, void());
71
72   MOCK_METHOD0(IntMethod0, int());
73   MOCK_CONST_METHOD0(IntConstMethod0, int());
74
75   MOCK_METHOD1(VoidMethodWithIntArg, void(int));
76   MOCK_METHOD0(UniquePtrMethod0, std::unique_ptr<int>());
77 };
78
79 class HasRef : public NoRef {
80  public:
81   HasRef() = default;
82   HasRef(const HasRef&) = delete;
83   // Particularly important in this test to ensure no copies are made.
84   HasRef& operator=(const HasRef&) = delete;
85
86   MOCK_CONST_METHOD0(AddRef, void());
87   MOCK_CONST_METHOD0(Release, bool());
88   MOCK_CONST_METHOD0(HasAtLeastOneRef, bool());
89 };
90
91 class HasRefPrivateDtor : public HasRef {
92  private:
93   ~HasRefPrivateDtor() = default;
94 };
95
96 static const int kParentValue = 1;
97 static const int kChildValue = 2;
98
99 class Parent {
100  public:
101   void AddRef() const {}
102   void Release() const {}
103   bool HasAtLeastOneRef() const { return true; }
104   virtual void VirtualSet() { value = kParentValue; }
105   void NonVirtualSet() { value = kParentValue; }
106   int value;
107 };
108
109 class Child : public Parent {
110  public:
111   void VirtualSet() override { value = kChildValue; }
112   void NonVirtualSet() { value = kChildValue; }
113 };
114
115 class NoRefParent {
116  public:
117   virtual void VirtualSet() { value = kParentValue; }
118   void NonVirtualSet() { value = kParentValue; }
119   int value;
120 };
121
122 class NoRefChild : public NoRefParent {
123   void VirtualSet() override { value = kChildValue; }
124   void NonVirtualSet() { value = kChildValue; }
125 };
126
127 // Used for probing the number of copies and moves that occur if a type must be
128 // coerced during argument forwarding in the Run() methods.
129 struct DerivedCopyMoveCounter {
130   DerivedCopyMoveCounter(int* copies,
131                          int* assigns,
132                          int* move_constructs,
133                          int* move_assigns)
134       : copies_(copies),
135         assigns_(assigns),
136         move_constructs_(move_constructs),
137         move_assigns_(move_assigns) {}
138   raw_ptr<int> copies_;
139   raw_ptr<int> assigns_;
140   raw_ptr<int> move_constructs_;
141   raw_ptr<int> move_assigns_;
142 };
143
144 // Used for probing the number of copies and moves in an argument.
145 class CopyMoveCounter {
146  public:
147   CopyMoveCounter(int* copies,
148                   int* assigns,
149                   int* move_constructs,
150                   int* move_assigns)
151       : copies_(copies),
152         assigns_(assigns),
153         move_constructs_(move_constructs),
154         move_assigns_(move_assigns) {}
155
156   CopyMoveCounter(const CopyMoveCounter& other)
157       : copies_(other.copies_),
158         assigns_(other.assigns_),
159         move_constructs_(other.move_constructs_),
160         move_assigns_(other.move_assigns_) {
161     (*copies_)++;
162   }
163
164   CopyMoveCounter(CopyMoveCounter&& other)
165       : copies_(other.copies_),
166         assigns_(other.assigns_),
167         move_constructs_(other.move_constructs_),
168         move_assigns_(other.move_assigns_) {
169     (*move_constructs_)++;
170   }
171
172   // Probing for copies from coercion.
173   explicit CopyMoveCounter(const DerivedCopyMoveCounter& other)
174       : copies_(other.copies_),
175         assigns_(other.assigns_),
176         move_constructs_(other.move_constructs_),
177         move_assigns_(other.move_assigns_) {
178     (*copies_)++;
179   }
180
181   // Probing for moves from coercion.
182   explicit CopyMoveCounter(DerivedCopyMoveCounter&& other)
183       : copies_(other.copies_),
184         assigns_(other.assigns_),
185         move_constructs_(other.move_constructs_),
186         move_assigns_(other.move_assigns_) {
187     (*move_constructs_)++;
188   }
189
190   const CopyMoveCounter& operator=(const CopyMoveCounter& rhs) {
191     copies_ = rhs.copies_;
192     assigns_ = rhs.assigns_;
193     move_constructs_ = rhs.move_constructs_;
194     move_assigns_ = rhs.move_assigns_;
195
196     (*assigns_)++;
197
198     return *this;
199   }
200
201   const CopyMoveCounter& operator=(CopyMoveCounter&& rhs) {
202     copies_ = rhs.copies_;
203     assigns_ = rhs.assigns_;
204     move_constructs_ = rhs.move_constructs_;
205     move_assigns_ = rhs.move_assigns_;
206
207     (*move_assigns_)++;
208
209     return *this;
210   }
211
212   int copies() const { return *copies_; }
213
214  private:
215   raw_ptr<int> copies_;
216   raw_ptr<int> assigns_;
217   raw_ptr<int> move_constructs_;
218   raw_ptr<int> move_assigns_;
219 };
220
221 // Used for probing the number of copies in an argument. The instance is a
222 // copyable and non-movable type.
223 class CopyCounter {
224  public:
225   CopyCounter(int* copies, int* assigns)
226       : counter_(copies, assigns, nullptr, nullptr) {}
227   CopyCounter(const CopyCounter& other) = default;
228   CopyCounter& operator=(const CopyCounter& other) = default;
229
230   explicit CopyCounter(const DerivedCopyMoveCounter& other) : counter_(other) {}
231
232   int copies() const { return counter_.copies(); }
233
234  private:
235   CopyMoveCounter counter_;
236 };
237
238 // Used for probing the number of moves in an argument. The instance is a
239 // non-copyable and movable type.
240 class MoveCounter {
241  public:
242   MoveCounter(int* move_constructs, int* move_assigns)
243       : counter_(nullptr, nullptr, move_constructs, move_assigns) {}
244   MoveCounter(MoveCounter&& other) : counter_(std::move(other.counter_)) {}
245   MoveCounter& operator=(MoveCounter&& other) {
246     counter_ = std::move(other.counter_);
247     return *this;
248   }
249
250   explicit MoveCounter(DerivedCopyMoveCounter&& other)
251       : counter_(std::move(other)) {}
252
253  private:
254   CopyMoveCounter counter_;
255 };
256
257 class DeleteCounter {
258  public:
259   explicit DeleteCounter(int* deletes) : deletes_(deletes) {}
260
261   ~DeleteCounter() { (*deletes_)++; }
262
263   void VoidMethod0() {}
264
265  private:
266   raw_ptr<int> deletes_;
267 };
268
269 template <typename T>
270 T PassThru(T scoper) {
271   return scoper;
272 }
273
274 // Some test functions that we can Bind to.
275 template <typename T>
276 T PolymorphicIdentity(T t) {
277   return t;
278 }
279
280 template <typename... Ts>
281 struct VoidPolymorphic {
282   static void Run(Ts... t) {}
283 };
284
285 int Identity(int n) {
286   return n;
287 }
288
289 int ArrayGet(const int array[], int n) {
290   return array[n];
291 }
292
293 int Sum(int a, int b, int c, int d, int e, int f) {
294   return a + b + c + d + e + f;
295 }
296
297 const char* CStringIdentity(const char* s) {
298   return s;
299 }
300
301 int GetCopies(const CopyMoveCounter& counter) {
302   return counter.copies();
303 }
304
305 int UnwrapNoRefParent(NoRefParent p) {
306   return p.value;
307 }
308
309 int UnwrapNoRefParentPtr(NoRefParent* p) {
310   return p->value;
311 }
312
313 int UnwrapNoRefParentConstRef(const NoRefParent& p) {
314   return p.value;
315 }
316
317 void RefArgSet(int& n) {
318   n = 2;
319 }
320
321 void PtrArgSet(int* n) {
322   *n = 2;
323 }
324
325 int FunctionWithWeakFirstParam(WeakPtr<NoRef> o, int n) {
326   return n;
327 }
328
329 int FunctionWithScopedRefptrFirstParam(const scoped_refptr<HasRef>& o, int n) {
330   return n;
331 }
332
333 void TakesACallback(const RepeatingClosure& callback) {
334   callback.Run();
335 }
336
337 int Noexcept() noexcept {
338   return 42;
339 }
340
341 class NoexceptFunctor {
342  public:
343   int operator()() noexcept { return 42; }
344 };
345
346 class ConstNoexceptFunctor {
347  public:
348   int operator()() noexcept { return 42; }
349 };
350
351 class BindTest : public ::testing::Test {
352  public:
353   BindTest() {
354     const_has_ref_ptr_ = &has_ref_;
355     const_no_ref_ptr_ = &no_ref_;
356     static_func_mock_ptr = &static_func_mock_;
357   }
358   BindTest(const BindTest&) = delete;
359   BindTest& operator=(const BindTest&) = delete;
360   ~BindTest() override = default;
361
362   static void VoidFunc0() { static_func_mock_ptr->VoidMethod0(); }
363
364   static int IntFunc0() { return static_func_mock_ptr->IntMethod0(); }
365   int NoexceptMethod() noexcept { return 42; }
366   int ConstNoexceptMethod() const noexcept { return 42; }
367
368  protected:
369   StrictMock<NoRef> no_ref_;
370   StrictMock<HasRef> has_ref_;
371   raw_ptr<const HasRef> const_has_ref_ptr_;
372   raw_ptr<const NoRef> const_no_ref_ptr_;
373   StrictMock<NoRef> static_func_mock_;
374
375   // Used by the static functions to perform expectations.
376   static StrictMock<NoRef>* static_func_mock_ptr;
377 };
378
379 StrictMock<NoRef>* BindTest::static_func_mock_ptr;
380 StrictMock<NoRef>* g_func_mock_ptr;
381
382 void VoidFunc0() {
383   g_func_mock_ptr->VoidMethod0();
384 }
385
386 int IntFunc0() {
387   return g_func_mock_ptr->IntMethod0();
388 }
389
390 TEST_F(BindTest, BasicTest) {
391   RepeatingCallback<int(int, int, int)> cb = BindRepeating(&Sum, 32, 16, 8);
392   EXPECT_EQ(92, cb.Run(13, 12, 11));
393
394   RepeatingCallback<int(int, int, int, int, int, int)> c1 = BindRepeating(&Sum);
395   EXPECT_EQ(69, c1.Run(14, 13, 12, 11, 10, 9));
396
397   RepeatingCallback<int(int, int, int)> c2 = BindRepeating(c1, 32, 16, 8);
398   EXPECT_EQ(86, c2.Run(11, 10, 9));
399
400   RepeatingCallback<int()> c3 = BindRepeating(c2, 4, 2, 1);
401   EXPECT_EQ(63, c3.Run());
402 }
403
404 // Test that currying the rvalue result of another BindRepeating() works
405 // correctly.
406 //   - rvalue should be usable as argument to BindRepeating().
407 //   - multiple runs of resulting RepeatingCallback remain valid.
408 TEST_F(BindTest, CurryingRvalueResultOfBind) {
409   int n = 0;
410   RepeatingClosure cb =
411       BindRepeating(&TakesACallback, BindRepeating(&PtrArgSet, &n));
412
413   // If we implement BindRepeating() such that the return value has
414   // auto_ptr-like semantics, the second call here will fail because ownership
415   // of the internal BindState<> would have been transferred to a *temporary*
416   // construction of a RepeatingCallback object on the first call.
417   cb.Run();
418   EXPECT_EQ(2, n);
419
420   n = 0;
421   cb.Run();
422   EXPECT_EQ(2, n);
423 }
424
425 TEST_F(BindTest, RepeatingCallbackBasicTest) {
426   RepeatingCallback<int(int)> c0 = BindRepeating(&Sum, 1, 2, 4, 8, 16);
427
428   // RepeatingCallback can run via a lvalue-reference.
429   EXPECT_EQ(63, c0.Run(32));
430
431   // It is valid to call a RepeatingCallback more than once.
432   EXPECT_EQ(54, c0.Run(23));
433
434   // BindRepeating can handle a RepeatingCallback as the target functor.
435   RepeatingCallback<int()> c1 = BindRepeating(c0, 11);
436
437   // RepeatingCallback can run via a rvalue-reference.
438   EXPECT_EQ(42, std::move(c1).Run());
439
440   // BindRepeating can handle a rvalue-reference of RepeatingCallback.
441   EXPECT_EQ(32, BindRepeating(std::move(c0), 1).Run());
442 }
443
444 TEST_F(BindTest, OnceCallbackBasicTest) {
445   OnceCallback<int(int)> c0 = BindOnce(&Sum, 1, 2, 4, 8, 16);
446
447   // OnceCallback can run via a rvalue-reference.
448   EXPECT_EQ(63, std::move(c0).Run(32));
449
450   // After running via the rvalue-reference, the value of the OnceCallback
451   // is undefined. The implementation simply clears the instance after the
452   // invocation.
453   EXPECT_TRUE(c0.is_null());
454
455   c0 = BindOnce(&Sum, 2, 3, 5, 7, 11);
456
457   // BindOnce can handle a rvalue-reference of OnceCallback as the target
458   // functor.
459   OnceCallback<int()> c1 = BindOnce(std::move(c0), 13);
460   EXPECT_EQ(41, std::move(c1).Run());
461
462   RepeatingCallback<int(int)> c2 = BindRepeating(&Sum, 2, 3, 5, 7, 11);
463   EXPECT_EQ(41, BindOnce(c2, 13).Run());
464 }
465
466 // IgnoreResult adapter test.
467 //   - Function with return value.
468 //   - Method with return value.
469 //   - Const Method with return.
470 //   - Method with return value bound to WeakPtr<>.
471 //   - Const Method with return bound to WeakPtr<>.
472 TEST_F(BindTest, IgnoreResultForRepeating) {
473   EXPECT_CALL(static_func_mock_, IntMethod0()).WillOnce(Return(1337));
474   EXPECT_CALL(has_ref_, AddRef()).Times(2);
475   EXPECT_CALL(has_ref_, Release()).Times(2);
476   EXPECT_CALL(has_ref_, HasAtLeastOneRef()).WillRepeatedly(Return(true));
477   EXPECT_CALL(has_ref_, IntMethod0()).WillOnce(Return(10));
478   EXPECT_CALL(has_ref_, IntConstMethod0()).WillOnce(Return(11));
479   EXPECT_CALL(no_ref_, IntMethod0()).WillOnce(Return(12));
480   EXPECT_CALL(no_ref_, IntConstMethod0()).WillOnce(Return(13));
481
482   RepeatingClosure normal_func_cb = BindRepeating(IgnoreResult(&IntFunc0));
483   normal_func_cb.Run();
484
485   RepeatingClosure non_void_method_cb =
486       BindRepeating(IgnoreResult(&HasRef::IntMethod0), &has_ref_);
487   non_void_method_cb.Run();
488
489   RepeatingClosure non_void_const_method_cb =
490       BindRepeating(IgnoreResult(&HasRef::IntConstMethod0), &has_ref_);
491   non_void_const_method_cb.Run();
492
493   WeakPtrFactory<NoRef> weak_factory(&no_ref_);
494   WeakPtrFactory<const NoRef> const_weak_factory(const_no_ref_ptr_.get());
495
496   RepeatingClosure non_void_weak_method_cb = BindRepeating(
497       IgnoreResult(&NoRef::IntMethod0), weak_factory.GetWeakPtr());
498   non_void_weak_method_cb.Run();
499
500   RepeatingClosure non_void_weak_const_method_cb = BindRepeating(
501       IgnoreResult(&NoRef::IntConstMethod0), weak_factory.GetWeakPtr());
502   non_void_weak_const_method_cb.Run();
503
504   weak_factory.InvalidateWeakPtrs();
505   non_void_weak_const_method_cb.Run();
506   non_void_weak_method_cb.Run();
507 }
508
509 TEST_F(BindTest, IgnoreResultForOnce) {
510   EXPECT_CALL(static_func_mock_, IntMethod0()).WillOnce(Return(1337));
511   EXPECT_CALL(has_ref_, AddRef()).Times(2);
512   EXPECT_CALL(has_ref_, Release()).Times(2);
513   EXPECT_CALL(has_ref_, HasAtLeastOneRef()).WillRepeatedly(Return(true));
514   EXPECT_CALL(has_ref_, IntMethod0()).WillOnce(Return(10));
515   EXPECT_CALL(has_ref_, IntConstMethod0()).WillOnce(Return(11));
516
517   OnceClosure normal_func_cb = BindOnce(IgnoreResult(&IntFunc0));
518   std::move(normal_func_cb).Run();
519
520   OnceClosure non_void_method_cb =
521       BindOnce(IgnoreResult(&HasRef::IntMethod0), &has_ref_);
522   std::move(non_void_method_cb).Run();
523
524   OnceClosure non_void_const_method_cb =
525       BindOnce(IgnoreResult(&HasRef::IntConstMethod0), &has_ref_);
526   std::move(non_void_const_method_cb).Run();
527
528   WeakPtrFactory<NoRef> weak_factory(&no_ref_);
529   WeakPtrFactory<const NoRef> const_weak_factory(const_no_ref_ptr_.get());
530
531   OnceClosure non_void_weak_method_cb =
532       BindOnce(IgnoreResult(&NoRef::IntMethod0), weak_factory.GetWeakPtr());
533   OnceClosure non_void_weak_const_method_cb = BindOnce(
534       IgnoreResult(&NoRef::IntConstMethod0), weak_factory.GetWeakPtr());
535
536   weak_factory.InvalidateWeakPtrs();
537   std::move(non_void_weak_const_method_cb).Run();
538   std::move(non_void_weak_method_cb).Run();
539 }
540
541 TEST_F(BindTest, IgnoreResultForRepeatingCallback) {
542   std::string s;
543   RepeatingCallback<int(int)> cb = BindRepeating(
544       [](std::string* s, int i) {
545         *s += "Run" + base::NumberToString(i);
546         return 5;
547       },
548       &s);
549   RepeatingCallback<void(int)> noreturn = BindRepeating(IgnoreResult(cb));
550   noreturn.Run(2);
551   EXPECT_EQ(s, "Run2");
552 }
553
554 TEST_F(BindTest, IgnoreResultForOnceCallback) {
555   std::string s;
556   OnceCallback<int(int)> cb = BindOnce(
557       [](std::string* s, int i) {
558         *s += "Run" + base::NumberToString(i);
559         return 5;
560       },
561       &s);
562   OnceCallback<void(int)> noreturn = BindOnce(IgnoreResult(std::move(cb)));
563   std::move(noreturn).Run(2);
564   EXPECT_EQ(s, "Run2");
565 }
566
567 void SetFromRef(int& ref) {
568   EXPECT_EQ(ref, 1);
569   ref = 2;
570   EXPECT_EQ(ref, 2);
571 }
572
573 TEST_F(BindTest, BindOnceWithNonConstRef) {
574   int v = 1;
575
576   // Mutates `v` because it's not bound to callback instead it's forwarded by
577   // Run().
578   auto cb1 = BindOnce(SetFromRef);
579   std::move(cb1).Run(v);
580   EXPECT_EQ(v, 2);
581   v = 1;
582
583   // Mutates `v` through std::reference_wrapper bound to callback.
584   auto cb2 = BindOnce(SetFromRef, std::ref(v));
585   std::move(cb2).Run();
586   EXPECT_EQ(v, 2);
587   v = 1;
588
589   // Everything past here following will make a copy of the argument. The copy
590   // will be mutated and leave `v` unmodified.
591   auto cb3 = BindOnce(SetFromRef, base::OwnedRef(v));
592   std::move(cb3).Run();
593   EXPECT_EQ(v, 1);
594
595   int& ref = v;
596   auto cb4 = BindOnce(SetFromRef, base::OwnedRef(ref));
597   std::move(cb4).Run();
598   EXPECT_EQ(v, 1);
599
600   const int cv = 1;
601   auto cb5 = BindOnce(SetFromRef, base::OwnedRef(cv));
602   std::move(cb5).Run();
603   EXPECT_EQ(cv, 1);
604
605   const int& cref = v;
606   auto cb6 = BindOnce(SetFromRef, base::OwnedRef(cref));
607   std::move(cb6).Run();
608   EXPECT_EQ(cref, 1);
609
610   auto cb7 = BindOnce(SetFromRef, base::OwnedRef(1));
611   std::move(cb7).Run();
612 }
613
614 TEST_F(BindTest, BindRepeatingWithNonConstRef) {
615   int v = 1;
616
617   // Mutates `v` because it's not bound to callback instead it's forwarded by
618   // Run().
619   auto cb1 = BindRepeating(SetFromRef);
620   std::move(cb1).Run(v);
621   EXPECT_EQ(v, 2);
622   v = 1;
623
624   // Mutates `v` through std::reference_wrapper bound to callback.
625   auto cb2 = BindRepeating(SetFromRef, std::ref(v));
626   std::move(cb2).Run();
627   EXPECT_EQ(v, 2);
628   v = 1;
629
630   // Everything past here following will make a copy of the argument. The copy
631   // will be mutated and leave `v` unmodified.
632   auto cb3 = BindRepeating(SetFromRef, base::OwnedRef(v));
633   std::move(cb3).Run();
634   EXPECT_EQ(v, 1);
635
636   int& ref = v;
637   auto cb4 = BindRepeating(SetFromRef, base::OwnedRef(ref));
638   std::move(cb4).Run();
639   EXPECT_EQ(v, 1);
640
641   const int cv = 1;
642   auto cb5 = BindRepeating(SetFromRef, base::OwnedRef(cv));
643   std::move(cb5).Run();
644   EXPECT_EQ(cv, 1);
645
646   const int& cref = v;
647   auto cb6 = BindRepeating(SetFromRef, base::OwnedRef(cref));
648   std::move(cb6).Run();
649   EXPECT_EQ(cref, 1);
650
651   auto cb7 = BindRepeating(SetFromRef, base::OwnedRef(1));
652   std::move(cb7).Run();
653 }
654
655 // Functions that take reference parameters.
656 //  - Forced reference parameter type still stores a copy.
657 //  - Forced const reference parameter type still stores a copy.
658 TEST_F(BindTest, ReferenceArgumentBindingForRepeating) {
659   int n = 1;
660   int& ref_n = n;
661   const int& const_ref_n = n;
662
663   RepeatingCallback<int()> ref_copies_cb = BindRepeating(&Identity, ref_n);
664   EXPECT_EQ(n, ref_copies_cb.Run());
665   n++;
666   EXPECT_EQ(n - 1, ref_copies_cb.Run());
667
668   RepeatingCallback<int()> const_ref_copies_cb =
669       BindRepeating(&Identity, const_ref_n);
670   EXPECT_EQ(n, const_ref_copies_cb.Run());
671   n++;
672   EXPECT_EQ(n - 1, const_ref_copies_cb.Run());
673 }
674
675 TEST_F(BindTest, ReferenceArgumentBindingForOnce) {
676   int n = 1;
677   int& ref_n = n;
678   const int& const_ref_n = n;
679
680   OnceCallback<int()> ref_copies_cb = BindOnce(&Identity, ref_n);
681   n++;
682   EXPECT_EQ(n - 1, std::move(ref_copies_cb).Run());
683
684   OnceCallback<int()> const_ref_copies_cb = BindOnce(&Identity, const_ref_n);
685   n++;
686   EXPECT_EQ(n - 1, std::move(const_ref_copies_cb).Run());
687 }
688
689 // Check that we can pass in arrays and have them be stored as a pointer.
690 //  - Array of values stores a pointer.
691 //  - Array of const values stores a pointer.
692 TEST_F(BindTest, ArrayArgumentBindingForRepeating) {
693   int array[4] = {1, 1, 1, 1};
694   const int(*const_array_ptr)[4] = &array;
695
696   RepeatingCallback<int()> array_cb = BindRepeating(&ArrayGet, array, 1);
697   EXPECT_EQ(1, array_cb.Run());
698
699   RepeatingCallback<int()> const_array_cb =
700       BindRepeating(&ArrayGet, *const_array_ptr, 1);
701   EXPECT_EQ(1, const_array_cb.Run());
702
703   array[1] = 3;
704   EXPECT_EQ(3, array_cb.Run());
705   EXPECT_EQ(3, const_array_cb.Run());
706 }
707
708 TEST_F(BindTest, ArrayArgumentBindingForOnce) {
709   int array[4] = {1, 1, 1, 1};
710   const int(*const_array_ptr)[4] = &array;
711
712   OnceCallback<int()> array_cb = BindOnce(&ArrayGet, array, 1);
713   OnceCallback<int()> const_array_cb = BindOnce(&ArrayGet, *const_array_ptr, 1);
714
715   array[1] = 3;
716   EXPECT_EQ(3, std::move(array_cb).Run());
717   EXPECT_EQ(3, std::move(const_array_cb).Run());
718 }
719
720 // WeakPtr() support.
721 //   - Method bound to WeakPtr<> to non-const object.
722 //   - Const method bound to WeakPtr<> to non-const object.
723 //   - Const method bound to WeakPtr<> to const object.
724 //   - Normal Function with WeakPtr<> as P1 can have return type and is
725 //     not canceled.
726 TEST_F(BindTest, WeakPtrForRepeating) {
727   EXPECT_CALL(no_ref_, VoidMethod0());
728   EXPECT_CALL(no_ref_, VoidConstMethod0()).Times(2);
729
730   WeakPtrFactory<NoRef> weak_factory(&no_ref_);
731   WeakPtrFactory<const NoRef> const_weak_factory(const_no_ref_ptr_.get());
732
733   RepeatingClosure method_cb =
734       BindRepeating(&NoRef::VoidMethod0, weak_factory.GetWeakPtr());
735   method_cb.Run();
736
737   RepeatingClosure const_method_cb =
738       BindRepeating(&NoRef::VoidConstMethod0, const_weak_factory.GetWeakPtr());
739   const_method_cb.Run();
740
741   RepeatingClosure const_method_const_ptr_cb =
742       BindRepeating(&NoRef::VoidConstMethod0, const_weak_factory.GetWeakPtr());
743   const_method_const_ptr_cb.Run();
744
745   RepeatingCallback<int(int)> normal_func_cb =
746       BindRepeating(&FunctionWithWeakFirstParam, weak_factory.GetWeakPtr());
747   EXPECT_EQ(1, normal_func_cb.Run(1));
748
749   weak_factory.InvalidateWeakPtrs();
750   const_weak_factory.InvalidateWeakPtrs();
751
752   method_cb.Run();
753   const_method_cb.Run();
754   const_method_const_ptr_cb.Run();
755
756   // Still runs even after the pointers are invalidated.
757   EXPECT_EQ(2, normal_func_cb.Run(2));
758 }
759
760 TEST_F(BindTest, WeakPtrForOnce) {
761   WeakPtrFactory<NoRef> weak_factory(&no_ref_);
762   WeakPtrFactory<const NoRef> const_weak_factory(const_no_ref_ptr_.get());
763
764   OnceClosure method_cb =
765       BindOnce(&NoRef::VoidMethod0, weak_factory.GetWeakPtr());
766   OnceClosure const_method_cb =
767       BindOnce(&NoRef::VoidConstMethod0, const_weak_factory.GetWeakPtr());
768   OnceClosure const_method_const_ptr_cb =
769       BindOnce(&NoRef::VoidConstMethod0, const_weak_factory.GetWeakPtr());
770   OnceCallback<int(int)> normal_func_cb =
771       BindOnce(&FunctionWithWeakFirstParam, weak_factory.GetWeakPtr());
772
773   weak_factory.InvalidateWeakPtrs();
774   const_weak_factory.InvalidateWeakPtrs();
775
776   std::move(method_cb).Run();
777   std::move(const_method_cb).Run();
778   std::move(const_method_const_ptr_cb).Run();
779
780   // Still runs even after the pointers are invalidated.
781   EXPECT_EQ(2, std::move(normal_func_cb).Run(2));
782 }
783
784 // std::cref() wrapper support.
785 //   - Binding w/o std::cref takes a copy.
786 //   - Binding a std::cref takes a reference.
787 //   - Binding std::cref to a function std::cref does not copy on invoke.
788 TEST_F(BindTest, StdCrefForRepeating) {
789   int n = 1;
790
791   RepeatingCallback<int()> copy_cb = BindRepeating(&Identity, n);
792   RepeatingCallback<int()> const_ref_cb =
793       BindRepeating(&Identity, std::cref(n));
794   EXPECT_EQ(n, copy_cb.Run());
795   EXPECT_EQ(n, const_ref_cb.Run());
796   n++;
797   EXPECT_EQ(n - 1, copy_cb.Run());
798   EXPECT_EQ(n, const_ref_cb.Run());
799
800   int copies = 0;
801   int assigns = 0;
802   int move_constructs = 0;
803   int move_assigns = 0;
804   CopyMoveCounter counter(&copies, &assigns, &move_constructs, &move_assigns);
805   RepeatingCallback<int()> all_const_ref_cb =
806       BindRepeating(&GetCopies, std::cref(counter));
807   EXPECT_EQ(0, all_const_ref_cb.Run());
808   EXPECT_EQ(0, copies);
809   EXPECT_EQ(0, assigns);
810   EXPECT_EQ(0, move_constructs);
811   EXPECT_EQ(0, move_assigns);
812 }
813
814 TEST_F(BindTest, StdCrefForOnce) {
815   int n = 1;
816
817   OnceCallback<int()> copy_cb = BindOnce(&Identity, n);
818   OnceCallback<int()> const_ref_cb = BindOnce(&Identity, std::cref(n));
819   n++;
820   EXPECT_EQ(n - 1, std::move(copy_cb).Run());
821   EXPECT_EQ(n, std::move(const_ref_cb).Run());
822
823   int copies = 0;
824   int assigns = 0;
825   int move_constructs = 0;
826   int move_assigns = 0;
827   CopyMoveCounter counter(&copies, &assigns, &move_constructs, &move_assigns);
828   OnceCallback<int()> all_const_ref_cb =
829       BindOnce(&GetCopies, std::cref(counter));
830   EXPECT_EQ(0, std::move(all_const_ref_cb).Run());
831   EXPECT_EQ(0, copies);
832   EXPECT_EQ(0, assigns);
833   EXPECT_EQ(0, move_constructs);
834   EXPECT_EQ(0, move_assigns);
835 }
836
837 // Test Owned() support.
838 TEST_F(BindTest, OwnedForRepeatingRawPtr) {
839   int deletes = 0;
840   DeleteCounter* counter = new DeleteCounter(&deletes);
841
842   // If we don't capture, delete happens on Callback destruction/reset.
843   // return the same value.
844   RepeatingCallback<DeleteCounter*()> no_capture_cb =
845       BindRepeating(&PolymorphicIdentity<DeleteCounter*>, Owned(counter));
846   ASSERT_EQ(counter, no_capture_cb.Run());
847   ASSERT_EQ(counter, no_capture_cb.Run());
848   EXPECT_EQ(0, deletes);
849   no_capture_cb.Reset();  // This should trigger a delete.
850   EXPECT_EQ(1, deletes);
851
852   deletes = 0;
853   counter = new DeleteCounter(&deletes);
854   RepeatingClosure own_object_cb =
855       BindRepeating(&DeleteCounter::VoidMethod0, Owned(counter));
856   own_object_cb.Run();
857   EXPECT_EQ(0, deletes);
858   own_object_cb.Reset();
859   EXPECT_EQ(1, deletes);
860 }
861
862 TEST_F(BindTest, OwnedForOnceRawPtr) {
863   int deletes = 0;
864   DeleteCounter* counter = new DeleteCounter(&deletes);
865
866   // If we don't capture, delete happens on Callback destruction/reset.
867   // return the same value.
868   OnceCallback<DeleteCounter*()> no_capture_cb =
869       BindOnce(&PolymorphicIdentity<DeleteCounter*>, Owned(counter));
870   EXPECT_EQ(0, deletes);
871   no_capture_cb.Reset();  // This should trigger a delete.
872   EXPECT_EQ(1, deletes);
873
874   deletes = 0;
875   counter = new DeleteCounter(&deletes);
876   OnceClosure own_object_cb =
877       BindOnce(&DeleteCounter::VoidMethod0, Owned(counter));
878   EXPECT_EQ(0, deletes);
879   own_object_cb.Reset();
880   EXPECT_EQ(1, deletes);
881 }
882
883 TEST_F(BindTest, OwnedForRepeatingUniquePtr) {
884   int deletes = 0;
885   auto counter = std::make_unique<DeleteCounter>(&deletes);
886   DeleteCounter* raw_counter = counter.get();
887
888   // If we don't capture, delete happens on Callback destruction/reset.
889   // return the same value.
890   RepeatingCallback<DeleteCounter*()> no_capture_cb = BindRepeating(
891       &PolymorphicIdentity<DeleteCounter*>, Owned(std::move(counter)));
892   ASSERT_EQ(raw_counter, no_capture_cb.Run());
893   ASSERT_EQ(raw_counter, no_capture_cb.Run());
894   EXPECT_EQ(0, deletes);
895   no_capture_cb.Reset();  // This should trigger a delete.
896   EXPECT_EQ(1, deletes);
897
898   deletes = 0;
899   counter = std::make_unique<DeleteCounter>(&deletes);
900   RepeatingClosure own_object_cb =
901       BindRepeating(&DeleteCounter::VoidMethod0, Owned(std::move(counter)));
902   own_object_cb.Run();
903   EXPECT_EQ(0, deletes);
904   own_object_cb.Reset();
905   EXPECT_EQ(1, deletes);
906 }
907
908 TEST_F(BindTest, OwnedForOnceUniquePtr) {
909   int deletes = 0;
910   auto counter = std::make_unique<DeleteCounter>(&deletes);
911
912   // If we don't capture, delete happens on Callback destruction/reset.
913   // return the same value.
914   OnceCallback<DeleteCounter*()> no_capture_cb =
915       BindOnce(&PolymorphicIdentity<DeleteCounter*>, Owned(std::move(counter)));
916   EXPECT_EQ(0, deletes);
917   no_capture_cb.Reset();  // This should trigger a delete.
918   EXPECT_EQ(1, deletes);
919
920   deletes = 0;
921   counter = std::make_unique<DeleteCounter>(&deletes);
922   OnceClosure own_object_cb =
923       BindOnce(&DeleteCounter::VoidMethod0, Owned(std::move(counter)));
924   EXPECT_EQ(0, deletes);
925   own_object_cb.Reset();
926   EXPECT_EQ(1, deletes);
927 }
928
929 // Tests OwnedRef
930 TEST_F(BindTest, OwnedRefForCounter) {
931   int counter = 0;
932   RepeatingCallback<int()> counter_callback =
933       BindRepeating([](int& counter) { return ++counter; }, OwnedRef(counter));
934
935   EXPECT_EQ(1, counter_callback.Run());
936   EXPECT_EQ(2, counter_callback.Run());
937   EXPECT_EQ(3, counter_callback.Run());
938   EXPECT_EQ(4, counter_callback.Run());
939
940   EXPECT_EQ(0, counter);  // counter should remain unchanged.
941 }
942
943 TEST_F(BindTest, OwnedRefForIgnoringArguments) {
944   OnceCallback<std::string(std::string)> echo_callback =
945       BindOnce([](int& ignore, std::string s) { return s; }, OwnedRef(0));
946
947   EXPECT_EQ("Hello World", std::move(echo_callback).Run("Hello World"));
948 }
949
950 template <typename T>
951 class BindVariantsTest : public ::testing::Test {};
952
953 struct RepeatingTestConfig {
954   template <typename Signature>
955   using CallbackType = RepeatingCallback<Signature>;
956   using ClosureType = RepeatingClosure;
957
958   template <typename F, typename... Args>
959   static CallbackType<internal::MakeUnboundRunType<F, Args...>> Bind(
960       F&& f,
961       Args&&... args) {
962     return BindRepeating(std::forward<F>(f), std::forward<Args>(args)...);
963   }
964 };
965
966 struct OnceTestConfig {
967   template <typename Signature>
968   using CallbackType = OnceCallback<Signature>;
969   using ClosureType = OnceClosure;
970
971   template <typename F, typename... Args>
972   static CallbackType<internal::MakeUnboundRunType<F, Args...>> Bind(
973       F&& f,
974       Args&&... args) {
975     return BindOnce(std::forward<F>(f), std::forward<Args>(args)...);
976   }
977 };
978
979 using BindVariantsTestConfig =
980     ::testing::Types<RepeatingTestConfig, OnceTestConfig>;
981 TYPED_TEST_SUITE(BindVariantsTest, BindVariantsTestConfig);
982
983 template <typename TypeParam, typename Signature>
984 using CallbackType = typename TypeParam::template CallbackType<Signature>;
985
986 // Function type support.
987 //   - Normal function.
988 //   - Normal function bound with non-refcounted first argument.
989 //   - Method bound to non-const object.
990 //   - Method bound to scoped_refptr.
991 //   - Const method bound to non-const object.
992 //   - Const method bound to const object.
993 //   - Derived classes can be used with pointers to non-virtual base functions.
994 //   - Derived classes can be used with pointers to virtual base functions (and
995 //     preserve virtual dispatch).
996 TYPED_TEST(BindVariantsTest, FunctionTypeSupport) {
997   using ClosureType = typename TypeParam::ClosureType;
998
999   StrictMock<HasRef> has_ref;
1000   StrictMock<NoRef> no_ref;
1001   StrictMock<NoRef> static_func_mock;
1002   const HasRef* const_has_ref_ptr = &has_ref;
1003   g_func_mock_ptr = &static_func_mock;
1004
1005   EXPECT_CALL(static_func_mock, VoidMethod0());
1006   EXPECT_CALL(has_ref, AddRef()).Times(4);
1007   EXPECT_CALL(has_ref, Release()).Times(4);
1008   EXPECT_CALL(has_ref, HasAtLeastOneRef()).WillRepeatedly(Return(true));
1009   EXPECT_CALL(has_ref, VoidMethod0()).Times(2);
1010   EXPECT_CALL(has_ref, VoidConstMethod0()).Times(2);
1011
1012   ClosureType normal_cb = TypeParam::Bind(&VoidFunc0);
1013   CallbackType<TypeParam, NoRef*()> normal_non_refcounted_cb =
1014       TypeParam::Bind(&PolymorphicIdentity<NoRef*>, &no_ref);
1015   std::move(normal_cb).Run();
1016   EXPECT_EQ(&no_ref, std::move(normal_non_refcounted_cb).Run());
1017
1018   ClosureType method_cb = TypeParam::Bind(&HasRef::VoidMethod0, &has_ref);
1019   ClosureType method_refptr_cb =
1020       TypeParam::Bind(&HasRef::VoidMethod0, WrapRefCounted(&has_ref));
1021   ClosureType const_method_nonconst_obj_cb =
1022       TypeParam::Bind(&HasRef::VoidConstMethod0, &has_ref);
1023   ClosureType const_method_const_obj_cb =
1024       TypeParam::Bind(&HasRef::VoidConstMethod0, const_has_ref_ptr);
1025   std::move(method_cb).Run();
1026   std::move(method_refptr_cb).Run();
1027   std::move(const_method_nonconst_obj_cb).Run();
1028   std::move(const_method_const_obj_cb).Run();
1029
1030   Child child;
1031   child.value = 0;
1032   ClosureType virtual_set_cb = TypeParam::Bind(&Parent::VirtualSet, &child);
1033   std::move(virtual_set_cb).Run();
1034   EXPECT_EQ(kChildValue, child.value);
1035
1036   child.value = 0;
1037   ClosureType non_virtual_set_cb =
1038       TypeParam::Bind(&Parent::NonVirtualSet, &child);
1039   std::move(non_virtual_set_cb).Run();
1040   EXPECT_EQ(kParentValue, child.value);
1041 }
1042
1043 // Return value support.
1044 //   - Function with return value.
1045 //   - Method with return value.
1046 //   - Const method with return value.
1047 //   - Move-only return value.
1048 TYPED_TEST(BindVariantsTest, ReturnValues) {
1049   StrictMock<NoRef> static_func_mock;
1050   StrictMock<HasRef> has_ref;
1051   g_func_mock_ptr = &static_func_mock;
1052   const HasRef* const_has_ref_ptr = &has_ref;
1053
1054   EXPECT_CALL(static_func_mock, IntMethod0()).WillOnce(Return(1337));
1055   EXPECT_CALL(has_ref, AddRef()).Times(4);
1056   EXPECT_CALL(has_ref, Release()).Times(4);
1057   EXPECT_CALL(has_ref, HasAtLeastOneRef()).WillRepeatedly(Return(true));
1058   EXPECT_CALL(has_ref, IntMethod0()).WillOnce(Return(31337));
1059   EXPECT_CALL(has_ref, IntConstMethod0())
1060       .WillOnce(Return(41337))
1061       .WillOnce(Return(51337));
1062   EXPECT_CALL(has_ref, UniquePtrMethod0())
1063       .WillOnce(Return(ByMove(std::make_unique<int>(42))));
1064
1065   CallbackType<TypeParam, int()> normal_cb = TypeParam::Bind(&IntFunc0);
1066   CallbackType<TypeParam, int()> method_cb =
1067       TypeParam::Bind(&HasRef::IntMethod0, &has_ref);
1068   CallbackType<TypeParam, int()> const_method_nonconst_obj_cb =
1069       TypeParam::Bind(&HasRef::IntConstMethod0, &has_ref);
1070   CallbackType<TypeParam, int()> const_method_const_obj_cb =
1071       TypeParam::Bind(&HasRef::IntConstMethod0, const_has_ref_ptr);
1072   CallbackType<TypeParam, std::unique_ptr<int>()> move_only_rv_cb =
1073       TypeParam::Bind(&HasRef::UniquePtrMethod0, &has_ref);
1074   EXPECT_EQ(1337, std::move(normal_cb).Run());
1075   EXPECT_EQ(31337, std::move(method_cb).Run());
1076   EXPECT_EQ(41337, std::move(const_method_nonconst_obj_cb).Run());
1077   EXPECT_EQ(51337, std::move(const_method_const_obj_cb).Run());
1078   EXPECT_EQ(42, *std::move(move_only_rv_cb).Run());
1079 }
1080
1081 // Argument binding tests.
1082 //   - Argument binding to primitive.
1083 //   - Argument binding to primitive pointer.
1084 //   - Argument binding to a literal integer.
1085 //   - Argument binding to a literal string.
1086 //   - Argument binding with template function.
1087 //   - Argument binding to an object.
1088 //   - Argument binding to pointer to incomplete type.
1089 //   - Argument gets type converted.
1090 //   - Pointer argument gets converted.
1091 //   - Const Reference forces conversion.
1092 TYPED_TEST(BindVariantsTest, ArgumentBinding) {
1093   int n = 2;
1094
1095   EXPECT_EQ(n, TypeParam::Bind(&Identity, n).Run());
1096   EXPECT_EQ(&n, TypeParam::Bind(&PolymorphicIdentity<int*>, &n).Run());
1097   EXPECT_EQ(3, TypeParam::Bind(&Identity, 3).Run());
1098   EXPECT_STREQ("hi", TypeParam::Bind(&CStringIdentity, "hi").Run());
1099   EXPECT_EQ(4, TypeParam::Bind(&PolymorphicIdentity<int>, 4).Run());
1100
1101   NoRefParent p;
1102   p.value = 5;
1103   EXPECT_EQ(5, TypeParam::Bind(&UnwrapNoRefParent, p).Run());
1104
1105   NoRefChild c;
1106   c.value = 6;
1107   EXPECT_EQ(6, TypeParam::Bind(&UnwrapNoRefParent, c).Run());
1108
1109   c.value = 7;
1110   EXPECT_EQ(7, TypeParam::Bind(&UnwrapNoRefParentPtr, &c).Run());
1111
1112   c.value = 8;
1113   EXPECT_EQ(8, TypeParam::Bind(&UnwrapNoRefParentConstRef, c).Run());
1114 }
1115
1116 // Unbound argument type support tests.
1117 //   - Unbound value.
1118 //   - Unbound pointer.
1119 //   - Unbound reference.
1120 //   - Unbound const reference.
1121 //   - Unbound unsized array.
1122 //   - Unbound sized array.
1123 //   - Unbound array-of-arrays.
1124 TYPED_TEST(BindVariantsTest, UnboundArgumentTypeSupport) {
1125   CallbackType<TypeParam, void(int)> unbound_value_cb =
1126       TypeParam::Bind(&VoidPolymorphic<int>::Run);
1127   CallbackType<TypeParam, void(int*)> unbound_pointer_cb =
1128       TypeParam::Bind(&VoidPolymorphic<int*>::Run);
1129   CallbackType<TypeParam, void(int&)> unbound_ref_cb =
1130       TypeParam::Bind(&VoidPolymorphic<int&>::Run);
1131   CallbackType<TypeParam, void(const int&)> unbound_const_ref_cb =
1132       TypeParam::Bind(&VoidPolymorphic<const int&>::Run);
1133   CallbackType<TypeParam, void(int[])> unbound_unsized_array_cb =
1134       TypeParam::Bind(&VoidPolymorphic<int[]>::Run);
1135   CallbackType<TypeParam, void(int[2])> unbound_sized_array_cb =
1136       TypeParam::Bind(&VoidPolymorphic<int[2]>::Run);
1137   CallbackType<TypeParam, void(int[][2])> unbound_array_of_arrays_cb =
1138       TypeParam::Bind(&VoidPolymorphic<int[][2]>::Run);
1139   CallbackType<TypeParam, void(int&)> unbound_ref_with_bound_arg =
1140       TypeParam::Bind(&VoidPolymorphic<int, int&>::Run, 1);
1141 }
1142
1143 // Function with unbound reference parameter.
1144 //   - Original parameter is modified by callback.
1145 TYPED_TEST(BindVariantsTest, UnboundReferenceSupport) {
1146   int n = 0;
1147   CallbackType<TypeParam, void(int&)> unbound_ref_cb =
1148       TypeParam::Bind(&RefArgSet);
1149   std::move(unbound_ref_cb).Run(n);
1150   EXPECT_EQ(2, n);
1151 }
1152
1153 // Unretained() wrapper support.
1154 //   - Method bound to Unretained() non-const object.
1155 //   - Const method bound to Unretained() non-const object.
1156 //   - Const method bound to Unretained() const object.
1157 TYPED_TEST(BindVariantsTest, Unretained) {
1158   StrictMock<NoRef> no_ref;
1159   const NoRef* const_no_ref_ptr = &no_ref;
1160
1161   EXPECT_CALL(no_ref, VoidMethod0());
1162   EXPECT_CALL(no_ref, VoidConstMethod0()).Times(2);
1163
1164   TypeParam::Bind(&NoRef::VoidMethod0, Unretained(&no_ref)).Run();
1165   TypeParam::Bind(&NoRef::VoidConstMethod0, Unretained(&no_ref)).Run();
1166   TypeParam::Bind(&NoRef::VoidConstMethod0, Unretained(const_no_ref_ptr)).Run();
1167 }
1168
1169 TYPED_TEST(BindVariantsTest, ScopedRefptr) {
1170   StrictMock<HasRef> has_ref;
1171   EXPECT_CALL(has_ref, AddRef()).Times(1);
1172   EXPECT_CALL(has_ref, Release()).Times(1);
1173   EXPECT_CALL(has_ref, HasAtLeastOneRef()).WillRepeatedly(Return(true));
1174
1175   const scoped_refptr<HasRef> refptr(&has_ref);
1176   CallbackType<TypeParam, int()> scoped_refptr_const_ref_cb = TypeParam::Bind(
1177       &FunctionWithScopedRefptrFirstParam, std::cref(refptr), 1);
1178   EXPECT_EQ(1, std::move(scoped_refptr_const_ref_cb).Run());
1179 }
1180
1181 TYPED_TEST(BindVariantsTest, UniquePtrReceiver) {
1182   std::unique_ptr<StrictMock<NoRef>> no_ref(new StrictMock<NoRef>);
1183   EXPECT_CALL(*no_ref, VoidMethod0()).Times(1);
1184   TypeParam::Bind(&NoRef::VoidMethod0, std::move(no_ref)).Run();
1185 }
1186
1187 TYPED_TEST(BindVariantsTest, ImplicitRefPtrReceiver) {
1188   StrictMock<HasRef> has_ref;
1189   EXPECT_CALL(has_ref, AddRef()).Times(1);
1190   EXPECT_CALL(has_ref, Release()).Times(1);
1191   EXPECT_CALL(has_ref, HasAtLeastOneRef()).WillRepeatedly(Return(true));
1192
1193   HasRef* ptr = &has_ref;
1194   auto ptr_cb = TypeParam::Bind(&HasRef::HasAtLeastOneRef, ptr);
1195   EXPECT_EQ(1, std::move(ptr_cb).Run());
1196 }
1197
1198 TYPED_TEST(BindVariantsTest, RawPtrReceiver) {
1199   StrictMock<HasRef> has_ref;
1200   EXPECT_CALL(has_ref, AddRef()).Times(1);
1201   EXPECT_CALL(has_ref, Release()).Times(1);
1202   EXPECT_CALL(has_ref, HasAtLeastOneRef()).WillRepeatedly(Return(true));
1203
1204   raw_ptr<HasRef> rawptr(&has_ref);
1205   auto rawptr_cb = TypeParam::Bind(&HasRef::HasAtLeastOneRef, rawptr);
1206   EXPECT_EQ(1, std::move(rawptr_cb).Run());
1207 }
1208
1209 TYPED_TEST(BindVariantsTest, UnretainedRawRefReceiver) {
1210   StrictMock<HasRef> has_ref;
1211   EXPECT_CALL(has_ref, AddRef()).Times(0);
1212   EXPECT_CALL(has_ref, Release()).Times(0);
1213   EXPECT_CALL(has_ref, HasAtLeastOneRef()).WillRepeatedly(Return(true));
1214
1215   raw_ref<HasRef> raw_has_ref(has_ref);
1216   auto has_ref_cb =
1217       TypeParam::Bind(&HasRef::HasAtLeastOneRef, Unretained(raw_has_ref));
1218   EXPECT_EQ(1, std::move(has_ref_cb).Run());
1219
1220   StrictMock<NoRef> no_ref;
1221   EXPECT_CALL(has_ref, IntMethod0()).WillRepeatedly(Return(1));
1222
1223   raw_ref<NoRef> raw_no_ref(has_ref);
1224   auto no_ref_cb = TypeParam::Bind(&NoRef::IntMethod0, Unretained(raw_no_ref));
1225   EXPECT_EQ(1, std::move(no_ref_cb).Run());
1226 }
1227
1228 // Tests for Passed() wrapper support:
1229 //   - Passed() can be constructed from a pointer to scoper.
1230 //   - Passed() can be constructed from a scoper rvalue.
1231 //   - Using Passed() gives Callback Ownership.
1232 //   - Ownership is transferred from Callback to callee on the first Run().
1233 //   - Callback supports unbound arguments.
1234 template <typename T>
1235 class BindMoveOnlyTypeTest : public ::testing::Test {};
1236
1237 struct CustomDeleter {
1238   void operator()(DeleteCounter* c) { delete c; }
1239 };
1240
1241 using MoveOnlyTypesToTest =
1242     ::testing::Types<std::unique_ptr<DeleteCounter>,
1243                      std::unique_ptr<DeleteCounter, CustomDeleter>>;
1244 TYPED_TEST_SUITE(BindMoveOnlyTypeTest, MoveOnlyTypesToTest);
1245
1246 TYPED_TEST(BindMoveOnlyTypeTest, PassedToBoundCallback) {
1247   int deletes = 0;
1248
1249   TypeParam ptr(new DeleteCounter(&deletes));
1250   RepeatingCallback<TypeParam()> callback =
1251       BindRepeating(&PassThru<TypeParam>, Passed(&ptr));
1252   EXPECT_FALSE(ptr.get());
1253   EXPECT_EQ(0, deletes);
1254
1255   // If we never invoke the Callback, it retains ownership and deletes.
1256   callback.Reset();
1257   EXPECT_EQ(1, deletes);
1258 }
1259
1260 TYPED_TEST(BindMoveOnlyTypeTest, PassedWithRvalue) {
1261   int deletes = 0;
1262   RepeatingCallback<TypeParam()> callback = BindRepeating(
1263       &PassThru<TypeParam>, Passed(TypeParam(new DeleteCounter(&deletes))));
1264   EXPECT_EQ(0, deletes);
1265
1266   // If we never invoke the Callback, it retains ownership and deletes.
1267   callback.Reset();
1268   EXPECT_EQ(1, deletes);
1269 }
1270
1271 // Check that ownership can be transferred back out.
1272 TYPED_TEST(BindMoveOnlyTypeTest, ReturnMoveOnlyType) {
1273   int deletes = 0;
1274   DeleteCounter* counter = new DeleteCounter(&deletes);
1275   RepeatingCallback<TypeParam()> callback =
1276       BindRepeating(&PassThru<TypeParam>, Passed(TypeParam(counter)));
1277   TypeParam result = callback.Run();
1278   ASSERT_EQ(counter, result.get());
1279   EXPECT_EQ(0, deletes);
1280
1281   // Resetting does not delete since ownership was transferred.
1282   callback.Reset();
1283   EXPECT_EQ(0, deletes);
1284
1285   // Ensure that we actually did get ownership.
1286   result.reset();
1287   EXPECT_EQ(1, deletes);
1288 }
1289
1290 TYPED_TEST(BindMoveOnlyTypeTest, UnboundForwarding) {
1291   int deletes = 0;
1292   TypeParam ptr(new DeleteCounter(&deletes));
1293   // Test unbound argument forwarding.
1294   RepeatingCallback<TypeParam(TypeParam)> cb_unbound =
1295       BindRepeating(&PassThru<TypeParam>);
1296   cb_unbound.Run(std::move(ptr));
1297   EXPECT_EQ(1, deletes);
1298 }
1299
1300 void VerifyVector(const std::vector<std::unique_ptr<int>>& v) {
1301   ASSERT_EQ(1u, v.size());
1302   EXPECT_EQ(12345, *v[0]);
1303 }
1304
1305 std::vector<std::unique_ptr<int>> AcceptAndReturnMoveOnlyVector(
1306     std::vector<std::unique_ptr<int>> v) {
1307   VerifyVector(v);
1308   return v;
1309 }
1310
1311 // Test that a vector containing move-only types can be used with Callback.
1312 TEST_F(BindTest, BindMoveOnlyVector) {
1313   using MoveOnlyVector = std::vector<std::unique_ptr<int>>;
1314
1315   MoveOnlyVector v;
1316   v.push_back(std::make_unique<int>(12345));
1317
1318   // Early binding should work:
1319   base::RepeatingCallback<MoveOnlyVector()> bound_cb =
1320       base::BindRepeating(&AcceptAndReturnMoveOnlyVector, Passed(&v));
1321   MoveOnlyVector intermediate_result = bound_cb.Run();
1322   VerifyVector(intermediate_result);
1323
1324   // As should passing it as an argument to Run():
1325   base::RepeatingCallback<MoveOnlyVector(MoveOnlyVector)> unbound_cb =
1326       base::BindRepeating(&AcceptAndReturnMoveOnlyVector);
1327   MoveOnlyVector final_result = unbound_cb.Run(std::move(intermediate_result));
1328   VerifyVector(final_result);
1329 }
1330
1331 // Argument copy-constructor usage for non-reference copy-only parameters.
1332 //   - Bound arguments are only copied once.
1333 //   - Forwarded arguments are only copied once.
1334 //   - Forwarded arguments with coercions are only copied twice (once for the
1335 //     coercion, and one for the final dispatch).
1336 TEST_F(BindTest, ArgumentCopies) {
1337   int copies = 0;
1338   int assigns = 0;
1339
1340   CopyCounter counter(&copies, &assigns);
1341   BindRepeating(&VoidPolymorphic<CopyCounter>::Run, counter);
1342   EXPECT_EQ(1, copies);
1343   EXPECT_EQ(0, assigns);
1344
1345   copies = 0;
1346   assigns = 0;
1347   BindRepeating(&VoidPolymorphic<CopyCounter>::Run,
1348                 CopyCounter(&copies, &assigns));
1349   EXPECT_EQ(1, copies);
1350   EXPECT_EQ(0, assigns);
1351
1352   copies = 0;
1353   assigns = 0;
1354   BindRepeating(&VoidPolymorphic<CopyCounter>::Run).Run(counter);
1355   EXPECT_EQ(2, copies);
1356   EXPECT_EQ(0, assigns);
1357
1358   copies = 0;
1359   assigns = 0;
1360   BindRepeating(&VoidPolymorphic<CopyCounter>::Run)
1361       .Run(CopyCounter(&copies, &assigns));
1362   EXPECT_EQ(1, copies);
1363   EXPECT_EQ(0, assigns);
1364
1365   copies = 0;
1366   assigns = 0;
1367   DerivedCopyMoveCounter derived(&copies, &assigns, nullptr, nullptr);
1368   BindRepeating(&VoidPolymorphic<CopyCounter>::Run).Run(CopyCounter(derived));
1369   EXPECT_EQ(2, copies);
1370   EXPECT_EQ(0, assigns);
1371
1372   copies = 0;
1373   assigns = 0;
1374   BindRepeating(&VoidPolymorphic<CopyCounter>::Run)
1375       .Run(CopyCounter(
1376           DerivedCopyMoveCounter(&copies, &assigns, nullptr, nullptr)));
1377   EXPECT_EQ(2, copies);
1378   EXPECT_EQ(0, assigns);
1379 }
1380
1381 // Argument move-constructor usage for move-only parameters.
1382 //   - Bound arguments passed by move are not copied.
1383 TEST_F(BindTest, ArgumentMoves) {
1384   int move_constructs = 0;
1385   int move_assigns = 0;
1386
1387   BindRepeating(&VoidPolymorphic<const MoveCounter&>::Run,
1388                 MoveCounter(&move_constructs, &move_assigns));
1389   EXPECT_EQ(1, move_constructs);
1390   EXPECT_EQ(0, move_assigns);
1391
1392   // TODO(tzik): Support binding move-only type into a non-reference parameter
1393   // of a variant of Callback.
1394
1395   move_constructs = 0;
1396   move_assigns = 0;
1397   BindRepeating(&VoidPolymorphic<MoveCounter>::Run)
1398       .Run(MoveCounter(&move_constructs, &move_assigns));
1399   EXPECT_EQ(1, move_constructs);
1400   EXPECT_EQ(0, move_assigns);
1401
1402   move_constructs = 0;
1403   move_assigns = 0;
1404   BindRepeating(&VoidPolymorphic<MoveCounter>::Run)
1405       .Run(MoveCounter(DerivedCopyMoveCounter(
1406           nullptr, nullptr, &move_constructs, &move_assigns)));
1407   EXPECT_EQ(2, move_constructs);
1408   EXPECT_EQ(0, move_assigns);
1409 }
1410
1411 // Argument constructor usage for non-reference movable-copyable
1412 // parameters.
1413 //   - Bound arguments passed by move are not copied.
1414 //   - Forwarded arguments are only copied once.
1415 //   - Forwarded arguments with coercions are only copied once and moved once.
1416 TEST_F(BindTest, ArgumentCopiesAndMoves) {
1417   int copies = 0;
1418   int assigns = 0;
1419   int move_constructs = 0;
1420   int move_assigns = 0;
1421
1422   CopyMoveCounter counter(&copies, &assigns, &move_constructs, &move_assigns);
1423   BindRepeating(&VoidPolymorphic<CopyMoveCounter>::Run, counter);
1424   EXPECT_EQ(1, copies);
1425   EXPECT_EQ(0, assigns);
1426   EXPECT_EQ(0, move_constructs);
1427   EXPECT_EQ(0, move_assigns);
1428
1429   copies = 0;
1430   assigns = 0;
1431   move_constructs = 0;
1432   move_assigns = 0;
1433   BindRepeating(
1434       &VoidPolymorphic<CopyMoveCounter>::Run,
1435       CopyMoveCounter(&copies, &assigns, &move_constructs, &move_assigns));
1436   EXPECT_EQ(0, copies);
1437   EXPECT_EQ(0, assigns);
1438   EXPECT_EQ(1, move_constructs);
1439   EXPECT_EQ(0, move_assigns);
1440
1441   copies = 0;
1442   assigns = 0;
1443   move_constructs = 0;
1444   move_assigns = 0;
1445   BindRepeating(&VoidPolymorphic<CopyMoveCounter>::Run).Run(counter);
1446   EXPECT_EQ(1, copies);
1447   EXPECT_EQ(0, assigns);
1448   EXPECT_EQ(1, move_constructs);
1449   EXPECT_EQ(0, move_assigns);
1450
1451   copies = 0;
1452   assigns = 0;
1453   move_constructs = 0;
1454   move_assigns = 0;
1455   BindRepeating(&VoidPolymorphic<CopyMoveCounter>::Run)
1456       .Run(CopyMoveCounter(&copies, &assigns, &move_constructs, &move_assigns));
1457   EXPECT_EQ(0, copies);
1458   EXPECT_EQ(0, assigns);
1459   EXPECT_EQ(1, move_constructs);
1460   EXPECT_EQ(0, move_assigns);
1461
1462   DerivedCopyMoveCounter derived_counter(&copies, &assigns, &move_constructs,
1463                                          &move_assigns);
1464   copies = 0;
1465   assigns = 0;
1466   move_constructs = 0;
1467   move_assigns = 0;
1468   BindRepeating(&VoidPolymorphic<CopyMoveCounter>::Run)
1469       .Run(CopyMoveCounter(derived_counter));
1470   EXPECT_EQ(1, copies);
1471   EXPECT_EQ(0, assigns);
1472   EXPECT_EQ(1, move_constructs);
1473   EXPECT_EQ(0, move_assigns);
1474
1475   copies = 0;
1476   assigns = 0;
1477   move_constructs = 0;
1478   move_assigns = 0;
1479   BindRepeating(&VoidPolymorphic<CopyMoveCounter>::Run)
1480       .Run(CopyMoveCounter(DerivedCopyMoveCounter(
1481           &copies, &assigns, &move_constructs, &move_assigns)));
1482   EXPECT_EQ(0, copies);
1483   EXPECT_EQ(0, assigns);
1484   EXPECT_EQ(2, move_constructs);
1485   EXPECT_EQ(0, move_assigns);
1486 }
1487
1488 TEST_F(BindTest, CapturelessLambda) {
1489   EXPECT_FALSE(internal::IsCallableObject<void>::value);
1490   EXPECT_FALSE(internal::IsCallableObject<int>::value);
1491   EXPECT_FALSE(internal::IsCallableObject<void (*)()>::value);
1492   EXPECT_FALSE(internal::IsCallableObject<void (NoRef::*)()>::value);
1493
1494   auto f = [] {};
1495   EXPECT_TRUE(internal::IsCallableObject<decltype(f)>::value);
1496
1497   int i = 0;
1498   auto g = [i] { (void)i; };
1499   EXPECT_TRUE(internal::IsCallableObject<decltype(g)>::value);
1500
1501   auto h = [](int, double) { return 'k'; };
1502   EXPECT_TRUE((std::is_same_v<char(int, double),
1503                               internal::ExtractCallableRunType<decltype(h)>>));
1504
1505   EXPECT_EQ(42, BindRepeating([] { return 42; }).Run());
1506   EXPECT_EQ(42, BindRepeating([](int i) { return i * 7; }, 6).Run());
1507
1508   int x = 1;
1509   base::RepeatingCallback<void(int)> cb =
1510       BindRepeating([](int* x, int i) { *x *= i; }, Unretained(&x));
1511   cb.Run(6);
1512   EXPECT_EQ(6, x);
1513   cb.Run(7);
1514   EXPECT_EQ(42, x);
1515 }
1516
1517 TEST_F(BindTest, EmptyFunctor) {
1518   struct NonEmptyFunctor {
1519     int operator()() const { return x; }
1520     int x = 42;
1521   };
1522
1523   struct EmptyFunctor {
1524     int operator()() { return 42; }
1525   };
1526
1527   struct EmptyFunctorConst {
1528     int operator()() const { return 42; }
1529   };
1530
1531   EXPECT_TRUE(internal::IsCallableObject<NonEmptyFunctor>::value);
1532   EXPECT_TRUE(internal::IsCallableObject<EmptyFunctor>::value);
1533   EXPECT_TRUE(internal::IsCallableObject<EmptyFunctorConst>::value);
1534   EXPECT_EQ(42, BindOnce(EmptyFunctor()).Run());
1535   EXPECT_EQ(42, BindOnce(EmptyFunctorConst()).Run());
1536   EXPECT_EQ(42, BindRepeating(EmptyFunctorConst()).Run());
1537 }
1538
1539 TEST_F(BindTest, CapturingLambdaForTesting) {
1540   // Test copyable lambdas.
1541   int x = 6;
1542   EXPECT_EQ(42, BindLambdaForTesting([=](int y) { return x * y; }).Run(7));
1543   EXPECT_EQ(42,
1544             BindLambdaForTesting([=](int y) mutable { return x *= y; }).Run(7));
1545   auto f = [x](std::unique_ptr<int> y) { return x * *y; };
1546   EXPECT_EQ(42, BindLambdaForTesting(f).Run(std::make_unique<int>(7)));
1547
1548   // Test move-only lambdas.
1549   auto y = std::make_unique<int>(7);
1550   auto g = [y = std::move(y)](int& x) mutable {
1551     return x * *std::exchange(y, nullptr);
1552   };
1553   EXPECT_EQ(42, BindLambdaForTesting(std::move(g)).Run(x));
1554
1555   y = std::make_unique<int>(7);
1556   auto h = [x, y = std::move(y)] { return x * *y; };
1557   EXPECT_EQ(42, BindLambdaForTesting(std::move(h)).Run());
1558 }
1559
1560 TEST_F(BindTest, Cancellation) {
1561   EXPECT_CALL(no_ref_, VoidMethodWithIntArg(_)).Times(2);
1562
1563   WeakPtrFactory<NoRef> weak_factory(&no_ref_);
1564   RepeatingCallback<void(int)> cb =
1565       BindRepeating(&NoRef::VoidMethodWithIntArg, weak_factory.GetWeakPtr());
1566   RepeatingClosure cb2 = BindRepeating(cb, 8);
1567   OnceClosure cb3 = BindOnce(cb, 8);
1568
1569   OnceCallback<void(int)> cb4 =
1570       BindOnce(&NoRef::VoidMethodWithIntArg, weak_factory.GetWeakPtr());
1571   EXPECT_FALSE(cb4.IsCancelled());
1572
1573   OnceClosure cb5 = BindOnce(std::move(cb4), 8);
1574
1575   EXPECT_FALSE(cb.IsCancelled());
1576   EXPECT_FALSE(cb2.IsCancelled());
1577   EXPECT_FALSE(cb3.IsCancelled());
1578   EXPECT_FALSE(cb5.IsCancelled());
1579
1580   cb.Run(6);
1581   cb2.Run();
1582
1583   weak_factory.InvalidateWeakPtrs();
1584
1585   EXPECT_TRUE(cb.IsCancelled());
1586   EXPECT_TRUE(cb2.IsCancelled());
1587   EXPECT_TRUE(cb3.IsCancelled());
1588   EXPECT_TRUE(cb5.IsCancelled());
1589
1590   cb.Run(6);
1591   cb2.Run();
1592   std::move(cb3).Run();
1593   std::move(cb5).Run();
1594 }
1595
1596 TEST_F(BindTest, OnceCallback) {
1597   // Check if Callback variants have declarations of conversions as expected.
1598   // Copy constructor and assignment of RepeatingCallback.
1599   static_assert(
1600       std::is_constructible_v<RepeatingClosure, const RepeatingClosure&>,
1601       "RepeatingClosure should be copyable.");
1602   static_assert(std::is_assignable_v<RepeatingClosure, const RepeatingClosure&>,
1603                 "RepeatingClosure should be copy-assignable.");
1604
1605   // Move constructor and assignment of RepeatingCallback.
1606   static_assert(std::is_constructible_v<RepeatingClosure, RepeatingClosure&&>,
1607                 "RepeatingClosure should be movable.");
1608   static_assert(std::is_assignable_v<RepeatingClosure, RepeatingClosure&&>,
1609                 "RepeatingClosure should be move-assignable");
1610
1611   // Conversions from OnceCallback to RepeatingCallback.
1612   static_assert(!std::is_constructible_v<RepeatingClosure, const OnceClosure&>,
1613                 "OnceClosure should not be convertible to RepeatingClosure.");
1614   static_assert(!std::is_assignable_v<RepeatingClosure, const OnceClosure&>,
1615                 "OnceClosure should not be convertible to RepeatingClosure.");
1616
1617   // Destructive conversions from OnceCallback to RepeatingCallback.
1618   static_assert(!std::is_constructible_v<RepeatingClosure, OnceClosure&&>,
1619                 "OnceClosure should not be convertible to RepeatingClosure.");
1620   static_assert(!std::is_assignable_v<RepeatingClosure, OnceClosure&&>,
1621                 "OnceClosure should not be convertible to RepeatingClosure.");
1622
1623   // Copy constructor and assignment of OnceCallback.
1624   static_assert(!std::is_constructible_v<OnceClosure, const OnceClosure&>,
1625                 "OnceClosure should not be copyable.");
1626   static_assert(!std::is_assignable_v<OnceClosure, const OnceClosure&>,
1627                 "OnceClosure should not be copy-assignable");
1628
1629   // Move constructor and assignment of OnceCallback.
1630   static_assert(std::is_constructible_v<OnceClosure, OnceClosure&&>,
1631                 "OnceClosure should be movable.");
1632   static_assert(std::is_assignable_v<OnceClosure, OnceClosure&&>,
1633                 "OnceClosure should be move-assignable.");
1634
1635   // Conversions from RepeatingCallback to OnceCallback.
1636   static_assert(std::is_constructible_v<OnceClosure, const RepeatingClosure&>,
1637                 "RepeatingClosure should be convertible to OnceClosure.");
1638   static_assert(std::is_assignable_v<OnceClosure, const RepeatingClosure&>,
1639                 "RepeatingClosure should be convertible to OnceClosure.");
1640
1641   // Destructive conversions from RepeatingCallback to OnceCallback.
1642   static_assert(std::is_constructible_v<OnceClosure, RepeatingClosure&&>,
1643                 "RepeatingClosure should be convertible to OnceClosure.");
1644   static_assert(std::is_assignable_v<OnceClosure, RepeatingClosure&&>,
1645                 "RepeatingClosure should be covretible to OnceClosure.");
1646
1647   OnceClosure cb = BindOnce(&VoidPolymorphic<>::Run);
1648   std::move(cb).Run();
1649
1650   // RepeatingCallback should be convertible to OnceCallback.
1651   OnceClosure cb2 = BindRepeating(&VoidPolymorphic<>::Run);
1652   std::move(cb2).Run();
1653
1654   RepeatingClosure cb3 = BindRepeating(&VoidPolymorphic<>::Run);
1655   cb = cb3;
1656   std::move(cb).Run();
1657
1658   cb = std::move(cb2);
1659
1660   OnceCallback<void(int)> cb4 =
1661       BindOnce(&VoidPolymorphic<std::unique_ptr<int>, int>::Run,
1662                std::make_unique<int>(0));
1663   BindOnce(std::move(cb4), 1).Run();
1664 }
1665
1666 // Callback construction and assignment tests.
1667 //   - Construction from an InvokerStorageHolder should not cause ref/deref.
1668 //   - Assignment from other callback should only cause one ref
1669 //
1670 // TODO(ajwong): Is there actually a way to test this?
1671
1672 #if BUILDFLAG(IS_WIN)
1673 int __fastcall FastCallFunc(int n) {
1674   return n;
1675 }
1676
1677 int __stdcall StdCallFunc(int n) {
1678   return n;
1679 }
1680
1681 // Windows specific calling convention support.
1682 //   - Can bind a __fastcall function.
1683 //   - Can bind a __stdcall function.
1684 //   - Can bind const and non-const __stdcall methods.
1685 TEST_F(BindTest, WindowsCallingConventions) {
1686   auto fastcall_cb = BindRepeating(&FastCallFunc, 1);
1687   EXPECT_EQ(1, fastcall_cb.Run());
1688
1689   auto stdcall_cb = BindRepeating(&StdCallFunc, 2);
1690   EXPECT_EQ(2, stdcall_cb.Run());
1691
1692   class MethodHolder {
1693    public:
1694     int __stdcall Func(int n) { return n; }
1695     int __stdcall ConstFunc(int n) const { return -n; }
1696   };
1697
1698   MethodHolder obj;
1699   auto stdcall_method_cb =
1700       BindRepeating(&MethodHolder::Func, base::Unretained(&obj), 1);
1701   EXPECT_EQ(1, stdcall_method_cb.Run());
1702
1703   const MethodHolder const_obj;
1704   auto stdcall_const_method_cb =
1705       BindRepeating(&MethodHolder::ConstFunc, base::Unretained(&const_obj), 1);
1706   EXPECT_EQ(-1, stdcall_const_method_cb.Run());
1707 }
1708 #endif
1709
1710 // Test unwrapping the various wrapping functions.
1711
1712 TEST_F(BindTest, UnwrapUnretained) {
1713   int i = 0;
1714   auto unretained = Unretained(&i);
1715   EXPECT_EQ(&i, internal::Unwrap(unretained));
1716   EXPECT_EQ(&i, internal::Unwrap(std::move(unretained)));
1717 }
1718
1719 TEST_F(BindTest, UnwrapRetainedRef) {
1720   auto p = MakeRefCounted<RefCountedData<int>>();
1721   auto retained_ref = RetainedRef(p);
1722   EXPECT_EQ(p.get(), internal::Unwrap(retained_ref));
1723   EXPECT_EQ(p.get(), internal::Unwrap(std::move(retained_ref)));
1724 }
1725
1726 TEST_F(BindTest, UnwrapOwned) {
1727   {
1728     int* p = new int;
1729     auto owned = Owned(p);
1730     EXPECT_EQ(p, internal::Unwrap(owned));
1731     EXPECT_EQ(p, internal::Unwrap(std::move(owned)));
1732   }
1733
1734   {
1735     auto p = std::make_unique<int>();
1736     int* raw_p = p.get();
1737     auto owned = Owned(std::move(p));
1738     EXPECT_EQ(raw_p, internal::Unwrap(owned));
1739     EXPECT_EQ(raw_p, internal::Unwrap(std::move(owned)));
1740   }
1741 }
1742
1743 TEST_F(BindTest, UnwrapPassed) {
1744   int* p = new int;
1745   auto passed = Passed(WrapUnique(p));
1746   EXPECT_EQ(p, internal::Unwrap(passed).get());
1747
1748   p = new int;
1749   EXPECT_EQ(p, internal::Unwrap(Passed(WrapUnique(p))).get());
1750 }
1751
1752 TEST_F(BindTest, BindNoexcept) {
1753   EXPECT_EQ(42, base::BindOnce(&Noexcept).Run());
1754   EXPECT_EQ(
1755       42,
1756       base::BindOnce(&BindTest::NoexceptMethod, base::Unretained(this)).Run());
1757   EXPECT_EQ(
1758       42, base::BindOnce(&BindTest::ConstNoexceptMethod, base::Unretained(this))
1759               .Run());
1760   EXPECT_EQ(42, base::BindOnce(NoexceptFunctor()).Run());
1761   EXPECT_EQ(42, base::BindOnce(ConstNoexceptFunctor()).Run());
1762 }
1763
1764 int PingPong(int* i_ptr) {
1765   return *i_ptr;
1766 }
1767
1768 TEST_F(BindTest, BindAndCallbacks) {
1769   int i = 123;
1770   raw_ptr<int> p = &i;
1771
1772   auto callback = base::BindOnce(PingPong, base::Unretained(p));
1773   int res = std::move(callback).Run();
1774   EXPECT_EQ(123, res);
1775 }
1776
1777 TEST_F(BindTest, ConvertibleArgs) {
1778   // Create two types S and T, such that you can convert a T to an S, but you
1779   // cannot construct an S from a T.
1780   struct T;
1781   class S {
1782     friend struct T;
1783     explicit S(const T&) {}
1784   };
1785   struct T {
1786     // NOLINTNEXTLINE(google-explicit-constructor)
1787     operator S() const { return S(*this); }
1788   };
1789   static_assert(!std::is_constructible_v<S, T>);
1790   static_assert(std::is_convertible_v<T, S>);
1791
1792   // Ensure it's possible to pass a T to a function expecting an S.
1793   void (*foo)(S) = +[](S) {};
1794   const T t;
1795   auto callback = base::BindOnce(foo, t);
1796   std::move(callback).Run();
1797 }
1798
1799 }  // namespace
1800
1801 // This simulates a race weak pointer that, unlike our `base::WeakPtr<>`,
1802 // may become invalidated between `operator bool()` is tested and `Lock()`
1803 // is called in the implementation of `Unwrap()`.
1804 template <typename T>
1805 struct MockRacyWeakPtr {
1806   explicit MockRacyWeakPtr(T*) {}
1807   T* Lock() const { return nullptr; }
1808
1809   explicit operator bool() const { return true; }
1810 };
1811
1812 template <typename T>
1813 struct IsWeakReceiver<MockRacyWeakPtr<T>> : std::true_type {};
1814
1815 template <typename T>
1816 struct BindUnwrapTraits<MockRacyWeakPtr<T>> {
1817   static T* Unwrap(const MockRacyWeakPtr<T>& o) { return o.Lock(); }
1818 };
1819
1820 template <typename T>
1821 struct MaybeValidTraits<MockRacyWeakPtr<T>> {
1822   static bool MaybeValid(const MockRacyWeakPtr<T>& o) { return true; }
1823 };
1824
1825 namespace {
1826
1827 // Note this only covers a case of racy weak pointer invalidation. Other
1828 // weak pointer scenarios (such as a valid pointer) are covered
1829 // in BindTest.WeakPtrFor{Once,Repeating}.
1830 TEST_F(BindTest, BindRacyWeakPtrTest) {
1831   MockRacyWeakPtr<NoRef> weak(&no_ref_);
1832
1833   RepeatingClosure cb = base::BindRepeating(&NoRef::VoidMethod0, weak);
1834   cb.Run();
1835 }
1836
1837 // Test null callbacks cause a DCHECK.
1838 TEST(BindDeathTest, NullCallback) {
1839   base::RepeatingCallback<void(int)> null_cb;
1840   ASSERT_TRUE(null_cb.is_null());
1841   EXPECT_CHECK_DEATH(base::BindRepeating(null_cb, 42));
1842 }
1843
1844 TEST(BindDeathTest, NullFunctionPointer) {
1845   void (*null_function)(int) = nullptr;
1846   EXPECT_DCHECK_DEATH(base::BindRepeating(null_function, 42));
1847 }
1848
1849 TEST(BindDeathTest, NullCallbackWithoutBoundArgs) {
1850   base::OnceCallback<void(int)> null_cb;
1851   ASSERT_TRUE(null_cb.is_null());
1852   EXPECT_CHECK_DEATH(base::BindOnce(std::move(null_cb)));
1853 }
1854
1855 TEST(BindDeathTest, BanFirstOwnerOfRefCountedType) {
1856   StrictMock<HasRef> has_ref;
1857   EXPECT_DCHECK_DEATH({
1858     EXPECT_CALL(has_ref, HasAtLeastOneRef()).WillOnce(Return(false));
1859     base::BindOnce(&HasRef::VoidMethod0, &has_ref);
1860   });
1861
1862   EXPECT_DCHECK_DEATH({
1863     raw_ptr<HasRef> rawptr(&has_ref);
1864     EXPECT_CALL(has_ref, HasAtLeastOneRef()).WillOnce(Return(false));
1865     base::BindOnce(&HasRef::VoidMethod0, rawptr);
1866   });
1867 }
1868
1869 #if BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT)
1870
1871 void HandleOOM(size_t unused_size) {
1872   LOG(FATAL) << "Out of memory";
1873 }
1874
1875 // Basic set of options to mostly only enable `BackupRefPtr::kEnabled`.
1876 // This avoids the boilerplate of having too much options enabled for simple
1877 // testing purpose.
1878 static constexpr partition_alloc::PartitionOptions
1879     kOnlyEnableBackupRefPtrOptions = {
1880         .backup_ref_ptr = partition_alloc::PartitionOptions::kEnabled,
1881 };
1882
1883 class BindUnretainedDanglingInternalFixture : public BindTest {
1884  public:
1885   void SetUp() override {
1886     partition_alloc::PartitionAllocGlobalInit(HandleOOM);
1887     enabled_feature_list_.InitWithFeaturesAndParameters(
1888         {{features::kPartitionAllocUnretainedDanglingPtr, {{"mode", "crash"}}}},
1889         {/* disabled_features */});
1890     allocator::InstallUnretainedDanglingRawPtrChecks();
1891   }
1892
1893   void TearDown() override {
1894     enabled_feature_list_.Reset();
1895     allocator::InstallUnretainedDanglingRawPtrChecks();
1896   }
1897
1898   // In unit tests, allocations being tested need to live in a separate PA
1899   // root so the test code doesn't interfere with various counters. Following
1900   // methods are helpers for managing allocations inside the separate allocator
1901   // root.
1902   template <typename T,
1903             RawPtrTraits Traits = RawPtrTraits::kEmpty,
1904             typename... Args>
1905   raw_ptr<T, Traits> Alloc(Args&&... args) {
1906     void* ptr = allocator_.root()->Alloc(sizeof(T), "");
1907     T* p = new (reinterpret_cast<T*>(ptr)) T(std::forward<Args>(args)...);
1908     return raw_ptr<T, Traits>(p);
1909   }
1910   template <typename T, RawPtrTraits Traits>
1911   void Free(raw_ptr<T, Traits>& ptr) {
1912     allocator_.root()->Free(ptr.ExtractAsDangling());
1913   }
1914
1915  private:
1916   test::ScopedFeatureList enabled_feature_list_;
1917   partition_alloc::PartitionAllocatorForTesting allocator_{
1918       kOnlyEnableBackupRefPtrOptions};
1919 };
1920
1921 class BindUnretainedDanglingTest
1922     : public BindUnretainedDanglingInternalFixture {};
1923 class BindUnretainedDanglingDeathTest
1924     : public BindUnretainedDanglingInternalFixture {};
1925
1926 bool PtrCheckFn(int* p) {
1927   return p != nullptr;
1928 }
1929
1930 bool RefCheckFn(const int& p) {
1931   return true;
1932 }
1933
1934 bool MayBeDanglingCheckFn(MayBeDangling<int> p) {
1935   return p != nullptr;
1936 }
1937
1938 bool MayBeDanglingAndDummyTraitCheckFn(
1939     MayBeDangling<int, RawPtrTraits::kDummyForTest> p) {
1940   return p != nullptr;
1941 }
1942
1943 class ClassWithWeakPtr {
1944  public:
1945   ClassWithWeakPtr() = default;
1946   void RawPtrArg(int* p) { *p = 123; }
1947   void RawRefArg(int& p) { p = 123; }
1948   WeakPtr<ClassWithWeakPtr> GetWeakPtr() { return weak_factory_.GetWeakPtr(); }
1949
1950  private:
1951   WeakPtrFactory<ClassWithWeakPtr> weak_factory_{this};
1952 };
1953
1954 TEST_F(BindUnretainedDanglingTest, UnretainedNoDanglingPtr) {
1955   raw_ptr<int> p = Alloc<int>(3);
1956   auto callback = base::BindOnce(PingPong, base::Unretained(p));
1957   EXPECT_EQ(std::move(callback).Run(), 3);
1958   Free(p);
1959 }
1960
1961 TEST_F(BindUnretainedDanglingTest, UnsafeDanglingPtr) {
1962   raw_ptr<int> p = Alloc<int>(3);
1963   auto callback = base::BindOnce(MayBeDanglingCheckFn, base::UnsafeDangling(p));
1964   Free(p);
1965   EXPECT_EQ(std::move(callback).Run(), true);
1966 }
1967
1968 TEST_F(BindUnretainedDanglingTest, UnsafeDanglingPtrWithDummyTrait) {
1969   raw_ptr<int, RawPtrTraits::kDummyForTest> p =
1970       Alloc<int, RawPtrTraits::kDummyForTest>(3);
1971   auto callback = base::BindOnce(MayBeDanglingAndDummyTraitCheckFn,
1972                                  base::UnsafeDangling(p));
1973   Free(p);
1974   EXPECT_EQ(std::move(callback).Run(), true);
1975 }
1976
1977 TEST_F(BindUnretainedDanglingTest,
1978        UnsafeDanglingPtrWithDummyAndDanglingTraits) {
1979   raw_ptr<int, RawPtrTraits::kDummyForTest | RawPtrTraits::kMayDangle> p =
1980       Alloc<int, RawPtrTraits::kDummyForTest | RawPtrTraits::kMayDangle>(3);
1981   auto callback = base::BindOnce(MayBeDanglingAndDummyTraitCheckFn,
1982                                  base::UnsafeDangling(p));
1983   Free(p);
1984   EXPECT_EQ(std::move(callback).Run(), true);
1985 }
1986
1987 TEST_F(BindUnretainedDanglingTest, UnsafeDanglingPtrNoRawPtrReceiver) {
1988   std::unique_ptr<ClassWithWeakPtr> r = std::make_unique<ClassWithWeakPtr>();
1989   int val = 0;
1990   auto callback =
1991       base::BindOnce(&ClassWithWeakPtr::RawPtrArg,
1992                      base::UnsafeDangling(r.get()), base::Unretained(&val));
1993   std::move(callback).Run();
1994   EXPECT_EQ(val, 123);
1995 }
1996
1997 TEST_F(BindUnretainedDanglingTest, UnsafeDanglingUntriagedPtr) {
1998   raw_ptr<int> p = Alloc<int>(3);
1999   auto callback = base::BindOnce(PtrCheckFn, base::UnsafeDanglingUntriaged(p));
2000   Free(p);
2001   EXPECT_EQ(std::move(callback).Run(), true);
2002 }
2003
2004 TEST_F(BindUnretainedDanglingTest, UnretainedWeakReceiverValidNoDangling) {
2005   raw_ptr<int> p = Alloc<int>(3);
2006   std::unique_ptr<ClassWithWeakPtr> r = std::make_unique<ClassWithWeakPtr>();
2007   auto callback = base::BindOnce(&ClassWithWeakPtr::RawPtrArg, r->GetWeakPtr(),
2008                                  base::Unretained(p));
2009   std::move(callback).Run();
2010   EXPECT_EQ(*p, 123);
2011   Free(p);
2012 }
2013
2014 TEST_F(BindUnretainedDanglingTest, UnretainedRefWeakReceiverValidNoDangling) {
2015   raw_ptr<int> p = Alloc<int>(3);
2016   int& ref = *p;
2017   std::unique_ptr<ClassWithWeakPtr> r = std::make_unique<ClassWithWeakPtr>();
2018   auto callback = base::BindOnce(&ClassWithWeakPtr::RawRefArg, r->GetWeakPtr(),
2019                                  std::ref(ref));
2020   std::move(callback).Run();
2021   EXPECT_EQ(*p, 123);
2022   Free(p);
2023 }
2024
2025 TEST_F(BindUnretainedDanglingTest, UnretainedWeakReceiverInvalidNoDangling) {
2026   raw_ptr<int> p = Alloc<int>(3);
2027   std::unique_ptr<ClassWithWeakPtr> r = std::make_unique<ClassWithWeakPtr>();
2028   auto callback = base::BindOnce(&ClassWithWeakPtr::RawPtrArg, r->GetWeakPtr(),
2029                                  base::Unretained(p));
2030   r.reset();
2031   Free(p);
2032   std::move(callback).Run();
2033   // Should reach this point without crashing; there is a dangling pointer, but
2034   // the callback is cancelled because the WeakPtr is already invalidated.
2035 }
2036
2037 TEST_F(BindUnretainedDanglingTest, UnretainedRefWeakReceiverInvalidNoDangling) {
2038   raw_ptr<int> p = Alloc<int>(3);
2039   int& ref = *p;
2040   std::unique_ptr<ClassWithWeakPtr> r = std::make_unique<ClassWithWeakPtr>();
2041   auto callback = base::BindOnce(&ClassWithWeakPtr::RawRefArg, r->GetWeakPtr(),
2042                                  std::ref(ref));
2043   r.reset();
2044   Free(p);
2045   std::move(callback).Run();
2046   // Should reach this point without crashing; there is a dangling pointer, but
2047   // the callback is cancelled because the WeakPtr is already invalidated.
2048 }
2049
2050 TEST_F(BindUnretainedDanglingTest, UnretainedRefUnsafeDangling) {
2051   raw_ptr<int> p = Alloc<int>(3);
2052   int& ref = *p;
2053   auto callback =
2054       base::BindOnce(RefCheckFn, base::UnsafeDangling(base::raw_ref<int>(ref)));
2055   Free(p);
2056   EXPECT_EQ(std::move(callback).Run(), true);
2057   // Should reach this point without crashing; there is a dangling pointer, but
2058   // the we marked the reference as `UnsafeDangling`.
2059 }
2060
2061 TEST_F(BindUnretainedDanglingTest, UnretainedRefUnsafeDanglingUntriaged) {
2062   raw_ptr<int> p = Alloc<int>(3);
2063   int& ref = *p;
2064   auto callback = base::BindOnce(
2065       RefCheckFn, base::UnsafeDanglingUntriaged(base::raw_ref<const int>(ref)));
2066   Free(p);
2067   EXPECT_EQ(std::move(callback).Run(), true);
2068   // Should reach this point without crashing; there is a dangling pointer, but
2069   // the we marked the reference as `UnsafeDanglingUntriaged`.
2070 }
2071
2072 // Death tests misbehave on Android, http://crbug.com/643760.
2073 #if defined(GTEST_HAS_DEATH_TEST) && !BUILDFLAG(IS_ANDROID)
2074
2075 int FuncWithRefArgument(int& i_ptr) {
2076   return i_ptr;
2077 }
2078
2079 TEST_F(BindUnretainedDanglingDeathTest, UnretainedDanglingPtr) {
2080   raw_ptr<int> p = Alloc<int>(3);
2081   auto callback = base::BindOnce(PingPong, base::Unretained(p));
2082   Free(p);
2083   EXPECT_DEATH(std::move(callback).Run(), "");
2084 }
2085
2086 TEST_F(BindUnretainedDanglingDeathTest, UnretainedRefDanglingPtr) {
2087   raw_ptr<int> p = Alloc<int>(3);
2088   int& ref = *p;
2089   auto callback = base::BindOnce(FuncWithRefArgument, std::ref(ref));
2090   Free(p);
2091   EXPECT_DEATH(std::move(callback).Run(), "");
2092 }
2093
2094 TEST_F(BindUnretainedDanglingDeathTest,
2095        UnretainedRefWithManualUnretainedDanglingPtr) {
2096   raw_ptr<int> p = Alloc<int>(3);
2097   int& ref = *p;
2098   auto callback = base::BindOnce(FuncWithRefArgument,
2099                                  base::Unretained(base::raw_ref<int>(ref)));
2100   Free(p);
2101   EXPECT_DEATH(std::move(callback).Run(), "");
2102 }
2103
2104 TEST_F(BindUnretainedDanglingDeathTest, UnretainedWeakReceiverDangling) {
2105   raw_ptr<int> p = Alloc<int>(3);
2106   std::unique_ptr<ClassWithWeakPtr> r = std::make_unique<ClassWithWeakPtr>();
2107   auto callback = base::BindOnce(&ClassWithWeakPtr::RawPtrArg, r->GetWeakPtr(),
2108                                  base::Unretained(p));
2109   Free(p);
2110   EXPECT_DEATH(std::move(callback).Run(), "");
2111 }
2112
2113 #endif  // defined(GTEST_HAS_DEATH_TEST) && !BUILDFLAG(IS_ANDROID)
2114
2115 #endif  // BUILDFLAG(ENABLE_BACKUP_REF_PTR_SUPPORT)
2116
2117 }  // namespace
2118 }  // namespace base