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
|
#pragma once
#include "typedef.h"
template <typename T>
struct FN;
// voodoo
template <typename RET, typename... ARGS>
struct FN<RET(ARGS...)> {
template <typename T> struct __strip_ref { using type = T; };
template <typename T> struct __strip_ref<T&> { using type = T; };
template <typename T> struct __strip_ref<T&&> { using type = T; };
template <typename R, typename... A> struct __strip_ref<R(A...)> { using type = R(*)(A...); };
template <typename R, typename... A> struct __strip_ref<R(&)(A...)> { using type = R(*)(A...); };
static const unsigned int BUF_SIZE = 32;
alignas(8) char buf[BUF_SIZE];
void* data;
RET( *invoke )( void*, ARGS... );
void( *destroy )( void* );
void*( *clone )( void*, char* );
template <typename F>
FN(F&& f) {
using __stripped = typename __strip_ref<F>::type;
if constexpr( sizeof(__stripped) <= BUF_SIZE ) {
new (buf) __stripped( f );
data = buf;
destroy = pfn( void* d ) {
( (__stripped*)d )->~__stripped();
};
clone = pfn( void* d, char* dst ) -> void* {
new (dst) __stripped( *(__stripped*)d );
return dst;
};
} else {
data = new __stripped( f );
destroy = pfn( void* d ) {
delete (__stripped*)d;
};
clone = pfn( void* d, char* dst ) -> void* {
return new __stripped( *(__stripped*)d );
};
}
invoke = pfn( void* d, ARGS... args ) -> RET {
return ( *(__stripped*)d )( args... );
};
}
FN( I32&& ) : data( 0 ), invoke( 0 ), destroy( 0 ), clone( 0 ) {}
FN( U32&& ) : data( 0 ), invoke( 0 ), destroy( 0 ), clone( 0 ) {}
FN() : data( 0 ), invoke( 0 ), destroy( 0 ), clone( 0 ) {}
FN( const FN& other ) : invoke( other.invoke ), destroy( other.destroy ), clone( other.clone ) {
if( !other.data ) {
data = 0;
return;
}
data = other.clone( other.data, buf );
}
FN& operator=( const FN& other ) {
if( this == &other ) return *this;
if( destroy && data ) destroy( data );
invoke = other.invoke;
destroy = other.destroy;
clone = other.clone;
data = other.data ? other.clone( other.data, buf ) : 0;
return *this;
}
~FN() {
if( destroy && data ) destroy( data );
}
RET operator()( ARGS... args ) const {
return invoke( data, args... );
}
operator bool() const { return !!invoke; }
};
|