2 * Copyright 2016 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
19 #include <folly/Function.h>
21 #include <folly/Memory.h>
22 #include <gtest/gtest.h>
24 using folly::Function;
27 int func_int_int_add_25(int x) {
30 int func_int_int_add_111(int x) {
33 float floatMult(float a, float b) {
37 template <class T, size_t S>
39 std::array<T, S> data = {{0}};
41 // Two operator() with different argument types.
42 // The InvokeReference tests use both
43 T const& operator()(size_t index) const {
46 T operator()(size_t index, T const& value) {
47 T oldvalue = data[index];
54 // TEST =====================================================================
55 // InvokeFunctor & InvokeReference
57 TEST(Function, InvokeFunctor) {
58 Functor<int, 100> func;
60 sizeof(func) > sizeof(Function<int(size_t)>),
61 "sizeof(Function) is much larger than expected");
64 Function<int(size_t) const> getter = std::move(func);
66 // Function will allocate memory on the heap to store the functor object
67 EXPECT_TRUE(getter.hasAllocatedMemory());
69 EXPECT_EQ(123, getter(5));
72 TEST(Function, InvokeReference) {
73 Functor<int, 10> func;
76 // Have Functions for getter and setter, both referencing the same funtor
77 Function<int(size_t) const> getter = std::ref(func);
78 Function<int(size_t, int)> setter = std::ref(func);
80 EXPECT_EQ(123, getter(5));
81 EXPECT_EQ(123, setter(5, 456));
82 EXPECT_EQ(456, setter(5, 567));
83 EXPECT_EQ(567, getter(5));
86 // TEST =====================================================================
89 TEST(Function, Emptiness_T) {
91 EXPECT_EQ(f, nullptr);
92 EXPECT_EQ(nullptr, f);
94 EXPECT_THROW(f(98), std::bad_function_call);
96 Function<int(int)> g([](int x) { return x + 1; });
97 EXPECT_NE(g, nullptr);
98 EXPECT_NE(nullptr, g);
100 EXPECT_EQ(100, g(99));
102 Function<int(int)> h(&func_int_int_add_25);
103 EXPECT_NE(h, nullptr);
104 EXPECT_NE(nullptr, h);
106 EXPECT_EQ(125, h(100));
109 EXPECT_EQ(h, nullptr);
110 EXPECT_EQ(nullptr, h);
112 EXPECT_THROW(h(101), std::bad_function_call);
115 // TEST =====================================================================
118 template <bool UseSwapMethod>
120 Function<int(int)> mf1(func_int_int_add_25);
121 Function<int(int)> mf2(func_int_int_add_111);
123 EXPECT_EQ(125, mf1(100));
124 EXPECT_EQ(211, mf2(100));
132 EXPECT_EQ(125, mf2(100));
133 EXPECT_EQ(211, mf1(100));
135 Function<int(int)> mf3(nullptr);
136 EXPECT_EQ(mf3, nullptr);
144 EXPECT_EQ(211, mf3(100));
145 EXPECT_EQ(nullptr, mf1);
147 Function<int(int)> mf4([](int x) { return x + 222; });
148 EXPECT_EQ(322, mf4(100));
155 EXPECT_EQ(211, mf4(100));
156 EXPECT_EQ(322, mf3(100));
163 EXPECT_EQ(nullptr, mf3);
164 EXPECT_EQ(322, mf1(100));
166 TEST(Function, SwapMethod) {
169 TEST(Function, SwapFunction) {
173 // TEST =====================================================================
176 TEST(Function, Bind) {
177 Function<float(float, float)> fnc = floatMult;
178 auto task = std::bind(std::move(fnc), 2.f, 4.f);
179 EXPECT_THROW(fnc(0, 0), std::bad_function_call);
180 EXPECT_EQ(8, task());
181 auto task2(std::move(task));
182 EXPECT_THROW(task(), std::bad_function_call);
183 EXPECT_EQ(8, task2());
186 // TEST =====================================================================
189 TEST(Function, NonCopyableLambda) {
190 auto unique_ptr_int = folly::make_unique<int>(900);
191 EXPECT_EQ(900, *unique_ptr_int);
193 char fooData[64] = {0};
194 EXPECT_EQ(0, fooData[0]); // suppress gcc warning about fooData not being used
196 auto functor = std::bind(
197 [fooData](std::unique_ptr<int>& up) mutable { return ++*up; },
198 std::move(unique_ptr_int));
200 EXPECT_EQ(901, functor());
202 Function<int(void)> func = std::move(functor);
203 EXPECT_TRUE(func.hasAllocatedMemory());
205 EXPECT_EQ(902, func());
208 // TEST =====================================================================
211 TEST(Function, OverloadedFunctor) {
212 struct OverloadedFunctor {
214 int operator()(int x) {
218 // variant 2 (const-overload of v1)
219 int operator()(int x) const {
224 int operator()(int x, int) {
228 // variant 4 (const-overload of v3)
229 int operator()(int x, int) const {
233 // variant 5 (non-const, has no const-overload)
234 int operator()(int x, char const*) {
238 // variant 6 (const only)
239 int operator()(int x, std::vector<int> const&) const {
243 OverloadedFunctor of;
245 Function<int(int)> variant1 = of;
246 EXPECT_EQ(100 + 1 * 15, variant1(15));
248 Function<int(int) const> variant2 = of;
249 EXPECT_EQ(100 + 2 * 16, variant2(16));
251 Function<int(int, int)> variant3 = of;
252 EXPECT_EQ(100 + 3 * 17, variant3(17, 0));
254 Function<int(int, int) const> variant4 = of;
255 EXPECT_EQ(100 + 4 * 18, variant4(18, 0));
257 Function<int(int, char const*)> variant5 = of;
258 EXPECT_EQ(100 + 5 * 19, variant5(19, "foo"));
260 Function<int(int, std::vector<int> const&)> variant6 = of;
261 EXPECT_EQ(100 + 6 * 20, variant6(20, {}));
262 EXPECT_EQ(100 + 6 * 20, variant6(20, {1, 2, 3}));
264 Function<int(int, std::vector<int> const&) const> variant6const = of;
265 EXPECT_EQ(100 + 6 * 21, variant6const(21, {}));
267 // Cast const-functions to non-const and the other way around: if the functor
268 // has both const and non-const operator()s for a given parameter signature,
269 // constructing a Function must select one of them, depending on
270 // whether the function type template parameter is const-qualified or not.
271 // When the const-ness is later changed (by moving the
272 // Function<R(Args...)const> into a Function<R(Args...)> or by
273 // calling the folly::constCastFunction which moves it into a
274 // Function<R(Args...)const>), the Function must still execute
275 // the initially selected function.
277 auto variant1_const = folly::constCastFunction(std::move(variant1));
278 EXPECT_THROW(variant1(0), std::bad_function_call);
279 EXPECT_EQ(100 + 1 * 22, variant1_const(22));
281 Function<int(int)> variant2_nonconst = std::move(variant2);
282 EXPECT_THROW(variant2(0), std::bad_function_call);
283 EXPECT_EQ(100 + 2 * 23, variant2_nonconst(23));
285 auto variant3_const = folly::constCastFunction(std::move(variant3));
286 EXPECT_THROW(variant3(0, 0), std::bad_function_call);
287 EXPECT_EQ(100 + 3 * 24, variant3_const(24, 0));
289 Function<int(int, int)> variant4_nonconst = std::move(variant4);
290 EXPECT_THROW(variant4(0, 0), std::bad_function_call);
291 EXPECT_EQ(100 + 4 * 25, variant4_nonconst(25, 0));
293 auto variant5_const = folly::constCastFunction(std::move(variant5));
294 EXPECT_THROW(variant5(0, ""), std::bad_function_call);
295 EXPECT_EQ(100 + 5 * 26, variant5_const(26, "foo"));
297 auto variant6_const = folly::constCastFunction(std::move(variant6));
298 EXPECT_THROW(variant6(0, {}), std::bad_function_call);
299 EXPECT_EQ(100 + 6 * 27, variant6_const(27, {}));
301 Function<int(int, std::vector<int> const&)> variant6const_nonconst =
302 std::move(variant6const);
303 EXPECT_THROW(variant6const(0, {}), std::bad_function_call);
304 EXPECT_EQ(100 + 6 * 28, variant6const_nonconst(28, {}));
307 // TEST =====================================================================
310 TEST(Function, Lambda) {
311 // Non-mutable lambdas: can be stored in a non-const...
312 Function<int(int)> func = [](int x) { return 1000 + x; };
313 EXPECT_EQ(1001, func(1));
315 // ...as well as in a const Function
316 Function<int(int) const> func_const = [](int x) { return 2000 + x; };
317 EXPECT_EQ(2001, func_const(1));
319 // Mutable lambda: can only be stored in a const Function:
321 Function<int()> func_mutable = [number]() mutable { return ++number; };
322 EXPECT_EQ(3001, func_mutable());
323 EXPECT_EQ(3002, func_mutable());
325 // test after const-casting
327 Function<int(int) const> func_made_const =
328 folly::constCastFunction(std::move(func));
329 EXPECT_EQ(1002, func_made_const(2));
330 EXPECT_THROW(func(0), std::bad_function_call);
332 Function<int(int)> func_const_made_nonconst = std::move(func_const);
333 EXPECT_EQ(2002, func_const_made_nonconst(2));
334 EXPECT_THROW(func_const(0), std::bad_function_call);
336 Function<int() const> func_mutable_made_const =
337 folly::constCastFunction(std::move(func_mutable));
338 EXPECT_EQ(3003, func_mutable_made_const());
339 EXPECT_EQ(3004, func_mutable_made_const());
340 EXPECT_THROW(func_mutable(), std::bad_function_call);
343 // TEST =====================================================================
344 // DataMember & MemberFunction
356 TEST(Function, DataMember) {
358 MemberFunc const& cmf = mf;
361 Function<int(MemberFunc const*)> data_getter1 = &MemberFunc::x;
362 EXPECT_EQ(123, data_getter1(&cmf));
363 Function<int(MemberFunc*)> data_getter2 = &MemberFunc::x;
364 EXPECT_EQ(123, data_getter2(&mf));
365 Function<int(MemberFunc const&)> data_getter3 = &MemberFunc::x;
366 EXPECT_EQ(123, data_getter3(cmf));
367 Function<int(MemberFunc&)> data_getter4 = &MemberFunc::x;
368 EXPECT_EQ(123, data_getter4(mf));
371 TEST(Function, MemberFunction) {
373 MemberFunc const& cmf = mf;
376 Function<int(MemberFunc const*)> getter1 = &MemberFunc::getX;
377 EXPECT_EQ(123, getter1(&cmf));
378 Function<int(MemberFunc*)> getter2 = &MemberFunc::getX;
379 EXPECT_EQ(123, getter2(&mf));
380 Function<int(MemberFunc const&)> getter3 = &MemberFunc::getX;
381 EXPECT_EQ(123, getter3(cmf));
382 Function<int(MemberFunc&)> getter4 = &MemberFunc::getX;
383 EXPECT_EQ(123, getter4(mf));
385 Function<void(MemberFunc*, int)> setter1 = &MemberFunc::setX;
387 EXPECT_EQ(234, mf.x);
389 Function<void(MemberFunc&, int)> setter2 = &MemberFunc::setX;
391 EXPECT_EQ(345, mf.x);
394 // TEST =====================================================================
395 // CaptureCopyMoveCount & ParameterCopyMoveCount
397 class CopyMoveTracker {
399 struct ConstructorTag {};
401 CopyMoveTracker() = delete;
402 explicit CopyMoveTracker(ConstructorTag)
403 : data_(std::make_shared<std::pair<size_t, size_t>>(0, 0)) {}
405 CopyMoveTracker(CopyMoveTracker const& o) noexcept : data_(o.data_) {
408 CopyMoveTracker& operator=(CopyMoveTracker const& o) noexcept {
414 CopyMoveTracker(CopyMoveTracker&& o) noexcept : data_(o.data_) {
417 CopyMoveTracker& operator=(CopyMoveTracker&& o) noexcept {
423 size_t copyCount() const {
426 size_t moveCount() const {
427 return data_->second;
429 size_t refCount() const {
430 return data_.use_count();
432 void resetCounters() {
433 data_->first = data_->second = 0;
438 std::shared_ptr<std::pair<size_t, size_t>> data_;
441 TEST(Function, CaptureCopyMoveCount) {
442 // This test checks that no unnecessary copies/moves are made.
444 CopyMoveTracker cmt(CopyMoveTracker::ConstructorTag{});
445 EXPECT_EQ(0, cmt.copyCount());
446 EXPECT_EQ(0, cmt.moveCount());
447 EXPECT_EQ(1, cmt.refCount());
449 // Move into lambda, move lambda into Function
450 auto lambda1 = [cmt = std::move(cmt)]() {
451 return cmt.moveCount();
453 Function<size_t(void)> uf1 = std::move(lambda1);
455 // Max copies: 0. Max copy+moves: 2.
456 EXPECT_LE(cmt.moveCount() + cmt.copyCount(), 2);
457 EXPECT_LE(cmt.copyCount(), 0);
461 // Move into lambda, copy lambda into Function
462 auto lambda2 = [cmt = std::move(cmt)]() {
463 return cmt.moveCount();
465 Function<size_t(void)> uf2 = lambda2;
467 // Max copies: 1. Max copy+moves: 2.
468 EXPECT_LE(cmt.moveCount() + cmt.copyCount(), 2);
469 EXPECT_LE(cmt.copyCount(), 1);
471 // Invoking Function must not make copies/moves of the callable
475 EXPECT_EQ(0, cmt.copyCount());
476 EXPECT_EQ(0, cmt.moveCount());
479 TEST(Function, ParameterCopyMoveCount) {
480 // This test checks that no unnecessary copies/moves are made.
482 CopyMoveTracker cmt(CopyMoveTracker::ConstructorTag{});
483 EXPECT_EQ(0, cmt.copyCount());
484 EXPECT_EQ(0, cmt.moveCount());
485 EXPECT_EQ(1, cmt.refCount());
488 Function<size_t(CopyMoveTracker)> uf1 = [](CopyMoveTracker c) {
489 return c.moveCount();
494 // Max copies: 1. Max copy+moves: 2.
495 EXPECT_LE(cmt.moveCount() + cmt.copyCount(), 2);
496 EXPECT_LE(cmt.copyCount(), 1);
500 // Max copies: 1. Max copy+moves: 2.
501 EXPECT_LE(cmt.moveCount() + cmt.copyCount(), 2);
502 EXPECT_LE(cmt.copyCount(), 0);
505 Function<size_t(CopyMoveTracker&)> uf2 = [](CopyMoveTracker& c) {
506 return c.moveCount();
511 // Max copies: 0. Max copy+moves: 0.
512 EXPECT_LE(cmt.moveCount() + cmt.copyCount(), 0);
513 EXPECT_LE(cmt.copyCount(), 0);
515 // pass by const reference
516 Function<size_t(CopyMoveTracker const&)> uf3 = [](CopyMoveTracker const& c) {
517 return c.moveCount();
522 // Max copies: 0. Max copy+moves: 0.
523 EXPECT_LE(cmt.moveCount() + cmt.copyCount(), 0);
524 EXPECT_LE(cmt.copyCount(), 0);
526 // pass by rvalue reference
527 Function<size_t(CopyMoveTracker &&)> uf4 = [](CopyMoveTracker&& c) {
528 return c.moveCount();
533 // Max copies: 0. Max copy+moves: 0.
534 EXPECT_LE(cmt.moveCount() + cmt.copyCount(), 0);
535 EXPECT_LE(cmt.copyCount(), 0);
538 // TEST =====================================================================
539 // VariadicTemplate & VariadicArguments
541 struct VariadicTemplateSum {
542 int operator()() const {
545 template <class... Args>
546 int operator()(int x, Args... args) const {
547 return x + (*this)(args...);
551 TEST(Function, VariadicTemplate) {
552 Function<int(int)> uf1 = VariadicTemplateSum();
553 Function<int(int, int)> uf2 = VariadicTemplateSum();
554 Function<int(int, int, int)> uf3 = VariadicTemplateSum();
556 EXPECT_EQ(66, uf1(66));
557 EXPECT_EQ(99, uf2(55, 44));
558 EXPECT_EQ(66, uf3(33, 22, 11));
561 struct VariadicArgumentsSum {
562 int operator()(int count, ...) const {
565 va_start(args, count);
566 for (int i = 0; i < count; ++i) {
567 result += va_arg(args, int);
574 TEST(Function, VariadicArguments) {
575 Function<int(int)> uf1 = VariadicArgumentsSum();
576 Function<int(int, int)> uf2 = VariadicArgumentsSum();
577 Function<int(int, int, int)> uf3 = VariadicArgumentsSum();
579 EXPECT_EQ(0, uf1(0));
580 EXPECT_EQ(66, uf2(1, 66));
581 EXPECT_EQ(99, uf3(2, 55, 44));
584 // TEST =====================================================================
585 // SafeCaptureByReference
587 // A function can use Function const& as a parameter to signal that it
588 // is safe to pass a lambda that captures local variables by reference.
589 // It is safe because we know the function called can only invoke the
590 // Function until it returns. It can't store a copy of the Function
591 // (because it's not copyable), and it can't move the Function somewhere
592 // else (because it gets only a const&).
594 template <typename T>
597 Function<void(typename T::value_type const&) const> const& func) {
598 for (auto const& elem : range) {
603 TEST(Function, SafeCaptureByReference) {
604 std::vector<int> const vec = {20, 30, 40, 2, 3, 4, 200, 300, 400};
608 // for_each's second parameter is of type Function<...> const&.
609 // Hence we know we can safely pass it a lambda that references local
610 // variables. There is no way the reference to x will be stored anywhere.
611 for_each<std::vector<int>>(vec, [&sum](int x) { sum += x; });
613 // gcc versions before 4.9 cannot deduce the type T in the above call
614 // to for_each. Modern compiler versions can compile the following line:
615 // for_each(vec, [&sum](int x) { sum += x; });
620 // TEST =====================================================================
623 TEST(Function, IgnoreReturnValue) {
626 // Assign a lambda that return int to a folly::Function that returns void.
627 Function<void()> f = [&]() -> int { return ++x; };
633 Function<int()> g = [&]() -> int { return ++x; };
634 Function<void()> cg = std::move(g);
641 // TEST =====================================================================
642 // ReturnConvertible, ConvertReturnType
644 TEST(Function, ReturnConvertible) {
648 struct CDerived : CBase {};
650 Function<double()> f1 = []() -> int { return 5; };
651 EXPECT_EQ(5.0, f1());
653 Function<int()> f2 = []() -> double { return 5.2; };
659 Function<CBase const&()> f3 = [&]() -> CDerived const& { return derived; };
660 EXPECT_EQ(55, f3().x);
662 Function<CBase const&()> f4 = [&]() -> CDerived& { return derived; };
663 EXPECT_EQ(55, f4().x);
665 Function<CBase&()> f5 = [&]() -> CDerived& { return derived; };
666 EXPECT_EQ(55, f5().x);
668 Function<CBase const*()> f6 = [&]() -> CDerived const* { return &derived; };
669 EXPECT_EQ(f6()->x, 55);
671 Function<CBase const*()> f7 = [&]() -> CDerived* { return &derived; };
672 EXPECT_EQ(55, f7()->x);
674 Function<CBase*()> f8 = [&]() -> CDerived* { return &derived; };
675 EXPECT_EQ(55, f8()->x);
677 Function<CBase()> f9 = [&]() -> CDerived {
682 EXPECT_EQ(66, f9().x);
685 TEST(Function, ConvertReturnType) {
689 struct CDerived : CBase {};
691 Function<int()> f1 = []() -> int { return 5; };
692 Function<double()> cf1 = std::move(f1);
693 EXPECT_EQ(5.0, cf1());
694 Function<int()> ccf1 = std::move(cf1);
695 EXPECT_EQ(5, ccf1());
697 Function<double()> f2 = []() -> double { return 5.2; };
698 Function<int()> cf2 = std::move(f2);
700 Function<double()> ccf2 = std::move(cf2);
701 EXPECT_EQ(5.0, ccf2());
706 Function<CDerived const&()> f3 = [&]() -> CDerived const& { return derived; };
707 Function<CBase const&()> cf3 = std::move(f3);
708 EXPECT_EQ(55, cf3().x);
710 Function<CDerived&()> f4 = [&]() -> CDerived& { return derived; };
711 Function<CBase const&()> cf4 = std::move(f4);
712 EXPECT_EQ(55, cf4().x);
714 Function<CDerived&()> f5 = [&]() -> CDerived& { return derived; };
715 Function<CBase&()> cf5 = std::move(f5);
716 EXPECT_EQ(55, cf5().x);
718 Function<CDerived const*()> f6 = [&]() -> CDerived const* {
721 Function<CBase const*()> cf6 = std::move(f6);
722 EXPECT_EQ(55, cf6()->x);
724 Function<CDerived const*()> f7 = [&]() -> CDerived* { return &derived; };
725 Function<CBase const*()> cf7 = std::move(f7);
726 EXPECT_EQ(55, cf7()->x);
728 Function<CDerived*()> f8 = [&]() -> CDerived* { return &derived; };
729 Function<CBase*()> cf8 = std::move(f8);
730 EXPECT_EQ(55, cf8()->x);
732 Function<CDerived()> f9 = [&]() -> CDerived {
737 Function<CBase()> cf9 = std::move(f9);
738 EXPECT_EQ(66, cf9().x);
741 // TEST =====================================================================
744 TEST(Function, asStdFunction_void) {
746 folly::Function<void()> f = [&] { ++i; };
747 auto sf = std::move(f).asStdFunction();
748 static_assert(std::is_same<decltype(sf), std::function<void()>>::value,
749 "std::function has wrong type");
754 TEST(Function, asStdFunction_void_const) {
756 folly::Function<void() const> f = [&] { ++i; };
757 auto sf = std::move(f).asStdFunction();
758 static_assert(std::is_same<decltype(sf), std::function<void()>>::value,
759 "std::function has wrong type");
764 TEST(Function, asStdFunction_return) {
766 folly::Function<int()> f = [&] {
770 auto sf = std::move(f).asStdFunction();
771 static_assert(std::is_same<decltype(sf), std::function<int()>>::value,
772 "std::function has wrong type");
777 TEST(Function, asStdFunction_return_const) {
779 folly::Function<int() const> f = [&] {
783 auto sf = std::move(f).asStdFunction();
784 static_assert(std::is_same<decltype(sf), std::function<int()>>::value,
785 "std::function has wrong type");
790 TEST(Function, asStdFunction_args) {
792 folly::Function<void(int, int)> f = [&](int x, int y) {
796 auto sf = std::move(f).asStdFunction();
797 static_assert(std::is_same<decltype(sf), std::function<void(int, int)>>::value,
798 "std::function has wrong type");
803 TEST(Function, asStdFunction_args_const) {
805 folly::Function<void(int, int) const> f = [&](int x, int y) {
809 auto sf = std::move(f).asStdFunction();
810 static_assert(std::is_same<decltype(sf), std::function<void(int, int)>>::value,
811 "std::function has wrong type");
816 TEST(Function, NoAllocatedMemoryAfterMove) {
817 Functor<int, 100> foo;
819 Function<int(size_t)> func = foo;
820 EXPECT_TRUE(func.hasAllocatedMemory());
822 Function<int(size_t)> func2 = std::move(func);
823 EXPECT_TRUE(func2.hasAllocatedMemory());
824 EXPECT_FALSE(func.hasAllocatedMemory());
827 TEST(Function, ConstCastEmbedded) {
829 auto functor = [&x]() { ++x; };
831 Function<void() const> func(functor);
832 EXPECT_FALSE(func.hasAllocatedMemory());
834 Function<void()> func2(std::move(func));
835 EXPECT_FALSE(func2.hasAllocatedMemory());
838 TEST(Function, EmptyAfterConstCast) {
839 Function<int(size_t)> func;
842 Function<int(size_t) const> func2 = constCastFunction(std::move(func));
846 TEST(Function, SelfMoveAssign) {
847 Function<int()> f = [] { return 0; };
848 Function<int()>& g = f;