-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBatcher.h
93 lines (89 loc) · 1.75 KB
/
Batcher.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
#pragma once
#include <thread>
#include <vector>
#include <mutex>
#include <algorithm>
template<typename T>
class BatchRegistry
{
protected:
std::vector<T*> entries;
std::mutex lock;
public:
std::unique_lock<std::mutex> Lock() {
return std::unique_lock<std::mutex>(lock);
}
bool Register(T* entry) {
if (entry == nullptr) return false;
entries.push_back(entry);
return true;
}
size_t Unregister(T* entry) {
if (entry == nullptr) return 0;
size_t count = 0;
size_t size = entries.size();
for (int i = 0; i < size; i++) {
if (entries[i] != entry) continue;
entries[i] = entries.back();
entries.pop_back();
count++;
size--;
i--;
}
return count;
}
void RunBatch(void (*function)(T*)) {
for (T* entry : entries) function(entry);
}
bool MoveTo(T* entry, size_t position) {
if (position >= entries.size()) {
return false;
}
auto it = std::find(entries.begin(), entries.end(), entry);
if (it == entries.end()) {
return false;
}
else {
entries.erase(it);
entries.insert(position, entry);
return true;
}
}
bool MoveToFront(T* entry) {
if (entries.size() == 0) {
return false;
}
auto it = std::find(entries.begin(), entries.end(), entry);
if (it == entries.end()) {
return false;
}
else {
entries.erase(it);
entries.insert(entries.begin(), entry);
return true;
}
}
bool MoveToBack(T* entry) {
if (entries.size() == 0) {
return false;
}
auto it = std::find(entries.begin(), entries.end(), entry);
if (it == entries.end()) {
return false;
}
else {
entries.erase(it);
entries.insert(entries.end(), entry);
return true;
}
}
void Clear() {
entries.clear();
}
size_t Count() {
return entries.size();
}
bool Empty() {
return entries.empty();
}
};