summaryrefslogtreecommitdiff
path: root/src/util/callback.h
blob: df93b5972ff0f0acadde30c4105b4626abebf533 (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
#pragma once
#include "typedef.h"

template <typename T>
struct FN;

template <typename RET, typename... ARGS>
struct FN<RET(ARGS...)> {
  // voodoo
  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...); };

  void* data;
  U32 size;
  RET( *invoke )( void*, ARGS... );
  void( *destroy )( void* );
  void*( *clone )( void* );

  template <typename F>
  FN( F&& f ) {
    using __stripped = typename __strip_ref<F>::type;
    data = new __stripped( static_cast<F&&>(f) );
    size = sizeof( __stripped );
    invoke = pfn( void* d, ARGS... args ) -> RET {
      return ( *(__stripped*)d )( args... );
    };
    destroy = pfn( void* d ) {
      delete (__stripped*)d;
    };
    clone = pfn( void* data ) {
      return (void*)new __stripped( *(__stripped*)data );
    };
  }

  template <>
  FN( int&& ) : data( 0 ), invoke( 0 ), destroy( 0 ) {}
  FN() : data( 0 ), invoke( 0 ), destroy( 0 ) {}

  FN( FN&& other ) : data( other.data ), invoke( other.invoke ), destroy( other.destroy ) {
    other.data = 0;
    other.invoke = 0;
    other.destroy = 0;
  }

  FN& operator=( FN&& other ) {
    if( this == &other ) return *this;
    if( destroy ) destroy( data );
    data = other.data;
    invoke = other.invoke;
    destroy = other.destroy;
    other.data = 0;
    other.invoke = 0;
    other.destroy = 0;
    return *this;
  }

  FN( const FN& other ) {
    *this = other;
  };

  FN& operator=( const FN& other ) {
    if( !other.data ) {
      data = 0;
      invoke = 0;
      destroy = 0;
      size = 0;
      return *this;
    }

    size = other.size;
    data = other.clone( other.data );
    invoke = other.invoke;
    destroy = other.destroy;
    clone = other.clone;
    return *this;
  }

  ~FN() { if( destroy ) destroy( data ); }
  operator bool() const { return !!invoke; }

  RET operator()( ARGS... args ) const {
    return invoke( data, args... );
  }

};