-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfifo.h
More file actions
109 lines (86 loc) · 1.81 KB
/
Copy pathfifo.h
File metadata and controls
109 lines (86 loc) · 1.81 KB
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
#ifndef _FIFO_H_
#define _FIFO_H_
#include <cstddef>
#include <cstdint>
#include <cstring>
template <typename T>
class Fifo {
public:
explicit Fifo(const size_t capacity) : capacity_(RoundUpToPowerOfTwo(capacity)), mask_(capacity_ - 1), buffer_(new T[capacity_]) {
}
~Fifo() {
delete[] buffer_;
}
bool empty() const {
return count() == 0;
}
bool full() const {
return count() == mask_;
}
bool Push(const T& data, bool force = false) {
if (full()) {
if (force) {
read_ptr_ = (read_ptr_ + 1) & mask_;
} else {
return false;
}
}
buffer_[write_ptr_] = data;
write_ptr_ = (write_ptr_ + 1) & mask_;
return true;
}
bool Push(const T* data, bool force = false) {
return Push(*data, force);
}
void Advance(size_t count = 1) {
read_ptr_ = (read_ptr_ + count) & mask_;
}
T Pop() {
T value = buffer_[read_ptr_];
read_ptr_ = (read_ptr_ + 1) & mask_;
return value;
}
bool Pop(T& data) {
if (empty()) {
return false;
}
data = Pop();
return true;
}
bool Pop(T* data) {
return Pop(*data);
}
void Clear() {
write_ptr_ = read_ptr_;
}
size_t count() const {
return (write_ptr_ - read_ptr_) & mask_;
}
size_t capacity() const {
return mask_;
}
size_t free_space() const {
return mask_ - count();
}
private:
Fifo(const Fifo&) = delete;
Fifo& operator=(const Fifo&) = delete;
static size_t RoundUpToPowerOfTwo(size_t value) {
if (value < 2) {
return 2;
}
value--;
for (size_t shift = 1; shift < sizeof(size_t) * 8; shift <<= 1) {
value |= value >> shift;
}
value++;
return value;
}
const size_t capacity_;
const size_t mask_;
T* buffer_;
// T buffer_[N];
size_t read_ptr_ = 0;
size_t write_ptr_ = 0;
};
#endif