-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdeferOperation.hpp
117 lines (85 loc) · 2.47 KB
/
deferOperation.hpp
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
/*!
\file deferOperation.hpp
\date 12.09.2021
\author Ildar Kasimov
The library provides 'defer' operator that Go programming language introduces. The closest
analogue in C++ is Boost.ScopeExit or some implementations of scope_guard.
The usage of the library is pretty simple, just copy this file into your enviornment and
predefine DEFER_IMPLEMENTATION macro before its inclusion like the following
\code
#define DEFER_IMPLEMENTATION
#include "library_template.hpp"
\endcode
*/
#pragma once
#include <cassert>
#include <functional>
///< Library's configs
#define DEFER_DISABLE_EXCEPTIONS 1
#define DEFER_ENABLE_EXPORT 1
#define DEFER_REDEFINE_NEW_KEYWORD 1
#define DEFER_DEBUG_OUTPUT_STREAM stdout
#if DEFER_DISABLE_EXCEPTIONS
#define DEFER_NOEXCEPT noexcept
#else
#define DEFER_NOEXCEPT
#endif
#if DEFER_ENABLE_EXPORT
#if defined(_WIN32) || defined(_MSC_VER)
#if !defined(WRENCH_APIENTRY)
#define WRENCH_APIENTRY __cdecl ///< Calling convention for VS
#endif
#if !defined(WRENCH_API)
#if defined(WRENCH_DLLIMPORT)
#define WRENCH_API __declspec(dllimport)
#else
#define WRENCH_API __declspec(dllexport)
#endif
#endif
#elif defined(__GNUC__)
#if !defined(WRENCH_APIENTRY)
#define WRENCH_APIENTRY __attribute__((cdecl)) ///< Calling convention for GNUC
#endif
#if !defined(WRENCH_API)
#if defined(WRENCH_DLLIMPORT)
#define WRENCH_API
#else
#define WRENCH_API __attribute__((visibility("default")))
#endif
#endif
#else /// Unknown platform and compiler
#define WRENCH_API
#endif
#endif
#define WRENCH_ASSERT(condition) assert(condition)
#define WRENCH_UNREACHABLE() do { assert(false); } while(false)
namespace Wrench
{
struct TDeferOperation
{
typedef std::function<void()> TActionCallback;
explicit TDeferOperation(TActionCallback action);
~TDeferOperation();
TDeferOperation() = delete;
TDeferOperation(TDeferOperation&) = delete;
TDeferOperation(TDeferOperation&&) = delete;
TActionCallback mAction = nullptr;
};
#define DEFER_CONCAT_ID_IMPL(left, right) left ## right
#define DEFER_CONCAT_ID(left, right) DEFER_CONCAT_ID_IMPL(left, right)
#define DEFER_ID(id) DEFER_CONCAT_ID(id, DEFER_CONCAT_ID(__COUNTER__, __LINE__))
#define defer(op) const TDeferOperation DEFER_ID(deferOp)(op)
#if defined(DEFER_IMPLEMENTATION)
TDeferOperation::TDeferOperation(std::function<void()> action):
mAction(action)
{
}
TDeferOperation::~TDeferOperation()
{
if (mAction)
{
mAction();
}
}
#endif
}