blob: 0feef7c04c00cd54e3a81c0bd903ff754e97ce5d [file] [log] [blame]
mtklein4a9426f2015-03-31 14:24:27 -07001/*
2 * Copyright 2015 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8#include "SkFunction.h"
9#include "Test.h"
10
11static void test_add_five(skiatest::Reporter* r, SkFunction<int(int)>&& f) {
mtklein97312d02015-04-01 08:11:16 -070012 REPORTER_ASSERT(r, f(3) == 8);
mtklein4a9426f2015-03-31 14:24:27 -070013 REPORTER_ASSERT(r, f(4) == 9);
14}
15
16static int add_five(int x) { return x + 5; }
17
18struct AddFive {
19 int operator()(int x) { return x + 5; };
20};
21
mtklein03e51612015-04-01 13:08:50 -070022class MoveOnlyAdd5 : SkNoncopyable {
23public:
24 MoveOnlyAdd5() {}
25 MoveOnlyAdd5(MoveOnlyAdd5&&) {}
26 MoveOnlyAdd5& operator=(MoveOnlyAdd5&&) { return *this; }
27
28 int operator()(int x) { return x + 5; }
29};
30
mtklein4a9426f2015-03-31 14:24:27 -070031DEF_TEST(Function, r) {
32 // We should be able to turn a static function, an explicit functor, or a lambda
33 // all into an SkFunction equally well.
mtklein03e51612015-04-01 13:08:50 -070034 test_add_five(r, &add_five);
35 test_add_five(r, AddFive());
36 test_add_five(r, [](int x) { return x + 5; });
mtklein97312d02015-04-01 08:11:16 -070037
38 // AddFive and the lambda above are both small enough to test small-object optimization.
39 // Now test a lambda that's much too large for the small-object optimization.
40 int a = 1, b = 1, c = 1, d = 1, e = 1;
mtklein03e51612015-04-01 13:08:50 -070041 test_add_five(r, [&](int x) { return x + a + b + c + d + e; });
mtklein74415272015-04-01 11:26:31 -070042
43 // Makes sure we forward the functor when constructing SkFunction.
mtklein03e51612015-04-01 13:08:50 -070044 test_add_five(r, MoveOnlyAdd5());
mtklein74415272015-04-01 11:26:31 -070045
46 // Makes sure we forward arguments when calling SkFunction.
mtkleinb41f0572015-04-01 13:36:23 -070047 SkFunction<int(int, MoveOnlyAdd5&&, int)> f([](int x, MoveOnlyAdd5&& addFive, int y) {
48 return x * addFive(y);
49 });
50 REPORTER_ASSERT(r, f(2, MoveOnlyAdd5(), 4) == 18);
mtklein74415272015-04-01 11:26:31 -070051}