-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathasync-input.hpp
56 lines (49 loc) · 1.43 KB
/
async-input.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
#include <thread>
#include <mutex>
#include <atomic>
#include <deque>
#include <istream>
#include "byte.hpp"
class AsyncInput {
private:
std::atomic<bool> enabled {true};
std::mutex mutex;
u8_fast historySize;
std::deque<std::string> lines{historySize};
std::istream& input;
std::thread thread{[&] () {
for (std::string line; enabled && std::getline(input, line); ) {
mutex.lock();
lines.push_back(line);
mutex.unlock();
}
}};
public:
AsyncInput(std::istream& input, u8_fast historySize)
: input{input}, historySize{historySize} {
}
~AsyncInput() {
enabled = false;
thread.join();
}
bool get(std::string& line) {
mutex.lock();
bool valid {lines.size() > historySize};
if (valid) {
line = lines[historySize];
lines.pop_front();
}
mutex.unlock();
return valid;
}
void getHistory(std::string& line, const u8_fast depth) {
mutex.lock();
line = lines[historySize - depth];
mutex.unlock();
}
void setHistory(const std::string& line, const u8_fast depth) {
mutex.lock();
lines[historySize - depth] = line;
mutex.unlock();
}
};