Codemod folly::make_unique to std::make_unique
[folly.git] / folly / test / FunctionTest.cpp
1 /*
2  * Copyright 2017 Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #include <array>
18 #include <cstdarg>
19
20 #include <folly/Function.h>
21
22 #include <folly/Memory.h>
23 #include <folly/portability/GTest.h>
24
25 using folly::Function;
26
27 namespace {
28 int func_int_int_add_25(int x) {
29   return x + 25;
30 }
31 int func_int_int_add_111(int x) {
32   return x + 111;
33 }
34 float floatMult(float a, float b) {
35   return a * b;
36 }
37
38 template <class T, size_t S>
39 struct Functor {
40   std::array<T, S> data = {{0}};
41
42   // Two operator() with different argument types.
43   // The InvokeReference tests use both
44   T const& operator()(size_t index) const {
45     return data[index];
46   }
47   T operator()(size_t index, T const& value) {
48     T oldvalue = data[index];
49     data[index] = value;
50     return oldvalue;
51   }
52 };
53
54 template <typename Ret, typename... Args>
55 void deduceArgs(Function<Ret(Args...)>) {}
56
57 struct CallableButNotCopyable {
58   CallableButNotCopyable() {}
59   CallableButNotCopyable(CallableButNotCopyable const&) = delete;
60   CallableButNotCopyable(CallableButNotCopyable&&) = delete;
61   CallableButNotCopyable& operator=(CallableButNotCopyable const&) = delete;
62   CallableButNotCopyable& operator=(CallableButNotCopyable&&) = delete;
63   template <class... Args>
64   void operator()(Args&&...) const {}
65 };
66
67 } // namespace
68
69 // TEST =====================================================================
70 // Test constructibility and non-constructibility for some tricky conversions
71 static_assert(
72     !std::is_assignable<Function<void()>, CallableButNotCopyable>::value,
73     "");
74 static_assert(
75     !std::is_constructible<Function<void()>, CallableButNotCopyable&>::value,
76     "");
77 static_assert(
78     !std::is_constructible<Function<void() const>, CallableButNotCopyable>::
79         value,
80     "");
81 static_assert(
82     !std::is_constructible<Function<void() const>, CallableButNotCopyable&>::
83         value,
84     "");
85
86 static_assert(
87     !std::is_assignable<Function<void()>, CallableButNotCopyable>::value,
88     "");
89 static_assert(
90     !std::is_assignable<Function<void()>, CallableButNotCopyable&>::value,
91     "");
92 static_assert(
93     !std::is_assignable<Function<void() const>, CallableButNotCopyable>::value,
94     "");
95 static_assert(
96     !std::is_assignable<Function<void() const>, CallableButNotCopyable&>::value,
97     "");
98
99 static_assert(
100     std::is_constructible<Function<int(int)>, Function<int(int) const>>::value,
101     "");
102 static_assert(
103     !std::is_constructible<Function<int(int) const>, Function<int(int)>>::value,
104     "");
105 static_assert(
106     std::is_constructible<Function<int(short)>, Function<short(int) const>>::
107         value,
108     "");
109 static_assert(
110     !std::is_constructible<Function<int(short) const>, Function<short(int)>>::
111         value,
112     "");
113 static_assert(
114     !std::is_constructible<Function<int(int)>, Function<int(int) const>&>::
115         value,
116     "");
117 static_assert(
118     !std::is_constructible<Function<int(int) const>, Function<int(int)>&>::
119         value,
120     "");
121 static_assert(
122     !std::is_constructible<Function<int(short)>, Function<short(int) const>&>::
123         value,
124     "");
125 static_assert(
126     !std::is_constructible<Function<int(short) const>, Function<short(int)>&>::
127         value,
128     "");
129
130 static_assert(
131     std::is_assignable<Function<int(int)>, Function<int(int) const>>::value,
132     "");
133 static_assert(
134     !std::is_assignable<Function<int(int) const>, Function<int(int)>>::value,
135     "");
136 static_assert(
137     std::is_assignable<Function<int(short)>, Function<short(int) const>>::value,
138     "");
139 static_assert(
140     !std::is_assignable<Function<int(short) const>, Function<short(int)>>::
141         value,
142     "");
143 static_assert(
144     !std::is_assignable<Function<int(int)>, Function<int(int) const>&>::value,
145     "");
146 static_assert(
147     !std::is_assignable<Function<int(int) const>, Function<int(int)>&>::value,
148     "");
149 static_assert(
150     !std::is_assignable<Function<int(short)>, Function<short(int) const>&>::
151         value,
152     "");
153 static_assert(
154     !std::is_assignable<Function<int(short) const>, Function<short(int)>&>::
155         value,
156     "");
157
158 static_assert(
159     std::is_nothrow_constructible<
160         Function<int(int)>,
161         Function<int(int) const>>::value,
162     "");
163 static_assert(
164     !std::is_nothrow_constructible<
165         Function<int(short)>,
166         Function<short(int) const>>::value,
167     "");
168 static_assert(
169     std::is_nothrow_assignable<Function<int(int)>, Function<int(int) const>>::
170         value,
171     "");
172 static_assert(
173     !std::is_nothrow_assignable<
174         Function<int(short)>,
175         Function<short(int) const>>::value,
176     "");
177
178 // TEST =====================================================================
179 // InvokeFunctor & InvokeReference
180
181 TEST(Function, InvokeFunctor) {
182   Functor<int, 100> func;
183   static_assert(
184       sizeof(func) > sizeof(Function<int(size_t)>),
185       "sizeof(Function) is much larger than expected");
186   func(5, 123);
187
188   Function<int(size_t) const> getter = std::move(func);
189
190   // Function will allocate memory on the heap to store the functor object
191   EXPECT_TRUE(getter.hasAllocatedMemory());
192
193   EXPECT_EQ(123, getter(5));
194 }
195
196 TEST(Function, InvokeReference) {
197   Functor<int, 10> func;
198   func(5, 123);
199
200   // Have Functions for getter and setter, both referencing the same funtor
201   Function<int(size_t) const> getter = std::ref(func);
202   Function<int(size_t, int)> setter = std::ref(func);
203
204   EXPECT_EQ(123, getter(5));
205   EXPECT_EQ(123, setter(5, 456));
206   EXPECT_EQ(456, setter(5, 567));
207   EXPECT_EQ(567, getter(5));
208 }
209
210 // TEST =====================================================================
211 // Emptiness
212
213 TEST(Function, Emptiness_T) {
214   Function<int(int)> f;
215   EXPECT_EQ(f, nullptr);
216   EXPECT_EQ(nullptr, f);
217   EXPECT_FALSE(f);
218   EXPECT_THROW(f(98), std::bad_function_call);
219
220   Function<int(int)> g([](int x) { return x + 1; });
221   EXPECT_NE(g, nullptr);
222   EXPECT_NE(nullptr, g);
223   // Explicitly convert to bool to work around
224   // https://github.com/google/googletest/issues/429
225   EXPECT_TRUE(bool(g));
226   EXPECT_EQ(100, g(99));
227
228   Function<int(int)> h(&func_int_int_add_25);
229   EXPECT_NE(h, nullptr);
230   EXPECT_NE(nullptr, h);
231   EXPECT_TRUE(bool(h));
232   EXPECT_EQ(125, h(100));
233
234   h = {};
235   EXPECT_EQ(h, nullptr);
236   EXPECT_EQ(nullptr, h);
237   EXPECT_FALSE(h);
238   EXPECT_THROW(h(101), std::bad_function_call);
239 }
240
241 // TEST =====================================================================
242 // Swap
243
244 template <bool UseSwapMethod>
245 void swap_test() {
246   Function<int(int)> mf1(func_int_int_add_25);
247   Function<int(int)> mf2(func_int_int_add_111);
248
249   EXPECT_EQ(125, mf1(100));
250   EXPECT_EQ(211, mf2(100));
251
252   if (UseSwapMethod) {
253     mf1.swap(mf2);
254   } else {
255     swap(mf1, mf2);
256   }
257
258   EXPECT_EQ(125, mf2(100));
259   EXPECT_EQ(211, mf1(100));
260
261   Function<int(int)> mf3(nullptr);
262   EXPECT_EQ(mf3, nullptr);
263
264   if (UseSwapMethod) {
265     mf1.swap(mf3);
266   } else {
267     swap(mf1, mf3);
268   }
269
270   EXPECT_EQ(211, mf3(100));
271   EXPECT_EQ(nullptr, mf1);
272
273   Function<int(int)> mf4([](int x) { return x + 222; });
274   EXPECT_EQ(322, mf4(100));
275
276   if (UseSwapMethod) {
277     mf4.swap(mf3);
278   } else {
279     swap(mf4, mf3);
280   }
281   EXPECT_EQ(211, mf4(100));
282   EXPECT_EQ(322, mf3(100));
283
284   if (UseSwapMethod) {
285     mf3.swap(mf1);
286   } else {
287     swap(mf3, mf1);
288   }
289   EXPECT_EQ(nullptr, mf3);
290   EXPECT_EQ(322, mf1(100));
291 }
292 TEST(Function, SwapMethod) {
293   swap_test<true>();
294 }
295 TEST(Function, SwapFunction) {
296   swap_test<false>();
297 }
298
299 // TEST =====================================================================
300 // Bind
301
302 TEST(Function, Bind) {
303   Function<float(float, float)> fnc = floatMult;
304   auto task = std::bind(std::move(fnc), 2.f, 4.f);
305   EXPECT_THROW(fnc(0, 0), std::bad_function_call);
306   EXPECT_EQ(8, task());
307   auto task2(std::move(task));
308   EXPECT_THROW(task(), std::bad_function_call);
309   EXPECT_EQ(8, task2());
310 }
311
312 // TEST =====================================================================
313 // NonCopyableLambda
314
315 TEST(Function, NonCopyableLambda) {
316   auto unique_ptr_int = std::make_unique<int>(900);
317   EXPECT_EQ(900, *unique_ptr_int);
318
319   struct {
320     char data[64];
321   } fooData = {{0}};
322   (void)fooData; // suppress gcc warning about fooData not being used
323
324   auto functor = std::bind(
325       [fooData](std::unique_ptr<int>& up) mutable { return ++*up; },
326       std::move(unique_ptr_int));
327
328   EXPECT_EQ(901, functor());
329
330   Function<int(void)> func = std::move(functor);
331   EXPECT_TRUE(func.hasAllocatedMemory());
332
333   EXPECT_EQ(902, func());
334 }
335
336 // TEST =====================================================================
337 // OverloadedFunctor
338
339 TEST(Function, OverloadedFunctor) {
340   struct OverloadedFunctor {
341     // variant 1
342     int operator()(int x) {
343       return 100 + 1 * x;
344     }
345
346     // variant 2 (const-overload of v1)
347     int operator()(int x) const {
348       return 100 + 2 * x;
349     }
350
351     // variant 3
352     int operator()(int x, int) {
353       return 100 + 3 * x;
354     }
355
356     // variant 4 (const-overload of v3)
357     int operator()(int x, int) const {
358       return 100 + 4 * x;
359     }
360
361     // variant 5 (non-const, has no const-overload)
362     int operator()(int x, char const*) {
363       return 100 + 5 * x;
364     }
365
366     // variant 6 (const only)
367     int operator()(int x, std::vector<int> const&) const {
368       return 100 + 6 * x;
369     }
370   };
371   OverloadedFunctor of;
372
373   Function<int(int)> variant1 = of;
374   EXPECT_EQ(100 + 1 * 15, variant1(15));
375
376   Function<int(int) const> variant2 = of;
377   EXPECT_EQ(100 + 2 * 16, variant2(16));
378
379   Function<int(int, int)> variant3 = of;
380   EXPECT_EQ(100 + 3 * 17, variant3(17, 0));
381
382   Function<int(int, int) const> variant4 = of;
383   EXPECT_EQ(100 + 4 * 18, variant4(18, 0));
384
385   Function<int(int, char const*)> variant5 = of;
386   EXPECT_EQ(100 + 5 * 19, variant5(19, "foo"));
387
388   Function<int(int, std::vector<int> const&)> variant6 = of;
389   EXPECT_EQ(100 + 6 * 20, variant6(20, {}));
390   EXPECT_EQ(100 + 6 * 20, variant6(20, {1, 2, 3}));
391
392   Function<int(int, std::vector<int> const&) const> variant6const = of;
393   EXPECT_EQ(100 + 6 * 21, variant6const(21, {}));
394
395   // Cast const-functions to non-const and the other way around: if the functor
396   // has both const and non-const operator()s for a given parameter signature,
397   // constructing a Function must select one of them, depending on
398   // whether the function type template parameter is const-qualified or not.
399   // When the const-ness is later changed (by moving the
400   // Function<R(Args...)const> into a Function<R(Args...)> or by
401   // calling the folly::constCastFunction which moves it into a
402   // Function<R(Args...)const>), the Function must still execute
403   // the initially selected function.
404
405   auto variant1_const = folly::constCastFunction(std::move(variant1));
406   EXPECT_THROW(variant1(0), std::bad_function_call);
407   EXPECT_EQ(100 + 1 * 22, variant1_const(22));
408
409   Function<int(int)> variant2_nonconst = std::move(variant2);
410   EXPECT_THROW(variant2(0), std::bad_function_call);
411   EXPECT_EQ(100 + 2 * 23, variant2_nonconst(23));
412
413   auto variant3_const = folly::constCastFunction(std::move(variant3));
414   EXPECT_THROW(variant3(0, 0), std::bad_function_call);
415   EXPECT_EQ(100 + 3 * 24, variant3_const(24, 0));
416
417   Function<int(int, int)> variant4_nonconst = std::move(variant4);
418   EXPECT_THROW(variant4(0, 0), std::bad_function_call);
419   EXPECT_EQ(100 + 4 * 25, variant4_nonconst(25, 0));
420
421   auto variant5_const = folly::constCastFunction(std::move(variant5));
422   EXPECT_THROW(variant5(0, ""), std::bad_function_call);
423   EXPECT_EQ(100 + 5 * 26, variant5_const(26, "foo"));
424
425   auto variant6_const = folly::constCastFunction(std::move(variant6));
426   EXPECT_THROW(variant6(0, {}), std::bad_function_call);
427   EXPECT_EQ(100 + 6 * 27, variant6_const(27, {}));
428
429   Function<int(int, std::vector<int> const&)> variant6const_nonconst =
430       std::move(variant6const);
431   EXPECT_THROW(variant6const(0, {}), std::bad_function_call);
432   EXPECT_EQ(100 + 6 * 28, variant6const_nonconst(28, {}));
433 }
434
435 // TEST =====================================================================
436 // Lambda
437
438 TEST(Function, Lambda) {
439   // Non-mutable lambdas: can be stored in a non-const...
440   Function<int(int)> func = [](int x) { return 1000 + x; };
441   EXPECT_EQ(1001, func(1));
442
443   // ...as well as in a const Function
444   Function<int(int) const> func_const = [](int x) { return 2000 + x; };
445   EXPECT_EQ(2001, func_const(1));
446
447   // Mutable lambda: can only be stored in a const Function:
448   int number = 3000;
449   Function<int()> func_mutable = [number]() mutable { return ++number; };
450   EXPECT_EQ(3001, func_mutable());
451   EXPECT_EQ(3002, func_mutable());
452
453   // test after const-casting
454
455   Function<int(int) const> func_made_const =
456       folly::constCastFunction(std::move(func));
457   EXPECT_EQ(1002, func_made_const(2));
458   EXPECT_THROW(func(0), std::bad_function_call);
459
460   Function<int(int)> func_const_made_nonconst = std::move(func_const);
461   EXPECT_EQ(2002, func_const_made_nonconst(2));
462   EXPECT_THROW(func_const(0), std::bad_function_call);
463
464   Function<int() const> func_mutable_made_const =
465       folly::constCastFunction(std::move(func_mutable));
466   EXPECT_EQ(3003, func_mutable_made_const());
467   EXPECT_EQ(3004, func_mutable_made_const());
468   EXPECT_THROW(func_mutable(), std::bad_function_call);
469 }
470
471 // TEST =====================================================================
472 // DataMember & MemberFunction
473
474 struct MemberFunc {
475   int x;
476   int getX() const {
477     return x;
478   }
479   void setX(int xx) {
480     x = xx;
481   }
482 };
483
484 TEST(Function, DataMember) {
485   MemberFunc mf;
486   MemberFunc const& cmf = mf;
487   mf.x = 123;
488
489   Function<int(MemberFunc const*)> data_getter1 = &MemberFunc::x;
490   EXPECT_EQ(123, data_getter1(&cmf));
491   Function<int(MemberFunc*)> data_getter2 = &MemberFunc::x;
492   EXPECT_EQ(123, data_getter2(&mf));
493   Function<int(MemberFunc const&)> data_getter3 = &MemberFunc::x;
494   EXPECT_EQ(123, data_getter3(cmf));
495   Function<int(MemberFunc&)> data_getter4 = &MemberFunc::x;
496   EXPECT_EQ(123, data_getter4(mf));
497 }
498
499 TEST(Function, MemberFunction) {
500   MemberFunc mf;
501   MemberFunc const& cmf = mf;
502   mf.x = 123;
503
504   Function<int(MemberFunc const*)> getter1 = &MemberFunc::getX;
505   EXPECT_EQ(123, getter1(&cmf));
506   Function<int(MemberFunc*)> getter2 = &MemberFunc::getX;
507   EXPECT_EQ(123, getter2(&mf));
508   Function<int(MemberFunc const&)> getter3 = &MemberFunc::getX;
509   EXPECT_EQ(123, getter3(cmf));
510   Function<int(MemberFunc&)> getter4 = &MemberFunc::getX;
511   EXPECT_EQ(123, getter4(mf));
512
513   Function<void(MemberFunc*, int)> setter1 = &MemberFunc::setX;
514   setter1(&mf, 234);
515   EXPECT_EQ(234, mf.x);
516
517   Function<void(MemberFunc&, int)> setter2 = &MemberFunc::setX;
518   setter2(mf, 345);
519   EXPECT_EQ(345, mf.x);
520 }
521
522 // TEST =====================================================================
523 // CaptureCopyMoveCount & ParameterCopyMoveCount
524
525 class CopyMoveTracker {
526  public:
527   struct ConstructorTag {};
528
529   CopyMoveTracker() = delete;
530   explicit CopyMoveTracker(ConstructorTag)
531       : data_(std::make_shared<std::pair<size_t, size_t>>(0, 0)) {}
532
533   CopyMoveTracker(CopyMoveTracker const& o) noexcept : data_(o.data_) {
534     ++data_->first;
535   }
536   CopyMoveTracker& operator=(CopyMoveTracker const& o) noexcept {
537     data_ = o.data_;
538     ++data_->first;
539     return *this;
540   }
541
542   CopyMoveTracker(CopyMoveTracker&& o) noexcept : data_(o.data_) {
543     ++data_->second;
544   }
545   CopyMoveTracker& operator=(CopyMoveTracker&& o) noexcept {
546     data_ = o.data_;
547     ++data_->second;
548     return *this;
549   }
550
551   size_t copyCount() const {
552     return data_->first;
553   }
554   size_t moveCount() const {
555     return data_->second;
556   }
557   size_t refCount() const {
558     return data_.use_count();
559   }
560   void resetCounters() {
561     data_->first = data_->second = 0;
562   }
563
564  private:
565   // copy, move
566   std::shared_ptr<std::pair<size_t, size_t>> data_;
567 };
568
569 TEST(Function, CaptureCopyMoveCount) {
570   // This test checks that no unnecessary copies/moves are made.
571
572   CopyMoveTracker cmt(CopyMoveTracker::ConstructorTag{});
573   EXPECT_EQ(0, cmt.copyCount());
574   EXPECT_EQ(0, cmt.moveCount());
575   EXPECT_EQ(1, cmt.refCount());
576
577   // Move into lambda, move lambda into Function
578   auto lambda1 = [cmt = std::move(cmt)]() {
579     return cmt.moveCount();
580   };
581   Function<size_t(void)> uf1 = std::move(lambda1);
582
583   // Max copies: 0. Max copy+moves: 2.
584   EXPECT_LE(cmt.moveCount() + cmt.copyCount(), 2);
585   EXPECT_LE(cmt.copyCount(), 0);
586
587   cmt.resetCounters();
588
589   // Move into lambda, copy lambda into Function
590   auto lambda2 = [cmt = std::move(cmt)]() {
591     return cmt.moveCount();
592   };
593   Function<size_t(void)> uf2 = lambda2;
594
595   // Max copies: 1. Max copy+moves: 2.
596   EXPECT_LE(cmt.moveCount() + cmt.copyCount(), 2);
597   EXPECT_LE(cmt.copyCount(), 1);
598
599   // Invoking Function must not make copies/moves of the callable
600   cmt.resetCounters();
601   uf1();
602   uf2();
603   EXPECT_EQ(0, cmt.copyCount());
604   EXPECT_EQ(0, cmt.moveCount());
605 }
606
607 TEST(Function, ParameterCopyMoveCount) {
608   // This test checks that no unnecessary copies/moves are made.
609
610   CopyMoveTracker cmt(CopyMoveTracker::ConstructorTag{});
611   EXPECT_EQ(0, cmt.copyCount());
612   EXPECT_EQ(0, cmt.moveCount());
613   EXPECT_EQ(1, cmt.refCount());
614
615   // pass by value
616   Function<size_t(CopyMoveTracker)> uf1 = [](CopyMoveTracker c) {
617     return c.moveCount();
618   };
619
620   cmt.resetCounters();
621   uf1(cmt);
622   // Max copies: 1. Max copy+moves: 2.
623   EXPECT_LE(cmt.moveCount() + cmt.copyCount(), 2);
624   EXPECT_LE(cmt.copyCount(), 1);
625
626   cmt.resetCounters();
627   uf1(std::move(cmt));
628   // Max copies: 1. Max copy+moves: 2.
629   EXPECT_LE(cmt.moveCount() + cmt.copyCount(), 2);
630   EXPECT_LE(cmt.copyCount(), 0);
631
632   // pass by reference
633   Function<size_t(CopyMoveTracker&)> uf2 = [](CopyMoveTracker& c) {
634     return c.moveCount();
635   };
636
637   cmt.resetCounters();
638   uf2(cmt);
639   // Max copies: 0. Max copy+moves: 0.
640   EXPECT_LE(cmt.moveCount() + cmt.copyCount(), 0);
641   EXPECT_LE(cmt.copyCount(), 0);
642
643   // pass by const reference
644   Function<size_t(CopyMoveTracker const&)> uf3 = [](CopyMoveTracker const& c) {
645     return c.moveCount();
646   };
647
648   cmt.resetCounters();
649   uf3(cmt);
650   // Max copies: 0. Max copy+moves: 0.
651   EXPECT_LE(cmt.moveCount() + cmt.copyCount(), 0);
652   EXPECT_LE(cmt.copyCount(), 0);
653
654   // pass by rvalue reference
655   Function<size_t(CopyMoveTracker &&)> uf4 = [](CopyMoveTracker&& c) {
656     return c.moveCount();
657   };
658
659   cmt.resetCounters();
660   uf4(std::move(cmt));
661   // Max copies: 0. Max copy+moves: 0.
662   EXPECT_LE(cmt.moveCount() + cmt.copyCount(), 0);
663   EXPECT_LE(cmt.copyCount(), 0);
664 }
665
666 // TEST =====================================================================
667 // VariadicTemplate & VariadicArguments
668
669 struct VariadicTemplateSum {
670   int operator()() const {
671     return 0;
672   }
673   template <class... Args>
674   int operator()(int x, Args... args) const {
675     return x + (*this)(args...);
676   }
677 };
678
679 TEST(Function, VariadicTemplate) {
680   Function<int(int)> uf1 = VariadicTemplateSum();
681   Function<int(int, int)> uf2 = VariadicTemplateSum();
682   Function<int(int, int, int)> uf3 = VariadicTemplateSum();
683
684   EXPECT_EQ(66, uf1(66));
685   EXPECT_EQ(99, uf2(55, 44));
686   EXPECT_EQ(66, uf3(33, 22, 11));
687 }
688
689 struct VariadicArgumentsSum {
690   int operator()(int count, ...) const {
691     int result = 0;
692     va_list args;
693     va_start(args, count);
694     for (int i = 0; i < count; ++i) {
695       result += va_arg(args, int);
696     }
697     va_end(args);
698     return result;
699   }
700 };
701
702 TEST(Function, VariadicArguments) {
703   Function<int(int)> uf1 = VariadicArgumentsSum();
704   Function<int(int, int)> uf2 = VariadicArgumentsSum();
705   Function<int(int, int, int)> uf3 = VariadicArgumentsSum();
706
707   EXPECT_EQ(0, uf1(0));
708   EXPECT_EQ(66, uf2(1, 66));
709   EXPECT_EQ(99, uf3(2, 55, 44));
710 }
711
712 // TEST =====================================================================
713 // SafeCaptureByReference
714
715 // A function can use Function const& as a parameter to signal that it
716 // is safe to pass a lambda that captures local variables by reference.
717 // It is safe because we know the function called can only invoke the
718 // Function until it returns. It can't store a copy of the Function
719 // (because it's not copyable), and it can't move the Function somewhere
720 // else (because it gets only a const&).
721
722 template <typename T>
723 void for_each(
724     T const& range,
725     Function<void(typename T::value_type const&) const> const& func) {
726   for (auto const& elem : range) {
727     func(elem);
728   }
729 }
730
731 TEST(Function, SafeCaptureByReference) {
732   std::vector<int> const vec = {20, 30, 40, 2, 3, 4, 200, 300, 400};
733
734   int sum = 0;
735
736   // for_each's second parameter is of type Function<...> const&.
737   // Hence we know we can safely pass it a lambda that references local
738   // variables. There is no way the reference to x will be stored anywhere.
739   for_each<std::vector<int>>(vec, [&sum](int x) { sum += x; });
740
741   // gcc versions before 4.9 cannot deduce the type T in the above call
742   // to for_each. Modern compiler versions can compile the following line:
743   //   for_each(vec, [&sum](int x) { sum += x; });
744
745   EXPECT_EQ(999, sum);
746 }
747
748 // TEST =====================================================================
749 // IgnoreReturnValue
750
751 TEST(Function, IgnoreReturnValue) {
752   int x = 95;
753
754   // Assign a lambda that return int to a folly::Function that returns void.
755   Function<void()> f = [&]() -> int { return ++x; };
756
757   EXPECT_EQ(95, x);
758   f();
759   EXPECT_EQ(96, x);
760
761   Function<int()> g = [&]() -> int { return ++x; };
762   Function<void()> cg = std::move(g);
763
764   EXPECT_EQ(96, x);
765   cg();
766   EXPECT_EQ(97, x);
767 }
768
769 // TEST =====================================================================
770 // ReturnConvertible, ConvertReturnType
771
772 TEST(Function, ReturnConvertible) {
773   struct CBase {
774     int x;
775   };
776   struct CDerived : CBase {};
777
778   Function<double()> f1 = []() -> int { return 5; };
779   EXPECT_EQ(5.0, f1());
780
781   Function<int()> f2 = []() -> double { return 5.2; };
782   EXPECT_EQ(5, f2());
783
784   CDerived derived;
785   derived.x = 55;
786
787   Function<CBase const&()> f3 = [&]() -> CDerived const& { return derived; };
788   EXPECT_EQ(55, f3().x);
789
790   Function<CBase const&()> f4 = [&]() -> CDerived& { return derived; };
791   EXPECT_EQ(55, f4().x);
792
793   Function<CBase&()> f5 = [&]() -> CDerived& { return derived; };
794   EXPECT_EQ(55, f5().x);
795
796   Function<CBase const*()> f6 = [&]() -> CDerived const* { return &derived; };
797   EXPECT_EQ(f6()->x, 55);
798
799   Function<CBase const*()> f7 = [&]() -> CDerived* { return &derived; };
800   EXPECT_EQ(55, f7()->x);
801
802   Function<CBase*()> f8 = [&]() -> CDerived* { return &derived; };
803   EXPECT_EQ(55, f8()->x);
804
805   Function<CBase()> f9 = [&]() -> CDerived {
806     auto d = derived;
807     d.x = 66;
808     return d;
809   };
810   EXPECT_EQ(66, f9().x);
811 }
812
813 TEST(Function, ConvertReturnType) {
814   struct CBase {
815     int x;
816   };
817   struct CDerived : CBase {};
818
819   Function<int()> f1 = []() -> int { return 5; };
820   Function<double()> cf1 = std::move(f1);
821   EXPECT_EQ(5.0, cf1());
822   Function<int()> ccf1 = std::move(cf1);
823   EXPECT_EQ(5, ccf1());
824
825   Function<double()> f2 = []() -> double { return 5.2; };
826   Function<int()> cf2 = std::move(f2);
827   EXPECT_EQ(5, cf2());
828   Function<double()> ccf2 = std::move(cf2);
829   EXPECT_EQ(5.0, ccf2());
830
831   CDerived derived;
832   derived.x = 55;
833
834   Function<CDerived const&()> f3 = [&]() -> CDerived const& { return derived; };
835   Function<CBase const&()> cf3 = std::move(f3);
836   EXPECT_EQ(55, cf3().x);
837
838   Function<CDerived&()> f4 = [&]() -> CDerived& { return derived; };
839   Function<CBase const&()> cf4 = std::move(f4);
840   EXPECT_EQ(55, cf4().x);
841
842   Function<CDerived&()> f5 = [&]() -> CDerived& { return derived; };
843   Function<CBase&()> cf5 = std::move(f5);
844   EXPECT_EQ(55, cf5().x);
845
846   Function<CDerived const*()> f6 = [&]() -> CDerived const* {
847     return &derived;
848   };
849   Function<CBase const*()> cf6 = std::move(f6);
850   EXPECT_EQ(55, cf6()->x);
851
852   Function<CDerived const*()> f7 = [&]() -> CDerived* { return &derived; };
853   Function<CBase const*()> cf7 = std::move(f7);
854   EXPECT_EQ(55, cf7()->x);
855
856   Function<CDerived*()> f8 = [&]() -> CDerived* { return &derived; };
857   Function<CBase*()> cf8 = std::move(f8);
858   EXPECT_EQ(55, cf8()->x);
859
860   Function<CDerived()> f9 = [&]() -> CDerived {
861     auto d = derived;
862     d.x = 66;
863     return d;
864   };
865   Function<CBase()> cf9 = std::move(f9);
866   EXPECT_EQ(66, cf9().x);
867 }
868
869 // TEST =====================================================================
870 // asStdFunction_*
871
872 TEST(Function, asStdFunction_void) {
873   int i = 0;
874   folly::Function<void()> f = [&] { ++i; };
875   auto sf = std::move(f).asStdFunction();
876   static_assert(std::is_same<decltype(sf), std::function<void()>>::value,
877       "std::function has wrong type");
878   sf();
879   EXPECT_EQ(1, i);
880 }
881
882 TEST(Function, asStdFunction_void_const) {
883   int i = 0;
884   folly::Function<void() const> f = [&] { ++i; };
885   auto sf = std::move(f).asStdFunction();
886   static_assert(std::is_same<decltype(sf), std::function<void()>>::value,
887       "std::function has wrong type");
888   sf();
889   EXPECT_EQ(1, i);
890 }
891
892 TEST(Function, asStdFunction_return) {
893   int i = 0;
894   folly::Function<int()> f = [&] {
895     ++i;
896     return 42;
897   };
898   auto sf = std::move(f).asStdFunction();
899   static_assert(std::is_same<decltype(sf), std::function<int()>>::value,
900       "std::function has wrong type");
901   EXPECT_EQ(42, sf());
902   EXPECT_EQ(1, i);
903 }
904
905 TEST(Function, asStdFunction_return_const) {
906   int i = 0;
907   folly::Function<int() const> f = [&] {
908     ++i;
909     return 42;
910   };
911   auto sf = std::move(f).asStdFunction();
912   static_assert(std::is_same<decltype(sf), std::function<int()>>::value,
913       "std::function has wrong type");
914   EXPECT_EQ(42, sf());
915   EXPECT_EQ(1, i);
916 }
917
918 TEST(Function, asStdFunction_args) {
919   int i = 0;
920   folly::Function<void(int, int)> f = [&](int x, int y) {
921     ++i;
922     return x + y;
923   };
924   auto sf = std::move(f).asStdFunction();
925   static_assert(std::is_same<decltype(sf), std::function<void(int, int)>>::value,
926       "std::function has wrong type");
927   sf(42, 42);
928   EXPECT_EQ(1, i);
929 }
930
931 TEST(Function, asStdFunction_args_const) {
932   int i = 0;
933   folly::Function<void(int, int) const> f = [&](int x, int y) {
934     ++i;
935     return x + y;
936   };
937   auto sf = std::move(f).asStdFunction();
938   static_assert(std::is_same<decltype(sf), std::function<void(int, int)>>::value,
939       "std::function has wrong type");
940   sf(42, 42);
941   EXPECT_EQ(1, i);
942 }
943
944 // TEST =====================================================================
945 // asSharedProxy_*
946
947 TEST(Function, asSharedProxy_void) {
948   int i = 0;
949   folly::Function<void()> f = [&i] { ++i; };
950   auto sp = std::move(f).asSharedProxy();
951   auto spcopy = sp;
952   sp();
953   EXPECT_EQ(1, i);
954   spcopy();
955   EXPECT_EQ(2, i);
956 }
957
958 TEST(Function, asSharedProxy_void_const) {
959   int i = 0;
960   folly::Function<void() const> f = [&i] { ++i; };
961   auto sp = std::move(f).asSharedProxy();
962   auto spcopy = sp;
963   sp();
964   EXPECT_EQ(1, i);
965   spcopy();
966   EXPECT_EQ(2, i);
967 }
968
969 TEST(Function, asSharedProxy_return) {
970   folly::Function<int()> f = [i = 0]() mutable {
971     ++i;
972     return i;
973   };
974   auto sp = std::move(f).asSharedProxy();
975   auto spcopy = sp;
976   EXPECT_EQ(1, sp());
977   EXPECT_EQ(2, spcopy());
978 }
979
980 TEST(Function, asSharedProxy_return_const) {
981   int i = 0;
982   folly::Function<int() const> f = [&i] {
983     ++i;
984     return i;
985   };
986   auto sp = std::move(f).asSharedProxy();
987   auto spcopy = sp;
988   EXPECT_EQ(1, sp());
989   EXPECT_EQ(2, spcopy());
990 }
991
992 TEST(Function, asSharedProxy_args) {
993   int i = 0;
994   folly::Function<int(int, int)> f = [&](int x, int y) mutable {
995     ++i;
996     return x + y * 2;
997   };
998   auto sp = std::move(f).asSharedProxy();
999   auto spcopy = sp;
1000   EXPECT_EQ(120, sp(100, 10));
1001   EXPECT_EQ(1, i);
1002   EXPECT_EQ(120, spcopy(100, 10));
1003   EXPECT_EQ(2, i);
1004 }
1005
1006 TEST(Function, asSharedProxy_args_const) {
1007   int i = 0;
1008   folly::Function<int(int, int) const> f = [&i](int x, int y) {
1009     ++i;
1010     return x * 100 + y * 10 + i;
1011   };
1012   auto sp = std::move(f).asSharedProxy();
1013   auto spcopy = sp;
1014   EXPECT_EQ(561, sp(5, 6));
1015   EXPECT_EQ(562, spcopy(5, 6));
1016 }
1017
1018 TEST(Function, NoAllocatedMemoryAfterMove) {
1019   Functor<int, 100> foo;
1020
1021   Function<int(size_t)> func = foo;
1022   EXPECT_TRUE(func.hasAllocatedMemory());
1023
1024   Function<int(size_t)> func2 = std::move(func);
1025   EXPECT_TRUE(func2.hasAllocatedMemory());
1026   EXPECT_FALSE(func.hasAllocatedMemory());
1027 }
1028
1029 TEST(Function, ConstCastEmbedded) {
1030   int x = 0;
1031   auto functor = [&x]() { ++x; };
1032
1033   Function<void() const> func(functor);
1034   EXPECT_FALSE(func.hasAllocatedMemory());
1035
1036   Function<void()> func2(std::move(func));
1037   EXPECT_FALSE(func2.hasAllocatedMemory());
1038 }
1039
1040 TEST(Function, EmptyAfterConstCast) {
1041   Function<int(size_t)> func;
1042   EXPECT_FALSE(func);
1043
1044   Function<int(size_t) const> func2 = constCastFunction(std::move(func));
1045   EXPECT_FALSE(func2);
1046 }
1047
1048 TEST(Function, SelfStdSwap) {
1049   Function<int()> f = [] { return 42; };
1050   f.swap(f);
1051   EXPECT_TRUE(bool(f));
1052   EXPECT_EQ(42, f());
1053   std::swap(f, f);
1054   EXPECT_TRUE(bool(f));
1055   EXPECT_EQ(42, f());
1056   folly::swap(f, f);
1057   EXPECT_TRUE(bool(f));
1058   EXPECT_EQ(42, f());
1059 }
1060
1061 TEST(Function, SelfMove) {
1062   Function<int()> f = [] { return 42; };
1063   Function<int()>& g = f;
1064   f = std::move(g); // shouldn't crash!
1065   (void)bool(f); // valid but unspecified state
1066   f = [] { return 43; };
1067   EXPECT_TRUE(bool(f));
1068   EXPECT_EQ(43, f());
1069 }
1070
1071 TEST(Function, DeducableArguments) {
1072   deduceArgs(Function<void()>{[] {}});
1073   deduceArgs(Function<void(int, float)>{[](int, float) {}});
1074   deduceArgs(Function<int(int, float)>{[](int i, float) { return i; }});
1075 }
1076
1077 TEST(Function, CtorWithCopy) {
1078   struct X {
1079     X() {}
1080     X(X const&) noexcept(true) {}
1081     X& operator=(X const&) = default;
1082   };
1083   struct Y {
1084     Y() {}
1085     Y(Y const&) noexcept(false) {}
1086     Y(Y&&) noexcept(true) {}
1087     Y& operator=(Y&&) = default;
1088     Y& operator=(Y const&) = default;
1089   };
1090   auto lx = [x = X()]{};
1091   auto ly = [y = Y()]{};
1092   EXPECT_TRUE(noexcept(Function<void()>(lx)));
1093   EXPECT_FALSE(noexcept(Function<void()>(ly)));
1094 }