-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCircularArray.hpp
79 lines (76 loc) · 1.79 KB
/
CircularArray.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#ifndef CircularArray_hpp
#define CircularArray_hpp
#include <bitset>
#include <stdexcept>
template<typename T,std::size_t N>
class CircularArray final {
T data[N];
std::bitset<N> inUse;
std::size_t next{};
void doNext() {
++next;
next %= N;
}
public:
CircularArray() = default;
CircularArray(const T* ptr, std::size_t n) {
for (auto *p = ptr; p != ptr + n; ++p) {
data[next] = *p;
inUse[next] = true;
doNext();
}
}
CircularArray(const CircularArray&) = default;
CircularArray(CircularArray&&) = default;
CircularArray& operator=(const CircularArray&) = default;
CircularArray& operator=(CircularArray&&) = default;
CircularArray& operator=(const T& rhs) {
data[next] = rhs;
inUse[next] = true;
return *this;
}
CircularArray& operator=(T&& rhs) {
data[next] = std::move(rhs);
inUse[next] = true;
return *this;
}
CircularArray& operator=(nullptr_t) {
data[next] = T{};
inUse[next] = false;
return *this;
}
bool hasData() const {
return inUse[next];
}
const T& operator*() const {
if (!hasData()) {
throw std::runtime_error("No data");
}
return data[next];
}
const T* operator->() const {
return &(operator*());
}
std::size_t operator++() {
doNext();
return next;
}
std::size_t operator++(int) {
auto prev = next;
doNext();
return prev;
}
std::size_t operator--() {
--next;
if (next >= N) {
next = N - 1;
}
return next;
}
std::size_t operator--(int) {
auto prev = next;
operator--();
return prev;
}
};
#endif