1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
12 #include "base/callback.h"
13 #include "base/memory/ptr_util.h"
14 #include "base/memory/ref_counted.h"
15 #include "base/memory/weak_ptr.h"
16 #include "base/strings/string_number_conversions.h"
17 #include "base/test/bind.h"
18 #include "base/test/gtest_util.h"
19 #include "build/build_config.h"
20 #include "testing/gmock/include/gmock/gmock.h"
21 #include "testing/gtest/include/gtest/gtest.h"
23 using ::testing::AnyNumber;
24 using ::testing::ByMove;
25 using ::testing::Mock;
26 using ::testing::Return;
27 using ::testing::StrictMock;
38 NoRef(const NoRef&) = delete;
39 // Particularly important in this test to ensure no copies are made.
40 NoRef& operator=(const NoRef&) = delete;
42 MOCK_METHOD0(VoidMethod0, void());
43 MOCK_CONST_METHOD0(VoidConstMethod0, void());
45 MOCK_METHOD0(IntMethod0, int());
46 MOCK_CONST_METHOD0(IntConstMethod0, int());
48 MOCK_METHOD1(VoidMethodWithIntArg, void(int));
49 MOCK_METHOD0(UniquePtrMethod0, std::unique_ptr<int>());
53 class HasRef : public NoRef {
56 HasRef(const HasRef&) = delete;
57 // Particularly important in this test to ensure no copies are made.
58 HasRef& operator=(const HasRef&) = delete;
60 MOCK_CONST_METHOD0(AddRef, void());
61 MOCK_CONST_METHOD0(Release, bool());
62 MOCK_CONST_METHOD0(HasAtLeastOneRef, bool());
65 class HasRefPrivateDtor : public HasRef {
67 ~HasRefPrivateDtor() = default;
70 static const int kParentValue = 1;
71 static const int kChildValue = 2;
75 void AddRef() const {}
76 void Release() const {}
77 bool HasAtLeastOneRef() const { return true; }
78 virtual void VirtualSet() { value = kParentValue; }
79 void NonVirtualSet() { value = kParentValue; }
83 class Child : public Parent {
85 void VirtualSet() override { value = kChildValue; }
86 void NonVirtualSet() { value = kChildValue; }
91 virtual void VirtualSet() { value = kParentValue; }
92 void NonVirtualSet() { value = kParentValue; }
96 class NoRefChild : public NoRefParent {
97 void VirtualSet() override { value = kChildValue; }
98 void NonVirtualSet() { value = kChildValue; }
101 // Used for probing the number of copies and moves that occur if a type must be
102 // coerced during argument forwarding in the Run() methods.
103 struct DerivedCopyMoveCounter {
104 DerivedCopyMoveCounter(int* copies,
106 int* move_constructs,
110 move_constructs_(move_constructs),
111 move_assigns_(move_assigns) {}
114 int* move_constructs_;
118 // Used for probing the number of copies and moves in an argument.
119 class CopyMoveCounter {
121 CopyMoveCounter(int* copies,
123 int* move_constructs,
127 move_constructs_(move_constructs),
128 move_assigns_(move_assigns) {}
130 CopyMoveCounter(const CopyMoveCounter& other)
131 : copies_(other.copies_),
132 assigns_(other.assigns_),
133 move_constructs_(other.move_constructs_),
134 move_assigns_(other.move_assigns_) {
138 CopyMoveCounter(CopyMoveCounter&& other)
139 : copies_(other.copies_),
140 assigns_(other.assigns_),
141 move_constructs_(other.move_constructs_),
142 move_assigns_(other.move_assigns_) {
143 (*move_constructs_)++;
146 // Probing for copies from coercion.
147 explicit CopyMoveCounter(const DerivedCopyMoveCounter& other)
148 : copies_(other.copies_),
149 assigns_(other.assigns_),
150 move_constructs_(other.move_constructs_),
151 move_assigns_(other.move_assigns_) {
155 // Probing for moves from coercion.
156 explicit CopyMoveCounter(DerivedCopyMoveCounter&& other)
157 : copies_(other.copies_),
158 assigns_(other.assigns_),
159 move_constructs_(other.move_constructs_),
160 move_assigns_(other.move_assigns_) {
161 (*move_constructs_)++;
164 const CopyMoveCounter& operator=(const CopyMoveCounter& rhs) {
165 copies_ = rhs.copies_;
166 assigns_ = rhs.assigns_;
167 move_constructs_ = rhs.move_constructs_;
168 move_assigns_ = rhs.move_assigns_;
175 const CopyMoveCounter& operator=(CopyMoveCounter&& rhs) {
176 copies_ = rhs.copies_;
177 assigns_ = rhs.assigns_;
178 move_constructs_ = rhs.move_constructs_;
179 move_assigns_ = rhs.move_assigns_;
193 int* move_constructs_;
197 // Used for probing the number of copies in an argument. The instance is a
198 // copyable and non-movable type.
201 CopyCounter(int* copies, int* assigns)
202 : counter_(copies, assigns, nullptr, nullptr) {}
203 CopyCounter(const CopyCounter& other) = default;
204 CopyCounter& operator=(const CopyCounter& other) = default;
206 explicit CopyCounter(const DerivedCopyMoveCounter& other) : counter_(other) {}
208 int copies() const { return counter_.copies(); }
211 CopyMoveCounter counter_;
214 // Used for probing the number of moves in an argument. The instance is a
215 // non-copyable and movable type.
218 MoveCounter(int* move_constructs, int* move_assigns)
219 : counter_(nullptr, nullptr, move_constructs, move_assigns) {}
220 MoveCounter(MoveCounter&& other) : counter_(std::move(other.counter_)) {}
221 MoveCounter& operator=(MoveCounter&& other) {
222 counter_ = std::move(other.counter_);
226 explicit MoveCounter(DerivedCopyMoveCounter&& other)
227 : counter_(std::move(other)) {}
230 CopyMoveCounter counter_;
233 class DeleteCounter {
235 explicit DeleteCounter(int* deletes)
236 : deletes_(deletes) {
243 void VoidMethod0() {}
249 template <typename T>
250 T PassThru(T scoper) {
254 // Some test functions that we can Bind to.
255 template <typename T>
256 T PolymorphicIdentity(T t) {
260 template <typename... Ts>
261 struct VoidPolymorphic {
262 static void Run(Ts... t) {}
265 int Identity(int n) {
269 int ArrayGet(const int array[], int n) {
273 int Sum(int a, int b, int c, int d, int e, int f) {
274 return a + b + c + d + e + f;
277 const char* CStringIdentity(const char* s) {
281 int GetCopies(const CopyMoveCounter& counter) {
282 return counter.copies();
285 int UnwrapNoRefParent(NoRefParent p) {
289 int UnwrapNoRefParentPtr(NoRefParent* p) {
293 int UnwrapNoRefParentConstRef(const NoRefParent& p) {
297 void RefArgSet(int &n) {
301 void PtrArgSet(int *n) {
305 int FunctionWithWeakFirstParam(WeakPtr<NoRef> o, int n) {
309 int FunctionWithScopedRefptrFirstParam(const scoped_refptr<HasRef>& o, int n) {
313 void TakesACallback(const RepeatingClosure& callback) {
317 int Noexcept() noexcept {
321 class BindTest : public ::testing::Test {
324 const_has_ref_ptr_ = &has_ref_;
325 const_no_ref_ptr_ = &no_ref_;
326 static_func_mock_ptr = &static_func_mock_;
328 BindTest(const BindTest&) = delete;
329 BindTest& operator=(const BindTest&) = delete;
330 ~BindTest() override = default;
332 static void VoidFunc0() {
333 static_func_mock_ptr->VoidMethod0();
336 static int IntFunc0() { return static_func_mock_ptr->IntMethod0(); }
337 int NoexceptMethod() noexcept { return 42; }
338 int ConstNoexceptMethod() const noexcept { return 42; }
341 StrictMock<NoRef> no_ref_;
342 StrictMock<HasRef> has_ref_;
343 const HasRef* const_has_ref_ptr_;
344 const NoRef* const_no_ref_ptr_;
345 StrictMock<NoRef> static_func_mock_;
347 // Used by the static functions to perform expectations.
348 static StrictMock<NoRef>* static_func_mock_ptr;
351 StrictMock<NoRef>* BindTest::static_func_mock_ptr;
352 StrictMock<NoRef>* g_func_mock_ptr;
355 g_func_mock_ptr->VoidMethod0();
359 return g_func_mock_ptr->IntMethod0();
362 TEST_F(BindTest, BasicTest) {
363 RepeatingCallback<int(int, int, int)> cb = BindRepeating(&Sum, 32, 16, 8);
364 EXPECT_EQ(92, cb.Run(13, 12, 11));
366 RepeatingCallback<int(int, int, int, int, int, int)> c1 = BindRepeating(&Sum);
367 EXPECT_EQ(69, c1.Run(14, 13, 12, 11, 10, 9));
369 RepeatingCallback<int(int, int, int)> c2 = BindRepeating(c1, 32, 16, 8);
370 EXPECT_EQ(86, c2.Run(11, 10, 9));
372 RepeatingCallback<int()> c3 = BindRepeating(c2, 4, 2, 1);
373 EXPECT_EQ(63, c3.Run());
376 // Test that currying the rvalue result of another BindRepeating() works
378 // - rvalue should be usable as argument to BindRepeating().
379 // - multiple runs of resulting RepeatingCallback remain valid.
380 TEST_F(BindTest, CurryingRvalueResultOfBind) {
382 RepeatingClosure cb = BindRepeating(&TakesACallback,
383 BindRepeating(&PtrArgSet, &n));
385 // If we implement BindRepeating() such that the return value has
386 // auto_ptr-like semantics, the second call here will fail because ownership
387 // of the internal BindState<> would have been transferred to a *temporary*
388 // construction of a RepeatingCallback object on the first call.
397 TEST_F(BindTest, RepeatingCallbackBasicTest) {
398 RepeatingCallback<int(int)> c0 = BindRepeating(&Sum, 1, 2, 4, 8, 16);
400 // RepeatingCallback can run via a lvalue-reference.
401 EXPECT_EQ(63, c0.Run(32));
403 // It is valid to call a RepeatingCallback more than once.
404 EXPECT_EQ(54, c0.Run(23));
406 // BindRepeating can handle a RepeatingCallback as the target functor.
407 RepeatingCallback<int()> c1 = BindRepeating(c0, 11);
409 // RepeatingCallback can run via a rvalue-reference.
410 EXPECT_EQ(42, std::move(c1).Run());
412 // BindRepeating can handle a rvalue-reference of RepeatingCallback.
413 EXPECT_EQ(32, BindRepeating(std::move(c0), 1).Run());
416 TEST_F(BindTest, OnceCallbackBasicTest) {
417 OnceCallback<int(int)> c0 = BindOnce(&Sum, 1, 2, 4, 8, 16);
419 // OnceCallback can run via a rvalue-reference.
420 EXPECT_EQ(63, std::move(c0).Run(32));
422 // After running via the rvalue-reference, the value of the OnceCallback
423 // is undefined. The implementation simply clears the instance after the
425 EXPECT_TRUE(c0.is_null());
427 c0 = BindOnce(&Sum, 2, 3, 5, 7, 11);
429 // BindOnce can handle a rvalue-reference of OnceCallback as the target
431 OnceCallback<int()> c1 = BindOnce(std::move(c0), 13);
432 EXPECT_EQ(41, std::move(c1).Run());
434 RepeatingCallback<int(int)> c2 = BindRepeating(&Sum, 2, 3, 5, 7, 11);
435 EXPECT_EQ(41, BindOnce(c2, 13).Run());
438 // IgnoreResult adapter test.
439 // - Function with return value.
440 // - Method with return value.
441 // - Const Method with return.
442 // - Method with return value bound to WeakPtr<>.
443 // - Const Method with return bound to WeakPtr<>.
444 TEST_F(BindTest, IgnoreResultForRepeating) {
445 EXPECT_CALL(static_func_mock_, IntMethod0()).WillOnce(Return(1337));
446 EXPECT_CALL(has_ref_, AddRef()).Times(2);
447 EXPECT_CALL(has_ref_, Release()).Times(2);
448 EXPECT_CALL(has_ref_, HasAtLeastOneRef()).WillRepeatedly(Return(true));
449 EXPECT_CALL(has_ref_, IntMethod0()).WillOnce(Return(10));
450 EXPECT_CALL(has_ref_, IntConstMethod0()).WillOnce(Return(11));
451 EXPECT_CALL(no_ref_, IntMethod0()).WillOnce(Return(12));
452 EXPECT_CALL(no_ref_, IntConstMethod0()).WillOnce(Return(13));
454 RepeatingClosure normal_func_cb = BindRepeating(IgnoreResult(&IntFunc0));
455 normal_func_cb.Run();
457 RepeatingClosure non_void_method_cb =
458 BindRepeating(IgnoreResult(&HasRef::IntMethod0), &has_ref_);
459 non_void_method_cb.Run();
461 RepeatingClosure non_void_const_method_cb =
462 BindRepeating(IgnoreResult(&HasRef::IntConstMethod0), &has_ref_);
463 non_void_const_method_cb.Run();
465 WeakPtrFactory<NoRef> weak_factory(&no_ref_);
466 WeakPtrFactory<const NoRef> const_weak_factory(const_no_ref_ptr_);
468 RepeatingClosure non_void_weak_method_cb =
469 BindRepeating(IgnoreResult(&NoRef::IntMethod0),
470 weak_factory.GetWeakPtr());
471 non_void_weak_method_cb.Run();
473 RepeatingClosure non_void_weak_const_method_cb =
474 BindRepeating(IgnoreResult(&NoRef::IntConstMethod0),
475 weak_factory.GetWeakPtr());
476 non_void_weak_const_method_cb.Run();
478 weak_factory.InvalidateWeakPtrs();
479 non_void_weak_const_method_cb.Run();
480 non_void_weak_method_cb.Run();
483 TEST_F(BindTest, IgnoreResultForOnce) {
484 EXPECT_CALL(static_func_mock_, IntMethod0()).WillOnce(Return(1337));
485 EXPECT_CALL(has_ref_, AddRef()).Times(2);
486 EXPECT_CALL(has_ref_, Release()).Times(2);
487 EXPECT_CALL(has_ref_, HasAtLeastOneRef()).WillRepeatedly(Return(true));
488 EXPECT_CALL(has_ref_, IntMethod0()).WillOnce(Return(10));
489 EXPECT_CALL(has_ref_, IntConstMethod0()).WillOnce(Return(11));
491 OnceClosure normal_func_cb = BindOnce(IgnoreResult(&IntFunc0));
492 std::move(normal_func_cb).Run();
494 OnceClosure non_void_method_cb =
495 BindOnce(IgnoreResult(&HasRef::IntMethod0), &has_ref_);
496 std::move(non_void_method_cb).Run();
498 OnceClosure non_void_const_method_cb =
499 BindOnce(IgnoreResult(&HasRef::IntConstMethod0), &has_ref_);
500 std::move(non_void_const_method_cb).Run();
502 WeakPtrFactory<NoRef> weak_factory(&no_ref_);
503 WeakPtrFactory<const NoRef> const_weak_factory(const_no_ref_ptr_);
505 OnceClosure non_void_weak_method_cb =
506 BindOnce(IgnoreResult(&NoRef::IntMethod0),
507 weak_factory.GetWeakPtr());
508 OnceClosure non_void_weak_const_method_cb =
509 BindOnce(IgnoreResult(&NoRef::IntConstMethod0),
510 weak_factory.GetWeakPtr());
512 weak_factory.InvalidateWeakPtrs();
513 std::move(non_void_weak_const_method_cb).Run();
514 std::move(non_void_weak_method_cb).Run();
517 TEST_F(BindTest, IgnoreResultForRepeatingCallback) {
519 RepeatingCallback<int(int)> cb = BindRepeating(
520 [](std::string* s, int i) {
521 *s += "Run" + base::NumberToString(i);
525 RepeatingCallback<void(int)> noreturn = BindRepeating(IgnoreResult(cb));
527 EXPECT_EQ(s, "Run2");
530 TEST_F(BindTest, IgnoreResultForOnceCallback) {
532 OnceCallback<int(int)> cb = BindOnce(
533 [](std::string* s, int i) {
534 *s += "Run" + base::NumberToString(i);
538 OnceCallback<void(int)> noreturn = BindOnce(IgnoreResult(std::move(cb)));
539 std::move(noreturn).Run(2);
540 EXPECT_EQ(s, "Run2");
543 void SetFromRef(int& ref) {
549 TEST_F(BindTest, BindOnceWithNonConstRef) {
552 // Mutates `v` because it's not bound to callback instead it's forwarded by
554 auto cb1 = BindOnce(SetFromRef);
555 std::move(cb1).Run(v);
559 // Mutates `v` through std::reference_wrapper bound to callback.
560 auto cb2 = BindOnce(SetFromRef, std::ref(v));
561 std::move(cb2).Run();
565 // Everything past here following will make a copy of the argument. The copy
566 // will be mutated and leave `v` unmodified.
567 auto cb3 = BindOnce(SetFromRef, base::OwnedRef(v));
568 std::move(cb3).Run();
572 auto cb4 = BindOnce(SetFromRef, base::OwnedRef(ref));
573 std::move(cb4).Run();
577 auto cb5 = BindOnce(SetFromRef, base::OwnedRef(cv));
578 std::move(cb5).Run();
582 auto cb6 = BindOnce(SetFromRef, base::OwnedRef(cref));
583 std::move(cb6).Run();
586 auto cb7 = BindOnce(SetFromRef, base::OwnedRef(1));
587 std::move(cb7).Run();
590 TEST_F(BindTest, BindRepeatingWithNonConstRef) {
593 // Mutates `v` because it's not bound to callback instead it's forwarded by
595 auto cb1 = BindRepeating(SetFromRef);
596 std::move(cb1).Run(v);
600 // Mutates `v` through std::reference_wrapper bound to callback.
601 auto cb2 = BindRepeating(SetFromRef, std::ref(v));
602 std::move(cb2).Run();
606 // Everything past here following will make a copy of the argument. The copy
607 // will be mutated and leave `v` unmodified.
608 auto cb3 = BindRepeating(SetFromRef, base::OwnedRef(v));
609 std::move(cb3).Run();
613 auto cb4 = BindRepeating(SetFromRef, base::OwnedRef(ref));
614 std::move(cb4).Run();
618 auto cb5 = BindRepeating(SetFromRef, base::OwnedRef(cv));
619 std::move(cb5).Run();
623 auto cb6 = BindRepeating(SetFromRef, base::OwnedRef(cref));
624 std::move(cb6).Run();
627 auto cb7 = BindRepeating(SetFromRef, base::OwnedRef(1));
628 std::move(cb7).Run();
631 // Functions that take reference parameters.
632 // - Forced reference parameter type still stores a copy.
633 // - Forced const reference parameter type still stores a copy.
634 TEST_F(BindTest, ReferenceArgumentBindingForRepeating) {
637 const int& const_ref_n = n;
639 RepeatingCallback<int()> ref_copies_cb = BindRepeating(&Identity, ref_n);
640 EXPECT_EQ(n, ref_copies_cb.Run());
642 EXPECT_EQ(n - 1, ref_copies_cb.Run());
644 RepeatingCallback<int()> const_ref_copies_cb =
645 BindRepeating(&Identity, const_ref_n);
646 EXPECT_EQ(n, const_ref_copies_cb.Run());
648 EXPECT_EQ(n - 1, const_ref_copies_cb.Run());
651 TEST_F(BindTest, ReferenceArgumentBindingForOnce) {
654 const int& const_ref_n = n;
656 OnceCallback<int()> ref_copies_cb = BindOnce(&Identity, ref_n);
658 EXPECT_EQ(n - 1, std::move(ref_copies_cb).Run());
660 OnceCallback<int()> const_ref_copies_cb =
661 BindOnce(&Identity, const_ref_n);
663 EXPECT_EQ(n - 1, std::move(const_ref_copies_cb).Run());
666 // Check that we can pass in arrays and have them be stored as a pointer.
667 // - Array of values stores a pointer.
668 // - Array of const values stores a pointer.
669 TEST_F(BindTest, ArrayArgumentBindingForRepeating) {
670 int array[4] = {1, 1, 1, 1};
671 const int (*const_array_ptr)[4] = &array;
673 RepeatingCallback<int()> array_cb = BindRepeating(&ArrayGet, array, 1);
674 EXPECT_EQ(1, array_cb.Run());
676 RepeatingCallback<int()> const_array_cb =
677 BindRepeating(&ArrayGet, *const_array_ptr, 1);
678 EXPECT_EQ(1, const_array_cb.Run());
681 EXPECT_EQ(3, array_cb.Run());
682 EXPECT_EQ(3, const_array_cb.Run());
685 TEST_F(BindTest, ArrayArgumentBindingForOnce) {
686 int array[4] = {1, 1, 1, 1};
687 const int (*const_array_ptr)[4] = &array;
689 OnceCallback<int()> array_cb = BindOnce(&ArrayGet, array, 1);
690 OnceCallback<int()> const_array_cb =
691 BindOnce(&ArrayGet, *const_array_ptr, 1);
694 EXPECT_EQ(3, std::move(array_cb).Run());
695 EXPECT_EQ(3, std::move(const_array_cb).Run());
698 // WeakPtr() support.
699 // - Method bound to WeakPtr<> to non-const object.
700 // - Const method bound to WeakPtr<> to non-const object.
701 // - Const method bound to WeakPtr<> to const object.
702 // - Normal Function with WeakPtr<> as P1 can have return type and is
704 TEST_F(BindTest, WeakPtrForRepeating) {
705 EXPECT_CALL(no_ref_, VoidMethod0());
706 EXPECT_CALL(no_ref_, VoidConstMethod0()).Times(2);
708 WeakPtrFactory<NoRef> weak_factory(&no_ref_);
709 WeakPtrFactory<const NoRef> const_weak_factory(const_no_ref_ptr_);
711 RepeatingClosure method_cb =
712 BindRepeating(&NoRef::VoidMethod0, weak_factory.GetWeakPtr());
715 RepeatingClosure const_method_cb =
716 BindRepeating(&NoRef::VoidConstMethod0, const_weak_factory.GetWeakPtr());
717 const_method_cb.Run();
719 RepeatingClosure const_method_const_ptr_cb =
720 BindRepeating(&NoRef::VoidConstMethod0, const_weak_factory.GetWeakPtr());
721 const_method_const_ptr_cb.Run();
723 RepeatingCallback<int(int)> normal_func_cb =
724 BindRepeating(&FunctionWithWeakFirstParam, weak_factory.GetWeakPtr());
725 EXPECT_EQ(1, normal_func_cb.Run(1));
727 weak_factory.InvalidateWeakPtrs();
728 const_weak_factory.InvalidateWeakPtrs();
731 const_method_cb.Run();
732 const_method_const_ptr_cb.Run();
734 // Still runs even after the pointers are invalidated.
735 EXPECT_EQ(2, normal_func_cb.Run(2));
738 TEST_F(BindTest, WeakPtrForOnce) {
739 WeakPtrFactory<NoRef> weak_factory(&no_ref_);
740 WeakPtrFactory<const NoRef> const_weak_factory(const_no_ref_ptr_);
742 OnceClosure method_cb =
743 BindOnce(&NoRef::VoidMethod0, weak_factory.GetWeakPtr());
744 OnceClosure const_method_cb =
745 BindOnce(&NoRef::VoidConstMethod0, const_weak_factory.GetWeakPtr());
746 OnceClosure const_method_const_ptr_cb =
747 BindOnce(&NoRef::VoidConstMethod0, const_weak_factory.GetWeakPtr());
748 OnceCallback<int(int)> normal_func_cb =
749 BindOnce(&FunctionWithWeakFirstParam, weak_factory.GetWeakPtr());
751 weak_factory.InvalidateWeakPtrs();
752 const_weak_factory.InvalidateWeakPtrs();
754 std::move(method_cb).Run();
755 std::move(const_method_cb).Run();
756 std::move(const_method_const_ptr_cb).Run();
758 // Still runs even after the pointers are invalidated.
759 EXPECT_EQ(2, std::move(normal_func_cb).Run(2));
762 // std::cref() wrapper support.
763 // - Binding w/o std::cref takes a copy.
764 // - Binding a std::cref takes a reference.
765 // - Binding std::cref to a function std::cref does not copy on invoke.
766 TEST_F(BindTest, StdCrefForRepeating) {
769 RepeatingCallback<int()> copy_cb = BindRepeating(&Identity, n);
770 RepeatingCallback<int()> const_ref_cb =
771 BindRepeating(&Identity, std::cref(n));
772 EXPECT_EQ(n, copy_cb.Run());
773 EXPECT_EQ(n, const_ref_cb.Run());
775 EXPECT_EQ(n - 1, copy_cb.Run());
776 EXPECT_EQ(n, const_ref_cb.Run());
780 int move_constructs = 0;
781 int move_assigns = 0;
782 CopyMoveCounter counter(&copies, &assigns, &move_constructs, &move_assigns);
783 RepeatingCallback<int()> all_const_ref_cb =
784 BindRepeating(&GetCopies, std::cref(counter));
785 EXPECT_EQ(0, all_const_ref_cb.Run());
786 EXPECT_EQ(0, copies);
787 EXPECT_EQ(0, assigns);
788 EXPECT_EQ(0, move_constructs);
789 EXPECT_EQ(0, move_assigns);
792 TEST_F(BindTest, StdCrefForOnce) {
795 OnceCallback<int()> copy_cb = BindOnce(&Identity, n);
796 OnceCallback<int()> const_ref_cb = BindOnce(&Identity, std::cref(n));
798 EXPECT_EQ(n - 1, std::move(copy_cb).Run());
799 EXPECT_EQ(n, std::move(const_ref_cb).Run());
803 int move_constructs = 0;
804 int move_assigns = 0;
805 CopyMoveCounter counter(&copies, &assigns, &move_constructs, &move_assigns);
806 OnceCallback<int()> all_const_ref_cb =
807 BindOnce(&GetCopies, std::cref(counter));
808 EXPECT_EQ(0, std::move(all_const_ref_cb).Run());
809 EXPECT_EQ(0, copies);
810 EXPECT_EQ(0, assigns);
811 EXPECT_EQ(0, move_constructs);
812 EXPECT_EQ(0, move_assigns);
815 // Test Owned() support.
816 TEST_F(BindTest, OwnedForRepeatingRawPtr) {
818 DeleteCounter* counter = new DeleteCounter(&deletes);
820 // If we don't capture, delete happens on Callback destruction/reset.
821 // return the same value.
822 RepeatingCallback<DeleteCounter*()> no_capture_cb =
823 BindRepeating(&PolymorphicIdentity<DeleteCounter*>, Owned(counter));
824 ASSERT_EQ(counter, no_capture_cb.Run());
825 ASSERT_EQ(counter, no_capture_cb.Run());
826 EXPECT_EQ(0, deletes);
827 no_capture_cb.Reset(); // This should trigger a delete.
828 EXPECT_EQ(1, deletes);
831 counter = new DeleteCounter(&deletes);
832 RepeatingClosure own_object_cb =
833 BindRepeating(&DeleteCounter::VoidMethod0, Owned(counter));
835 EXPECT_EQ(0, deletes);
836 own_object_cb.Reset();
837 EXPECT_EQ(1, deletes);
840 TEST_F(BindTest, OwnedForOnceRawPtr) {
842 DeleteCounter* counter = new DeleteCounter(&deletes);
844 // If we don't capture, delete happens on Callback destruction/reset.
845 // return the same value.
846 OnceCallback<DeleteCounter*()> no_capture_cb =
847 BindOnce(&PolymorphicIdentity<DeleteCounter*>, Owned(counter));
848 EXPECT_EQ(0, deletes);
849 no_capture_cb.Reset(); // This should trigger a delete.
850 EXPECT_EQ(1, deletes);
853 counter = new DeleteCounter(&deletes);
854 OnceClosure own_object_cb =
855 BindOnce(&DeleteCounter::VoidMethod0, Owned(counter));
856 EXPECT_EQ(0, deletes);
857 own_object_cb.Reset();
858 EXPECT_EQ(1, deletes);
861 TEST_F(BindTest, OwnedForRepeatingUniquePtr) {
863 auto counter = std::make_unique<DeleteCounter>(&deletes);
864 DeleteCounter* raw_counter = counter.get();
866 // If we don't capture, delete happens on Callback destruction/reset.
867 // return the same value.
868 RepeatingCallback<DeleteCounter*()> no_capture_cb = BindRepeating(
869 &PolymorphicIdentity<DeleteCounter*>, Owned(std::move(counter)));
870 ASSERT_EQ(raw_counter, no_capture_cb.Run());
871 ASSERT_EQ(raw_counter, no_capture_cb.Run());
872 EXPECT_EQ(0, deletes);
873 no_capture_cb.Reset(); // This should trigger a delete.
874 EXPECT_EQ(1, deletes);
877 counter = std::make_unique<DeleteCounter>(&deletes);
878 RepeatingClosure own_object_cb =
879 BindRepeating(&DeleteCounter::VoidMethod0, Owned(std::move(counter)));
881 EXPECT_EQ(0, deletes);
882 own_object_cb.Reset();
883 EXPECT_EQ(1, deletes);
886 TEST_F(BindTest, OwnedForOnceUniquePtr) {
888 auto counter = std::make_unique<DeleteCounter>(&deletes);
890 // If we don't capture, delete happens on Callback destruction/reset.
891 // return the same value.
892 OnceCallback<DeleteCounter*()> no_capture_cb =
893 BindOnce(&PolymorphicIdentity<DeleteCounter*>, Owned(std::move(counter)));
894 EXPECT_EQ(0, deletes);
895 no_capture_cb.Reset(); // This should trigger a delete.
896 EXPECT_EQ(1, deletes);
899 counter = std::make_unique<DeleteCounter>(&deletes);
900 OnceClosure own_object_cb =
901 BindOnce(&DeleteCounter::VoidMethod0, Owned(std::move(counter)));
902 EXPECT_EQ(0, deletes);
903 own_object_cb.Reset();
904 EXPECT_EQ(1, deletes);
908 TEST_F(BindTest, OwnedRefForCounter) {
910 RepeatingCallback<int()> counter_callback =
911 BindRepeating([](int& counter) { return ++counter; }, OwnedRef(counter));
913 EXPECT_EQ(1, counter_callback.Run());
914 EXPECT_EQ(2, counter_callback.Run());
915 EXPECT_EQ(3, counter_callback.Run());
916 EXPECT_EQ(4, counter_callback.Run());
918 EXPECT_EQ(0, counter); // counter should remain unchanged.
921 TEST_F(BindTest, OwnedRefForIgnoringArguments) {
922 OnceCallback<std::string(std::string)> echo_callback =
923 BindOnce([](int& ignore, std::string s) { return s; }, OwnedRef(0));
925 EXPECT_EQ("Hello World", std::move(echo_callback).Run("Hello World"));
928 template <typename T>
929 class BindVariantsTest : public ::testing::Test {
932 struct RepeatingTestConfig {
933 template <typename Signature>
934 using CallbackType = RepeatingCallback<Signature>;
935 using ClosureType = RepeatingClosure;
937 template <typename F, typename... Args>
938 static CallbackType<internal::MakeUnboundRunType<F, Args...>> Bind(
941 return BindRepeating(std::forward<F>(f), std::forward<Args>(args)...);
945 struct OnceTestConfig {
946 template <typename Signature>
947 using CallbackType = OnceCallback<Signature>;
948 using ClosureType = OnceClosure;
950 template <typename F, typename... Args>
951 static CallbackType<internal::MakeUnboundRunType<F, Args...>> Bind(
954 return BindOnce(std::forward<F>(f), std::forward<Args>(args)...);
958 using BindVariantsTestConfig = ::testing::Types<
959 RepeatingTestConfig, OnceTestConfig>;
960 TYPED_TEST_SUITE(BindVariantsTest, BindVariantsTestConfig);
962 template <typename TypeParam, typename Signature>
963 using CallbackType = typename TypeParam::template CallbackType<Signature>;
965 // Function type support.
966 // - Normal function.
967 // - Normal function bound with non-refcounted first argument.
968 // - Method bound to non-const object.
969 // - Method bound to scoped_refptr.
970 // - Const method bound to non-const object.
971 // - Const method bound to const object.
972 // - Derived classes can be used with pointers to non-virtual base functions.
973 // - Derived classes can be used with pointers to virtual base functions (and
974 // preserve virtual dispatch).
975 TYPED_TEST(BindVariantsTest, FunctionTypeSupport) {
976 using ClosureType = typename TypeParam::ClosureType;
978 StrictMock<HasRef> has_ref;
979 StrictMock<NoRef> no_ref;
980 StrictMock<NoRef> static_func_mock;
981 const HasRef* const_has_ref_ptr = &has_ref;
982 g_func_mock_ptr = &static_func_mock;
984 EXPECT_CALL(static_func_mock, VoidMethod0());
985 EXPECT_CALL(has_ref, AddRef()).Times(4);
986 EXPECT_CALL(has_ref, Release()).Times(4);
987 EXPECT_CALL(has_ref, HasAtLeastOneRef()).WillRepeatedly(Return(true));
988 EXPECT_CALL(has_ref, VoidMethod0()).Times(2);
989 EXPECT_CALL(has_ref, VoidConstMethod0()).Times(2);
991 ClosureType normal_cb = TypeParam::Bind(&VoidFunc0);
992 CallbackType<TypeParam, NoRef*()> normal_non_refcounted_cb =
993 TypeParam::Bind(&PolymorphicIdentity<NoRef*>, &no_ref);
994 std::move(normal_cb).Run();
995 EXPECT_EQ(&no_ref, std::move(normal_non_refcounted_cb).Run());
997 ClosureType method_cb = TypeParam::Bind(&HasRef::VoidMethod0, &has_ref);
998 ClosureType method_refptr_cb =
999 TypeParam::Bind(&HasRef::VoidMethod0, WrapRefCounted(&has_ref));
1000 ClosureType const_method_nonconst_obj_cb =
1001 TypeParam::Bind(&HasRef::VoidConstMethod0, &has_ref);
1002 ClosureType const_method_const_obj_cb =
1003 TypeParam::Bind(&HasRef::VoidConstMethod0, const_has_ref_ptr);
1004 std::move(method_cb).Run();
1005 std::move(method_refptr_cb).Run();
1006 std::move(const_method_nonconst_obj_cb).Run();
1007 std::move(const_method_const_obj_cb).Run();
1011 ClosureType virtual_set_cb = TypeParam::Bind(&Parent::VirtualSet, &child);
1012 std::move(virtual_set_cb).Run();
1013 EXPECT_EQ(kChildValue, child.value);
1016 ClosureType non_virtual_set_cb =
1017 TypeParam::Bind(&Parent::NonVirtualSet, &child);
1018 std::move(non_virtual_set_cb).Run();
1019 EXPECT_EQ(kParentValue, child.value);
1022 // Return value support.
1023 // - Function with return value.
1024 // - Method with return value.
1025 // - Const method with return value.
1026 // - Move-only return value.
1027 TYPED_TEST(BindVariantsTest, ReturnValues) {
1028 StrictMock<NoRef> static_func_mock;
1029 StrictMock<HasRef> has_ref;
1030 g_func_mock_ptr = &static_func_mock;
1031 const HasRef* const_has_ref_ptr = &has_ref;
1033 EXPECT_CALL(static_func_mock, IntMethod0()).WillOnce(Return(1337));
1034 EXPECT_CALL(has_ref, AddRef()).Times(4);
1035 EXPECT_CALL(has_ref, Release()).Times(4);
1036 EXPECT_CALL(has_ref, HasAtLeastOneRef()).WillRepeatedly(Return(true));
1037 EXPECT_CALL(has_ref, IntMethod0()).WillOnce(Return(31337));
1038 EXPECT_CALL(has_ref, IntConstMethod0())
1039 .WillOnce(Return(41337))
1040 .WillOnce(Return(51337));
1041 EXPECT_CALL(has_ref, UniquePtrMethod0())
1042 .WillOnce(Return(ByMove(std::make_unique<int>(42))));
1044 CallbackType<TypeParam, int()> normal_cb = TypeParam::Bind(&IntFunc0);
1045 CallbackType<TypeParam, int()> method_cb =
1046 TypeParam::Bind(&HasRef::IntMethod0, &has_ref);
1047 CallbackType<TypeParam, int()> const_method_nonconst_obj_cb =
1048 TypeParam::Bind(&HasRef::IntConstMethod0, &has_ref);
1049 CallbackType<TypeParam, int()> const_method_const_obj_cb =
1050 TypeParam::Bind(&HasRef::IntConstMethod0, const_has_ref_ptr);
1051 CallbackType<TypeParam, std::unique_ptr<int>()> move_only_rv_cb =
1052 TypeParam::Bind(&HasRef::UniquePtrMethod0, &has_ref);
1053 EXPECT_EQ(1337, std::move(normal_cb).Run());
1054 EXPECT_EQ(31337, std::move(method_cb).Run());
1055 EXPECT_EQ(41337, std::move(const_method_nonconst_obj_cb).Run());
1056 EXPECT_EQ(51337, std::move(const_method_const_obj_cb).Run());
1057 EXPECT_EQ(42, *std::move(move_only_rv_cb).Run());
1060 // Argument binding tests.
1061 // - Argument binding to primitive.
1062 // - Argument binding to primitive pointer.
1063 // - Argument binding to a literal integer.
1064 // - Argument binding to a literal string.
1065 // - Argument binding with template function.
1066 // - Argument binding to an object.
1067 // - Argument binding to pointer to incomplete type.
1068 // - Argument gets type converted.
1069 // - Pointer argument gets converted.
1070 // - Const Reference forces conversion.
1071 TYPED_TEST(BindVariantsTest, ArgumentBinding) {
1074 EXPECT_EQ(n, TypeParam::Bind(&Identity, n).Run());
1075 EXPECT_EQ(&n, TypeParam::Bind(&PolymorphicIdentity<int*>, &n).Run());
1076 EXPECT_EQ(3, TypeParam::Bind(&Identity, 3).Run());
1077 EXPECT_STREQ("hi", TypeParam::Bind(&CStringIdentity, "hi").Run());
1078 EXPECT_EQ(4, TypeParam::Bind(&PolymorphicIdentity<int>, 4).Run());
1082 EXPECT_EQ(5, TypeParam::Bind(&UnwrapNoRefParent, p).Run());
1084 IncompleteType* incomplete_ptr = reinterpret_cast<IncompleteType*>(123);
1085 EXPECT_EQ(incomplete_ptr,
1086 TypeParam::Bind(&PolymorphicIdentity<IncompleteType*>,
1087 incomplete_ptr).Run());
1091 EXPECT_EQ(6, TypeParam::Bind(&UnwrapNoRefParent, c).Run());
1094 EXPECT_EQ(7, TypeParam::Bind(&UnwrapNoRefParentPtr, &c).Run());
1097 EXPECT_EQ(8, TypeParam::Bind(&UnwrapNoRefParentConstRef, c).Run());
1100 // Unbound argument type support tests.
1102 // - Unbound pointer.
1103 // - Unbound reference.
1104 // - Unbound const reference.
1105 // - Unbound unsized array.
1106 // - Unbound sized array.
1107 // - Unbound array-of-arrays.
1108 TYPED_TEST(BindVariantsTest, UnboundArgumentTypeSupport) {
1109 CallbackType<TypeParam, void(int)> unbound_value_cb =
1110 TypeParam::Bind(&VoidPolymorphic<int>::Run);
1111 CallbackType<TypeParam, void(int*)> unbound_pointer_cb =
1112 TypeParam::Bind(&VoidPolymorphic<int*>::Run);
1113 CallbackType<TypeParam, void(int&)> unbound_ref_cb =
1114 TypeParam::Bind(&VoidPolymorphic<int&>::Run);
1115 CallbackType<TypeParam, void(const int&)> unbound_const_ref_cb =
1116 TypeParam::Bind(&VoidPolymorphic<const int&>::Run);
1117 CallbackType<TypeParam, void(int[])> unbound_unsized_array_cb =
1118 TypeParam::Bind(&VoidPolymorphic<int[]>::Run);
1119 CallbackType<TypeParam, void(int[2])> unbound_sized_array_cb =
1120 TypeParam::Bind(&VoidPolymorphic<int[2]>::Run);
1121 CallbackType<TypeParam, void(int[][2])> unbound_array_of_arrays_cb =
1122 TypeParam::Bind(&VoidPolymorphic<int[][2]>::Run);
1123 CallbackType<TypeParam, void(int&)> unbound_ref_with_bound_arg =
1124 TypeParam::Bind(&VoidPolymorphic<int, int&>::Run, 1);
1127 // Function with unbound reference parameter.
1128 // - Original parameter is modified by callback.
1129 TYPED_TEST(BindVariantsTest, UnboundReferenceSupport) {
1131 CallbackType<TypeParam, void(int&)> unbound_ref_cb =
1132 TypeParam::Bind(&RefArgSet);
1133 std::move(unbound_ref_cb).Run(n);
1137 // Unretained() wrapper support.
1138 // - Method bound to Unretained() non-const object.
1139 // - Const method bound to Unretained() non-const object.
1140 // - Const method bound to Unretained() const object.
1141 TYPED_TEST(BindVariantsTest, Unretained) {
1142 StrictMock<NoRef> no_ref;
1143 const NoRef* const_no_ref_ptr = &no_ref;
1145 EXPECT_CALL(no_ref, VoidMethod0());
1146 EXPECT_CALL(no_ref, VoidConstMethod0()).Times(2);
1148 TypeParam::Bind(&NoRef::VoidMethod0, Unretained(&no_ref)).Run();
1149 TypeParam::Bind(&NoRef::VoidConstMethod0, Unretained(&no_ref)).Run();
1150 TypeParam::Bind(&NoRef::VoidConstMethod0, Unretained(const_no_ref_ptr)).Run();
1153 TYPED_TEST(BindVariantsTest, ScopedRefptr) {
1154 StrictMock<HasRef> has_ref;
1155 EXPECT_CALL(has_ref, AddRef()).Times(1);
1156 EXPECT_CALL(has_ref, Release()).Times(1);
1157 EXPECT_CALL(has_ref, HasAtLeastOneRef()).WillRepeatedly(Return(true));
1159 const scoped_refptr<HasRef> refptr(&has_ref);
1160 CallbackType<TypeParam, int()> scoped_refptr_const_ref_cb = TypeParam::Bind(
1161 &FunctionWithScopedRefptrFirstParam, std::cref(refptr), 1);
1162 EXPECT_EQ(1, std::move(scoped_refptr_const_ref_cb).Run());
1165 TYPED_TEST(BindVariantsTest, UniquePtrReceiver) {
1166 std::unique_ptr<StrictMock<NoRef>> no_ref(new StrictMock<NoRef>);
1167 EXPECT_CALL(*no_ref, VoidMethod0()).Times(1);
1168 TypeParam::Bind(&NoRef::VoidMethod0, std::move(no_ref)).Run();
1171 // Tests for Passed() wrapper support:
1172 // - Passed() can be constructed from a pointer to scoper.
1173 // - Passed() can be constructed from a scoper rvalue.
1174 // - Using Passed() gives Callback Ownership.
1175 // - Ownership is transferred from Callback to callee on the first Run().
1176 // - Callback supports unbound arguments.
1177 template <typename T>
1178 class BindMoveOnlyTypeTest : public ::testing::Test {
1181 struct CustomDeleter {
1182 void operator()(DeleteCounter* c) { delete c; }
1185 using MoveOnlyTypesToTest =
1186 ::testing::Types<std::unique_ptr<DeleteCounter>,
1187 std::unique_ptr<DeleteCounter, CustomDeleter>>;
1188 TYPED_TEST_SUITE(BindMoveOnlyTypeTest, MoveOnlyTypesToTest);
1190 TYPED_TEST(BindMoveOnlyTypeTest, PassedToBoundCallback) {
1193 TypeParam ptr(new DeleteCounter(&deletes));
1194 RepeatingCallback<TypeParam()> callback =
1195 BindRepeating(&PassThru<TypeParam>, Passed(&ptr));
1196 EXPECT_FALSE(ptr.get());
1197 EXPECT_EQ(0, deletes);
1199 // If we never invoke the Callback, it retains ownership and deletes.
1201 EXPECT_EQ(1, deletes);
1204 TYPED_TEST(BindMoveOnlyTypeTest, PassedWithRvalue) {
1206 RepeatingCallback<TypeParam()> callback = BindRepeating(
1207 &PassThru<TypeParam>, Passed(TypeParam(new DeleteCounter(&deletes))));
1208 EXPECT_EQ(0, deletes);
1210 // If we never invoke the Callback, it retains ownership and deletes.
1212 EXPECT_EQ(1, deletes);
1215 // Check that ownership can be transferred back out.
1216 TYPED_TEST(BindMoveOnlyTypeTest, ReturnMoveOnlyType) {
1218 DeleteCounter* counter = new DeleteCounter(&deletes);
1219 RepeatingCallback<TypeParam()> callback =
1220 BindRepeating(&PassThru<TypeParam>, Passed(TypeParam(counter)));
1221 TypeParam result = callback.Run();
1222 ASSERT_EQ(counter, result.get());
1223 EXPECT_EQ(0, deletes);
1225 // Resetting does not delete since ownership was transferred.
1227 EXPECT_EQ(0, deletes);
1229 // Ensure that we actually did get ownership.
1231 EXPECT_EQ(1, deletes);
1234 TYPED_TEST(BindMoveOnlyTypeTest, UnboundForwarding) {
1236 TypeParam ptr(new DeleteCounter(&deletes));
1237 // Test unbound argument forwarding.
1238 RepeatingCallback<TypeParam(TypeParam)> cb_unbound =
1239 BindRepeating(&PassThru<TypeParam>);
1240 cb_unbound.Run(std::move(ptr));
1241 EXPECT_EQ(1, deletes);
1244 void VerifyVector(const std::vector<std::unique_ptr<int>>& v) {
1245 ASSERT_EQ(1u, v.size());
1246 EXPECT_EQ(12345, *v[0]);
1249 std::vector<std::unique_ptr<int>> AcceptAndReturnMoveOnlyVector(
1250 std::vector<std::unique_ptr<int>> v) {
1255 // Test that a vector containing move-only types can be used with Callback.
1256 TEST_F(BindTest, BindMoveOnlyVector) {
1257 using MoveOnlyVector = std::vector<std::unique_ptr<int>>;
1260 v.push_back(std::make_unique<int>(12345));
1262 // Early binding should work:
1263 base::RepeatingCallback<MoveOnlyVector()> bound_cb =
1264 base::BindRepeating(&AcceptAndReturnMoveOnlyVector, Passed(&v));
1265 MoveOnlyVector intermediate_result = bound_cb.Run();
1266 VerifyVector(intermediate_result);
1268 // As should passing it as an argument to Run():
1269 base::RepeatingCallback<MoveOnlyVector(MoveOnlyVector)> unbound_cb =
1270 base::BindRepeating(&AcceptAndReturnMoveOnlyVector);
1271 MoveOnlyVector final_result = unbound_cb.Run(std::move(intermediate_result));
1272 VerifyVector(final_result);
1275 // Argument copy-constructor usage for non-reference copy-only parameters.
1276 // - Bound arguments are only copied once.
1277 // - Forwarded arguments are only copied once.
1278 // - Forwarded arguments with coercions are only copied twice (once for the
1279 // coercion, and one for the final dispatch).
1280 TEST_F(BindTest, ArgumentCopies) {
1284 CopyCounter counter(&copies, &assigns);
1285 BindRepeating(&VoidPolymorphic<CopyCounter>::Run, counter);
1286 EXPECT_EQ(1, copies);
1287 EXPECT_EQ(0, assigns);
1291 BindRepeating(&VoidPolymorphic<CopyCounter>::Run,
1292 CopyCounter(&copies, &assigns));
1293 EXPECT_EQ(1, copies);
1294 EXPECT_EQ(0, assigns);
1298 BindRepeating(&VoidPolymorphic<CopyCounter>::Run).Run(counter);
1299 EXPECT_EQ(2, copies);
1300 EXPECT_EQ(0, assigns);
1304 BindRepeating(&VoidPolymorphic<CopyCounter>::Run)
1305 .Run(CopyCounter(&copies, &assigns));
1306 EXPECT_EQ(1, copies);
1307 EXPECT_EQ(0, assigns);
1311 DerivedCopyMoveCounter derived(&copies, &assigns, nullptr, nullptr);
1312 BindRepeating(&VoidPolymorphic<CopyCounter>::Run).Run(CopyCounter(derived));
1313 EXPECT_EQ(2, copies);
1314 EXPECT_EQ(0, assigns);
1318 BindRepeating(&VoidPolymorphic<CopyCounter>::Run)
1320 DerivedCopyMoveCounter(&copies, &assigns, nullptr, nullptr)));
1321 EXPECT_EQ(2, copies);
1322 EXPECT_EQ(0, assigns);
1325 // Argument move-constructor usage for move-only parameters.
1326 // - Bound arguments passed by move are not copied.
1327 TEST_F(BindTest, ArgumentMoves) {
1328 int move_constructs = 0;
1329 int move_assigns = 0;
1331 BindRepeating(&VoidPolymorphic<const MoveCounter&>::Run,
1332 MoveCounter(&move_constructs, &move_assigns));
1333 EXPECT_EQ(1, move_constructs);
1334 EXPECT_EQ(0, move_assigns);
1336 // TODO(tzik): Support binding move-only type into a non-reference parameter
1337 // of a variant of Callback.
1339 move_constructs = 0;
1341 BindRepeating(&VoidPolymorphic<MoveCounter>::Run)
1342 .Run(MoveCounter(&move_constructs, &move_assigns));
1343 EXPECT_EQ(1, move_constructs);
1344 EXPECT_EQ(0, move_assigns);
1346 move_constructs = 0;
1348 BindRepeating(&VoidPolymorphic<MoveCounter>::Run)
1349 .Run(MoveCounter(DerivedCopyMoveCounter(
1350 nullptr, nullptr, &move_constructs, &move_assigns)));
1351 EXPECT_EQ(2, move_constructs);
1352 EXPECT_EQ(0, move_assigns);
1355 // Argument constructor usage for non-reference movable-copyable
1357 // - Bound arguments passed by move are not copied.
1358 // - Forwarded arguments are only copied once.
1359 // - Forwarded arguments with coercions are only copied once and moved once.
1360 TEST_F(BindTest, ArgumentCopiesAndMoves) {
1363 int move_constructs = 0;
1364 int move_assigns = 0;
1366 CopyMoveCounter counter(&copies, &assigns, &move_constructs, &move_assigns);
1367 BindRepeating(&VoidPolymorphic<CopyMoveCounter>::Run, counter);
1368 EXPECT_EQ(1, copies);
1369 EXPECT_EQ(0, assigns);
1370 EXPECT_EQ(0, move_constructs);
1371 EXPECT_EQ(0, move_assigns);
1375 move_constructs = 0;
1378 &VoidPolymorphic<CopyMoveCounter>::Run,
1379 CopyMoveCounter(&copies, &assigns, &move_constructs, &move_assigns));
1380 EXPECT_EQ(0, copies);
1381 EXPECT_EQ(0, assigns);
1382 EXPECT_EQ(1, move_constructs);
1383 EXPECT_EQ(0, move_assigns);
1387 move_constructs = 0;
1389 BindRepeating(&VoidPolymorphic<CopyMoveCounter>::Run).Run(counter);
1390 EXPECT_EQ(1, copies);
1391 EXPECT_EQ(0, assigns);
1392 EXPECT_EQ(1, move_constructs);
1393 EXPECT_EQ(0, move_assigns);
1397 move_constructs = 0;
1399 BindRepeating(&VoidPolymorphic<CopyMoveCounter>::Run)
1400 .Run(CopyMoveCounter(&copies, &assigns, &move_constructs, &move_assigns));
1401 EXPECT_EQ(0, copies);
1402 EXPECT_EQ(0, assigns);
1403 EXPECT_EQ(1, move_constructs);
1404 EXPECT_EQ(0, move_assigns);
1406 DerivedCopyMoveCounter derived_counter(&copies, &assigns, &move_constructs,
1410 move_constructs = 0;
1412 BindRepeating(&VoidPolymorphic<CopyMoveCounter>::Run)
1413 .Run(CopyMoveCounter(derived_counter));
1414 EXPECT_EQ(1, copies);
1415 EXPECT_EQ(0, assigns);
1416 EXPECT_EQ(1, move_constructs);
1417 EXPECT_EQ(0, move_assigns);
1421 move_constructs = 0;
1423 BindRepeating(&VoidPolymorphic<CopyMoveCounter>::Run)
1424 .Run(CopyMoveCounter(DerivedCopyMoveCounter(
1425 &copies, &assigns, &move_constructs, &move_assigns)));
1426 EXPECT_EQ(0, copies);
1427 EXPECT_EQ(0, assigns);
1428 EXPECT_EQ(2, move_constructs);
1429 EXPECT_EQ(0, move_assigns);
1432 TEST_F(BindTest, CapturelessLambda) {
1433 EXPECT_FALSE(internal::IsCallableObject<void>::value);
1434 EXPECT_FALSE(internal::IsCallableObject<int>::value);
1435 EXPECT_FALSE(internal::IsCallableObject<void (*)()>::value);
1436 EXPECT_FALSE(internal::IsCallableObject<void (NoRef::*)()>::value);
1439 EXPECT_TRUE(internal::IsCallableObject<decltype(f)>::value);
1442 auto g = [i]() { (void)i; };
1443 EXPECT_TRUE(internal::IsCallableObject<decltype(g)>::value);
1445 auto h = [](int, double) { return 'k'; };
1446 EXPECT_TRUE((std::is_same<
1448 internal::ExtractCallableRunType<decltype(h)>>::value));
1450 EXPECT_EQ(42, BindRepeating([] { return 42; }).Run());
1451 EXPECT_EQ(42, BindRepeating([](int i) { return i * 7; }, 6).Run());
1454 base::RepeatingCallback<void(int)> cb =
1455 BindRepeating([](int* x, int i) { *x *= i; }, Unretained(&x));
1462 TEST_F(BindTest, EmptyFunctor) {
1463 struct NonEmptyFunctor {
1464 int operator()() const { return x; }
1468 struct EmptyFunctor {
1469 int operator()() { return 42; }
1472 struct EmptyFunctorConst {
1473 int operator()() const { return 42; }
1476 EXPECT_TRUE(internal::IsCallableObject<NonEmptyFunctor>::value);
1477 EXPECT_TRUE(internal::IsCallableObject<EmptyFunctor>::value);
1478 EXPECT_TRUE(internal::IsCallableObject<EmptyFunctorConst>::value);
1479 EXPECT_EQ(42, BindOnce(EmptyFunctor()).Run());
1480 EXPECT_EQ(42, BindOnce(EmptyFunctorConst()).Run());
1481 EXPECT_EQ(42, BindRepeating(EmptyFunctorConst()).Run());
1484 TEST_F(BindTest, CapturingLambdaForTesting) {
1485 // Test copyable lambdas.
1487 EXPECT_EQ(42, BindLambdaForTesting([=](int y) { return x * y; }).Run(7));
1489 BindLambdaForTesting([=](int y) mutable { return x *= y; }).Run(7));
1490 auto f = [x](std::unique_ptr<int> y) { return x * *y; };
1491 EXPECT_EQ(42, BindLambdaForTesting(f).Run(std::make_unique<int>(7)));
1493 // Test move-only lambdas.
1494 auto y = std::make_unique<int>(7);
1495 auto g = [y = std::move(y)](int& x) mutable {
1496 return x * *std::exchange(y, nullptr);
1498 EXPECT_EQ(42, BindLambdaForTesting(std::move(g)).Run(x));
1500 y = std::make_unique<int>(7);
1501 auto h = [x, y = std::move(y)] { return x * *y; };
1502 EXPECT_EQ(42, BindLambdaForTesting(std::move(h)).Run());
1505 TEST_F(BindTest, Cancellation) {
1506 EXPECT_CALL(no_ref_, VoidMethodWithIntArg(_)).Times(2);
1508 WeakPtrFactory<NoRef> weak_factory(&no_ref_);
1509 RepeatingCallback<void(int)> cb =
1510 BindRepeating(&NoRef::VoidMethodWithIntArg, weak_factory.GetWeakPtr());
1511 RepeatingClosure cb2 = BindRepeating(cb, 8);
1512 OnceClosure cb3 = BindOnce(cb, 8);
1514 OnceCallback<void(int)> cb4 =
1515 BindOnce(&NoRef::VoidMethodWithIntArg, weak_factory.GetWeakPtr());
1516 EXPECT_FALSE(cb4.IsCancelled());
1518 OnceClosure cb5 = BindOnce(std::move(cb4), 8);
1520 EXPECT_FALSE(cb.IsCancelled());
1521 EXPECT_FALSE(cb2.IsCancelled());
1522 EXPECT_FALSE(cb3.IsCancelled());
1523 EXPECT_FALSE(cb5.IsCancelled());
1528 weak_factory.InvalidateWeakPtrs();
1530 EXPECT_TRUE(cb.IsCancelled());
1531 EXPECT_TRUE(cb2.IsCancelled());
1532 EXPECT_TRUE(cb3.IsCancelled());
1533 EXPECT_TRUE(cb5.IsCancelled());
1537 std::move(cb3).Run();
1538 std::move(cb5).Run();
1541 TEST_F(BindTest, OnceCallback) {
1542 // Check if Callback variants have declarations of conversions as expected.
1543 // Copy constructor and assignment of RepeatingCallback.
1544 static_assert(std::is_constructible<
1545 RepeatingClosure, const RepeatingClosure&>::value,
1546 "RepeatingClosure should be copyable.");
1548 std::is_assignable<RepeatingClosure, const RepeatingClosure&>::value,
1549 "RepeatingClosure should be copy-assignable.");
1551 // Move constructor and assignment of RepeatingCallback.
1552 static_assert(std::is_constructible<
1553 RepeatingClosure, RepeatingClosure&&>::value,
1554 "RepeatingClosure should be movable.");
1555 static_assert(std::is_assignable<RepeatingClosure, RepeatingClosure&&>::value,
1556 "RepeatingClosure should be move-assignable");
1558 // Conversions from OnceCallback to RepeatingCallback.
1559 static_assert(!std::is_constructible<
1560 RepeatingClosure, const OnceClosure&>::value,
1561 "OnceClosure should not be convertible to RepeatingClosure.");
1563 !std::is_assignable<RepeatingClosure, const OnceClosure&>::value,
1564 "OnceClosure should not be convertible to RepeatingClosure.");
1566 // Destructive conversions from OnceCallback to RepeatingCallback.
1567 static_assert(!std::is_constructible<
1568 RepeatingClosure, OnceClosure&&>::value,
1569 "OnceClosure should not be convertible to RepeatingClosure.");
1570 static_assert(!std::is_assignable<RepeatingClosure, OnceClosure&&>::value,
1571 "OnceClosure should not be convertible to RepeatingClosure.");
1573 // Copy constructor and assignment of OnceCallback.
1574 static_assert(!std::is_constructible<
1575 OnceClosure, const OnceClosure&>::value,
1576 "OnceClosure should not be copyable.");
1577 static_assert(!std::is_assignable<OnceClosure, const OnceClosure&>::value,
1578 "OnceClosure should not be copy-assignable");
1580 // Move constructor and assignment of OnceCallback.
1581 static_assert(std::is_constructible<
1582 OnceClosure, OnceClosure&&>::value,
1583 "OnceClosure should be movable.");
1584 static_assert(std::is_assignable<OnceClosure, OnceClosure&&>::value,
1585 "OnceClosure should be move-assignable.");
1587 // Conversions from RepeatingCallback to OnceCallback.
1588 static_assert(std::is_constructible<
1589 OnceClosure, const RepeatingClosure&>::value,
1590 "RepeatingClosure should be convertible to OnceClosure.");
1591 static_assert(std::is_assignable<OnceClosure, const RepeatingClosure&>::value,
1592 "RepeatingClosure should be convertible to OnceClosure.");
1594 // Destructive conversions from RepeatingCallback to OnceCallback.
1595 static_assert(std::is_constructible<
1596 OnceClosure, RepeatingClosure&&>::value,
1597 "RepeatingClosure should be convertible to OnceClosure.");
1598 static_assert(std::is_assignable<OnceClosure, RepeatingClosure&&>::value,
1599 "RepeatingClosure should be covretible to OnceClosure.");
1601 OnceClosure cb = BindOnce(&VoidPolymorphic<>::Run);
1602 std::move(cb).Run();
1604 // RepeatingCallback should be convertible to OnceCallback.
1605 OnceClosure cb2 = BindRepeating(&VoidPolymorphic<>::Run);
1606 std::move(cb2).Run();
1608 RepeatingClosure cb3 = BindRepeating(&VoidPolymorphic<>::Run);
1610 std::move(cb).Run();
1612 cb = std::move(cb2);
1614 OnceCallback<void(int)> cb4 =
1615 BindOnce(&VoidPolymorphic<std::unique_ptr<int>, int>::Run,
1616 std::make_unique<int>(0));
1617 BindOnce(std::move(cb4), 1).Run();
1620 // Callback construction and assignment tests.
1621 // - Construction from an InvokerStorageHolder should not cause ref/deref.
1622 // - Assignment from other callback should only cause one ref
1624 // TODO(ajwong): Is there actually a way to test this?
1627 int __fastcall FastCallFunc(int n) {
1631 int __stdcall StdCallFunc(int n) {
1635 // Windows specific calling convention support.
1636 // - Can bind a __fastcall function.
1637 // - Can bind a __stdcall function.
1638 // - Can bind const and non-const __stdcall methods.
1639 TEST_F(BindTest, WindowsCallingConventions) {
1640 auto fastcall_cb = BindRepeating(&FastCallFunc, 1);
1641 EXPECT_EQ(1, fastcall_cb.Run());
1643 auto stdcall_cb = BindRepeating(&StdCallFunc, 2);
1644 EXPECT_EQ(2, stdcall_cb.Run());
1646 class MethodHolder {
1648 int __stdcall Func(int n) { return n; }
1649 int __stdcall ConstFunc(int n) const { return -n; }
1653 auto stdcall_method_cb =
1654 BindRepeating(&MethodHolder::Func, base::Unretained(&obj), 1);
1655 EXPECT_EQ(1, stdcall_method_cb.Run());
1657 const MethodHolder const_obj;
1658 auto stdcall_const_method_cb =
1659 BindRepeating(&MethodHolder::ConstFunc, base::Unretained(&const_obj), 1);
1660 EXPECT_EQ(-1, stdcall_const_method_cb.Run());
1664 // Test unwrapping the various wrapping functions.
1666 TEST_F(BindTest, UnwrapUnretained) {
1668 auto unretained = Unretained(&i);
1669 EXPECT_EQ(&i, internal::Unwrap(unretained));
1670 EXPECT_EQ(&i, internal::Unwrap(std::move(unretained)));
1673 TEST_F(BindTest, UnwrapRetainedRef) {
1674 auto p = MakeRefCounted<RefCountedData<int>>();
1675 auto retained_ref = RetainedRef(p);
1676 EXPECT_EQ(p.get(), internal::Unwrap(retained_ref));
1677 EXPECT_EQ(p.get(), internal::Unwrap(std::move(retained_ref)));
1680 TEST_F(BindTest, UnwrapOwned) {
1683 auto owned = Owned(p);
1684 EXPECT_EQ(p, internal::Unwrap(owned));
1685 EXPECT_EQ(p, internal::Unwrap(std::move(owned)));
1689 auto p = std::make_unique<int>();
1690 int* raw_p = p.get();
1691 auto owned = Owned(std::move(p));
1692 EXPECT_EQ(raw_p, internal::Unwrap(owned));
1693 EXPECT_EQ(raw_p, internal::Unwrap(std::move(owned)));
1697 TEST_F(BindTest, UnwrapPassed) {
1699 auto passed = Passed(WrapUnique(p));
1700 EXPECT_EQ(p, internal::Unwrap(passed).get());
1703 EXPECT_EQ(p, internal::Unwrap(Passed(WrapUnique(p))).get());
1706 TEST_F(BindTest, BindNoexcept) {
1707 EXPECT_EQ(42, base::BindOnce(&Noexcept).Run());
1710 base::BindOnce(&BindTest::NoexceptMethod, base::Unretained(this)).Run());
1712 42, base::BindOnce(&BindTest::ConstNoexceptMethod, base::Unretained(this))
1716 // Test null callbacks cause a DCHECK.
1717 TEST(BindDeathTest, NullCallback) {
1718 base::RepeatingCallback<void(int)> null_cb;
1719 ASSERT_TRUE(null_cb.is_null());
1720 EXPECT_CHECK_DEATH(base::BindRepeating(null_cb, 42));
1723 TEST(BindDeathTest, NullFunctionPointer) {
1724 void (*null_function)(int) = nullptr;
1725 EXPECT_DCHECK_DEATH(base::BindRepeating(null_function, 42));
1728 TEST(BindDeathTest, NullCallbackWithoutBoundArgs) {
1729 base::OnceCallback<void(int)> null_cb;
1730 ASSERT_TRUE(null_cb.is_null());
1731 EXPECT_CHECK_DEATH(base::BindOnce(std::move(null_cb)));
1734 TEST(BindDeathTest, BanFirstOwnerOfRefCountedType) {
1735 StrictMock<HasRef> has_ref;
1736 EXPECT_DCHECK_DEATH({
1737 EXPECT_CALL(has_ref, HasAtLeastOneRef()).WillOnce(Return(false));
1738 base::BindOnce(&HasRef::VoidMethod0, &has_ref);