summaryrefslogtreecommitdiffstats
path: root/include/jau/function_def.hpp
blob: 3d802257d2f77c74416a440f46ac42b8c5619648 (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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
/*
 * Author: Sven Gothel <sgothel@jausoft.com>
 * Copyright (c) 2020 Gothel Software e.K.
 * Copyright (c) 2020 ZAFENA AB
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#ifndef JAU_FUNCTION_HPP_
#define JAU_FUNCTION_HPP_

#include <cstring>
#include <string>
#include <memory>
#include <cstdint>
#include <vector>
#include <functional>

#include <jau/basic_types.hpp>

namespace jau {

    /**
     * One goal to _produce_ the member-function type instance
     * is to be class type agnostic for storing in the toolkit.
     * This is essential to utilize a function-callback API,
     * where only the provider of an instance knows about its class type.
     *
     * Further we can't utilize std::function and std::bind,
     * as std::function doesn't provide details about the
     * member-function-call identity and hence lacks of
     * the equality operator and
     * std::bind doesn't even specify a return type.
     *
     * A capturing lambda in C++-11, does produce decoration code
     * accessing the captured elements, i.e. an anonymous helper class.
     * Due to this fact, the return type is an undefined lambda specific
     * and hence we can't use it to feed the function invocation
     * into ClassFunction<> using a well specified type.
     *
     * <pre>
        template<typename R, typename C, typename... A>
        inline ClassFunction<R, A...>
        bindClassFunction(C *base, R(C::*mfunc)(A...)) {
            return ClassFunction<R, A...>(
                    (void*)base,
                    (void*)(*((void**)&mfunc)),
                    [&](A... args)->R{ (base->*mfunc)(args...); });
                     ^
                     | Capturing lambda function-pointer are undefined!
        }
        </pre>
     *
     * Hence we need to manually produce the on-the-fly invocation data type
     * to capture details on the caller's class type for the member-function-call,
     * which are then being passed to the ClassFunction<> anonymously
     * while still being able to perform certain operations
     * like equality operation for identity.
     */
    template<typename R, typename... A>
    class InvocationFunc {
        protected:
            InvocationFunc() noexcept {}

        public:
            virtual ~InvocationFunc() noexcept {}

            InvocationFunc(const InvocationFunc &o) noexcept = default;
            InvocationFunc(InvocationFunc &&o) noexcept = default;
            InvocationFunc& operator=(const InvocationFunc &o) noexcept = default;
            InvocationFunc& operator=(InvocationFunc &&o) noexcept = default;

            /** Poor man's RTTI */
            virtual int getType() const noexcept = 0;

            virtual InvocationFunc<R, A...> * clone() const noexcept = 0;

            virtual R invoke(A... args) = 0;

            virtual bool operator==(const InvocationFunc<R, A...>& rhs) const noexcept = 0;

            virtual bool operator!=(const InvocationFunc<R, A...>& rhs) const noexcept = 0;

            virtual std::string toString() const = 0;
    };

    template<typename R, typename... A>
    class NullInvocationFunc : public InvocationFunc<R, A...> {
        public:
            NullInvocationFunc() noexcept { }

            int getType() const noexcept override { return 0; }

            InvocationFunc<R, A...> * clone() const noexcept override { return new NullInvocationFunc(); }

            R invoke(A...) override {
                return (R)0;
            }

            bool operator==(const InvocationFunc<R, A...>& rhs) const noexcept override
            {
                return getType() == rhs.getType();
            }

            bool operator!=(const InvocationFunc<R, A...>& rhs) const noexcept override
            {
                return !( *this == rhs );
            }

            std::string toString() const override {
                return "NullInvocation";
            }
    };

    template<typename R, typename C, typename... A>
    class ClassInvocationFunc : public InvocationFunc<R, A...> {
        private:
            C* base;
            R(C::*member)(A...);

        public:
            ClassInvocationFunc(C *_base, R(C::*_member)(A...)) noexcept
            : base(_base), member(_member) {
            }

            int getType() const noexcept override { return 1; }

            InvocationFunc<R, A...> * clone() const noexcept override { return new ClassInvocationFunc(*this); }

            R invoke(A... args) override {
                return (base->*member)(args...);
            }

            bool operator==(const InvocationFunc<R, A...>& rhs) const noexcept override
            {
                if( &rhs == this ) {
                    return true;
                }
                if( getType() != rhs.getType() ) {
                    return false;
                }
                const ClassInvocationFunc<R, C, A...> * prhs = static_cast<const ClassInvocationFunc<R, C, A...>*>(&rhs);
                return base == prhs->base && member == prhs->member;
            }

            bool operator!=(const InvocationFunc<R, A...>& rhs) const noexcept override
            {
                return !( *this == rhs );
            }

            std::string toString() const override {
                // hack to convert member pointer to void *: '*((void**)&member)'
                return "ClassInvocation "+to_hexstring((uint64_t)base)+"->"+to_hexstring( *((void**)&member) );
            }
    };

    template<typename R, typename... A>
    class PlainInvocationFunc : public InvocationFunc<R, A...> {
        private:
            R(*function)(A...);

        public:
            PlainInvocationFunc(R(*_function)(A...)) noexcept
            : function(_function) {
            }

            int getType() const noexcept override { return 2; }

            InvocationFunc<R, A...> * clone() const noexcept override { return new PlainInvocationFunc(*this); }

            R invoke(A... args) override {
                return (*function)(args...);
            }

            bool operator==(const InvocationFunc<R, A...>& rhs) const noexcept override
            {
                if( &rhs == this ) {
                    return true;
                }
                if( getType() != rhs.getType() ) {
                    return false;
                }
                const PlainInvocationFunc<R, A...> * prhs = static_cast<const PlainInvocationFunc<R, A...>*>(&rhs);
                return function == prhs->function;
            }

            bool operator!=(const InvocationFunc<R, A...>& rhs) const noexcept override
            {
                return !( *this == rhs );
            }

            std::string toString() const override {
                // hack to convert function pointer to void *: '*((void**)&function)'
                return "PlainInvocation "+to_hexstring( *((void**)&function) );
            }
    };

    template<typename R, typename I, typename... A>
    class CaptureInvocationFunc : public InvocationFunc<R, A...> {
        private:
            I data;
            R(*function)(I&, A...);
            bool dataIsIdentity;

        public:
            /** Utilizes copy-ctor from 'const I& _data' */
            CaptureInvocationFunc(const I& _data, R(*_function)(I&, A...), bool dataIsIdentity_) noexcept
            : data(_data), function(_function), dataIsIdentity(dataIsIdentity_) {
            }

            /** Utilizes move-ctor from moved 'I&& _data' */
            CaptureInvocationFunc(I&& _data, R(*_function)(I&, A...), bool dataIsIdentity_) noexcept
            : data(std::move(_data)), function(_function), dataIsIdentity(dataIsIdentity_) {
            }

            int getType() const noexcept override { return 3; }

            InvocationFunc<R, A...> * clone() const noexcept override { return new CaptureInvocationFunc(*this); }

            R invoke(A... args) override {
                return (*function)(data, args...);
            }

            bool operator==(const InvocationFunc<R, A...>& rhs) const noexcept override
            {
                if( &rhs == this ) {
                    return true;
                }
                if( getType() != rhs.getType() ) {
                    return false;
                }
                const CaptureInvocationFunc<R, I, A...> * prhs = static_cast<const CaptureInvocationFunc<R, I, A...>*>(&rhs);
                return dataIsIdentity == prhs->dataIsIdentity && function == prhs->function && ( !dataIsIdentity || data == prhs->data );
            }

            bool operator!=(const InvocationFunc<R, A...>& rhs) const noexcept override
            {
                return !( *this == rhs );
            }

            std::string toString() const override {
                // hack to convert function pointer to void *: '*((void**)&function)'
                return "CaptureInvocation "+to_hexstring( *((void**)&function) );
            }
    };

    template<typename R, typename... A>
    class StdInvocationFunc : public InvocationFunc<R, A...> {
        private:
            uint64_t id;
            std::function<R(A...)> function;

        public:
            StdInvocationFunc(uint64_t _id, std::function<R(A...)> _function) noexcept
            : id(_id), function(_function) {
            }
            StdInvocationFunc(uint64_t _id) noexcept
            : id(_id), function() {
            }

            int getType() const noexcept override { return 10; }

            InvocationFunc<R, A...> * clone() const noexcept override { return new StdInvocationFunc(*this); }

            R invoke(A... args) override {
                return function(args...);
            }

            bool operator==(const InvocationFunc<R, A...>& rhs) const noexcept override
            {
                if( &rhs == this ) {
                    return true;
                }
                if( getType() != rhs.getType() ) {
                    return false;
                }
                const StdInvocationFunc<R, A...> * prhs = static_cast<const StdInvocationFunc<R, A...>*>(&rhs);
                return id == prhs->id;
            }

            bool operator!=(const InvocationFunc<R, A...>& rhs) const noexcept override
            {
                return !( *this == rhs );
            }

            std::string toString() const override {
                return "StdInvocation "+to_hexstring( id );
            }
    };

    template<typename R, typename... A>
    class FunctionDef {
        private:
            std::shared_ptr<InvocationFunc<R, A...>> func;

        public:
            /**
             * Constructs an instance with a null function.
             */
            FunctionDef() noexcept
            : func( new NullInvocationFunc<R, A...>() ) { }

            /**
             * Constructs an instance by wrapping the given naked InvocationFunc<R, A...> function pointer
             * in a shared_ptr and taking ownership.
             */
            FunctionDef(InvocationFunc<R, A...> * _funcPtr) noexcept
            : func( _funcPtr ) { }

            /**
             * Constructs an instance using the shared InvocationFunc<R, A...> function.
             */
            explicit FunctionDef(std::shared_ptr<InvocationFunc<R, A...>> _func) noexcept
            : func( _func ) { }

            FunctionDef(const FunctionDef &o) noexcept = default;
            FunctionDef(FunctionDef &&o) noexcept = default;
            FunctionDef& operator=(const FunctionDef &o) noexcept = default;
            FunctionDef& operator=(FunctionDef &&o) noexcept= default;

            bool operator==(const FunctionDef<R, A...>& rhs) const noexcept
            { return *func == *rhs.func; }

            bool operator!=(const FunctionDef<R, A...>& rhs) const noexcept
            { return *func != *rhs.func; }

            /** Returns the shared InvocationFunc<R, A...> function */
            std::shared_ptr<InvocationFunc<R, A...>> getFunction() noexcept { return func; }

            /** Returns a new instance of the held InvocationFunc<R, A...> function. */
            InvocationFunc<R, A...> * cloneFunction() const noexcept { return func->clone(); }

            std::string toString() const {
                return "FunctionDef["+func->toString()+"]";
            }

            R invoke(A... args) {
                return func->invoke(args...);
            }
    };

    template<typename R, typename C, typename... A>
    inline jau::FunctionDef<R, A...>
    bindMemberFunc(C *base, R(C::*mfunc)(A...)) noexcept {
        return FunctionDef<R, A...>( new ClassInvocationFunc<R, C, A...>(base, mfunc) );
    }

    template<typename R, typename... A>
    inline jau::FunctionDef<R, A...>
    bindPlainFunc(R(*func)(A...)) noexcept {
        return FunctionDef<R, A...>( new PlainInvocationFunc<R, A...>(func) );
    }

    /**
     * <code>const I& data</code> will be copied into the InvocationFunc<..> specialization
     * and hence captured by copy.
     * <p>
     * The function call will have the reference of the copied data being passed for efficiency.
     * </p>
     */
    template<typename R, typename I, typename... A>
    inline jau::FunctionDef<R, A...>
    bindCaptureFunc(const I& data, R(*func)(I&, A...), bool dataIsIdentity=true) noexcept {
        return FunctionDef<R, A...>( new CaptureInvocationFunc<R, I, A...>(data, func, dataIsIdentity) );
    }

    /**
     * <code>I&& data</code> will be moved into the InvocationFunc<..> specialization.
     * <p>
     * The function call will have the reference of the copied data being passed for efficiency.
     * </p>
     */
    template<typename R, typename I, typename... A>
    inline jau::FunctionDef<R, A...>
    bindCaptureFunc(I&& data, R(*func)(I&, A...), bool dataIsIdentity=true) noexcept {
        return FunctionDef<R, A...>( new CaptureInvocationFunc<R, I, A...>(std::move(data), func, dataIsIdentity) );
    }

    template<typename R, typename... A>
    inline jau::FunctionDef<R, A...>
    bindStdFunc(uint64_t id, std::function<R(A...)> func) noexcept {
        return FunctionDef<R, A...>( new StdInvocationFunc<R, A...>(id, func) );
    }
    template<typename R, typename... A>
    inline jau::FunctionDef<R, A...>
    bindStdFunc(uint64_t id) noexcept {
        return FunctionDef<R, A...>( new StdInvocationFunc<R, A...>(id) );
    }

} // namespace jau

/** \example test_functiondef01.cpp
 * This C++ unit test validates the jau::FunctionDef and all its jau::InvocationFunc specializations.
 */

#endif /* JAU_FUNCTION_HPP_ */