-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcircular_list.h
84 lines (65 loc) · 2.05 KB
/
circular_list.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
#ifndef CIRCULAR_LIST_H
#define CIRCULAR_LIST_H
template <class T, uint32_t LEN>
class CircularList {
private:
uint32_t head_, tail_; // indices
T list_[LEN]; // buffer
public:
CircularList() noexcept : head_{0}, tail_{0} {
static_assert((LEN > 0 && ((LEN & (LEN - 1)) == 0)) != 0,
"LIST IS NOT POWER OF TWO");
}
~CircularList(void) noexcept {}
void clear() noexcept { head_ = tail_ = 0; }
// Enqueue one element
inline void Push(const T &element) noexcept {
// test for buffer full
if (IsFull()) head_ = (head_ + 1) & (LEN - 1);
list_[tail_] = element;
tail_ = (tail_ + 1) & (LEN - 1);
}
inline void PushAll(const T element[], uint32_t len) noexcept {
for (uint32_t i = 0; i < len; i++) Push(element[i]);
}
// read top element or last enqueued element
bool At(uint32_t idx, T *element) const noexcept {
// check for empty list
if (Length() <= idx) return false;
uint32_t _idx = (head_ + idx) & (LEN - 1);
*element = list_[_idx];
return true;
}
bool AtLast(uint32_t idx, T *element) const noexcept {
// check for empty list
if (Length() <= idx) return false;
const auto _idx = (tail_ - 1 - idx + LEN) & (LEN - 1);
*element = list_[_idx];
return true;
}
// dequeue one element
inline bool pop(T *element) noexcept {
// check for empty list
if (IsEmpty()) return false;
*element = list_[head_];
head_ = (head_ + 1) & (LEN - 1);
return true;
}
bool Top(const T *element) const noexcept {
// check for empty list
if (IsEmpty()) return false;
*element = list_[head_];
return true;
}
uint32_t Length() const noexcept {
if (IsEmpty()) return 0;
return LEN - ((head_ - tail_) & (LEN - 1));
}
inline uint32_t Capacity() const noexcept { return (LEN - 1); }
inline uint32_t RemainingCapacity() const noexcept {
return (Capacity() - Length());
}
bool IsEmpty() const noexcept { return (head_ == tail_); }
inline bool IsFull() const noexcept { return (RemainingCapacity() <= 0); }
};
#endif // !1