aboutsummaryrefslogtreecommitdiffhomepage
path: root/include/private/SkFunction.h
blob: 6be95394c8f8ac0116e1f090b475de5cfa56393e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/*
 * Copyright 2015 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#ifndef SkFunction_DEFINED
#define SkFunction_DEFINED

// TODO: document, more pervasive move support in constructors, small-Fn optimization

#include "SkUtility.h"
#include "SkUniquePtr.h"
#include "SkTypes.h"

template <typename> class SkFunction;

template <typename R, typename... Args>
class SkFunction<R(Args...)> {
public:
    SkFunction() {}

    template <typename Fn>
    SkFunction(const Fn& fn)
        : fFunction(new LambdaImpl<Fn>(fn)) {}

    SkFunction(R (*fn)(Args...)) : fFunction(new FnPtrImpl(fn)) {}

    SkFunction(const SkFunction& other) { *this = other; }
    SkFunction& operator=(const SkFunction& other) {
        if (this != &other) {
            fFunction.reset(other.fFunction.get() ? other.fFunction->clone() : nullptr);
        }
        return *this;
    }

    R operator()(Args... args) const {
        SkASSERT(fFunction.get());
        return fFunction->call(skstd::forward<Args>(args)...);
    }

private:
    struct Interface {
        virtual ~Interface() {}
        virtual R call(Args...) const = 0;
        virtual Interface* clone() const = 0;
    };

    template <typename Fn>
    class LambdaImpl final : public Interface {
    public:
        LambdaImpl(const Fn& fn) : fFn(fn) {}

        R call(Args... args) const override { return fFn(skstd::forward<Args>(args)...); }
        Interface* clone() const override { return new LambdaImpl<Fn>(fFn); }

    private:
        Fn fFn;
    };

    class FnPtrImpl final : public Interface {
    public:
        FnPtrImpl(R (*fn)(Args...)) : fFn(fn) {}

        R call(Args... args) const override { return fFn(skstd::forward<Args>(args)...); }
        Interface* clone() const override { return new FnPtrImpl(fFn); }

    private:
        R (*fFn)(Args...);
    };

    skstd::unique_ptr<Interface> fFunction;
};

#endif//SkFunction_DEFINED