forked from makerust/TheKNOB
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmailbox.hpp
50 lines (43 loc) · 968 Bytes
/
mailbox.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
template<typename _Tp, int LENGTH>
struct mailbox {
typedef _Tp value_type;
typedef const value_type& const_reference;
typedef size_t size_type;
value_type buf[LENGTH ? LENGTH : 1];
size_type head; // Write To Head
size_type tail; // Read from Tail
bool full;
void
fill(const value_type& v) {
for (auto i = 0; i < LENGTH; i++) buf[i] = v;
head = 0;
tail = 0;
full = false;
}
size_type
count() const{
if (full) return LENGTH;
return (head >= tail) ? head - tail
: LENGTH + head - tail;
}
void
push_back(const_reference value) {
buf[head] = value;
if (full){
if (++tail == LENGTH) tail = 0;
}
if (++head == LENGTH) head = 0;
full = head == tail;
}
value_type
pop_front(){
auto res = buf[tail];
full = false;
if (++tail >= LENGTH) tail = 0;
return res;
}
bool
is_full() const{
return full;
}
};