-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcollapse_function.h
94 lines (76 loc) · 1.79 KB
/
collapse_function.h
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
#ifndef collapse_function_h
#define collapse_function_h
#include <functional>
#include <chrono>
namespace async
{
class collapse_function_execute
{
public:
collapse_function_execute() = delete;
protected:
collapse_function_execute(std::chrono::milliseconds grace_period)
: grace_period_(grace_period)
{ }
protected:
bool is_locked() const
{
auto now = std::chrono::high_resolution_clock::now();
auto delta = now - start_time_;
if (delta > grace_period_)
{
start_time_ = now;
return false;
}
return true;
}
private:
std::chrono::milliseconds grace_period_;
mutable std::chrono::high_resolution_clock::time_point start_time_;
};
template<typename... args_types>
class collapse_function final : private collapse_function_execute
{
public:
collapse_function(
std::chrono::milliseconds grace_period,
const std::function<void(args_types...)>& fn
)
: collapse_function_execute(grace_period), fn_(fn)
{ }
public:
void operator()(args_types... args) const
{
if (is_locked())
{
return;
}
fn_(std::forward<args_types>(args)...);
}
private:
std::function<void(args_types...)> fn_;
};
template<>
class collapse_function<void> final : private collapse_function_execute
{
public:
collapse_function(
std::chrono::milliseconds grace_period,
const std::function<void()>& fn
)
: collapse_function_execute(grace_period), fn_(fn)
{ }
public:
void operator()() const
{
if (is_locked())
{
return;
}
fn_();
}
private:
std::function<void()> fn_;
};
} // namespace async
#endif