FastLED 3.9.7
Loading...
Searching...
No Matches
circular_buffer.h
1#pragma once
2
3#include <stddef.h> // For size_t
4#include <stdint.h> // For standard integer types
5#include "fl/namespace.h"
6#include "fl/ptr.h" // Assuming this provides `scoped_array` or similar
7#include "fl/math_macros.h"
8
9namespace fl {
10
11template <typename T>
13public:
14 CircularBuffer(size_t capacity)
15 : mCapacity(capacity + 1), mHead(0), mTail(0) { // Extra space for distinguishing full/empty
16 mBuffer.reset(new T[mCapacity]);
17 }
18
19 CircularBuffer(const CircularBuffer&) = delete;
20 CircularBuffer& operator=(const CircularBuffer&) = delete;
21
22 bool push_back(const T& value) {
23 if (full()) {
24 mTail = increment(mTail); // Overwrite the oldest element
25 }
26 mBuffer[mHead] = value;
27 mHead = increment(mHead);
28 return true;
29 }
30
31 bool pop_front(T* dst = nullptr) {
32 if (empty()) {
33 return false;
34 }
35 if (dst) {
36 *dst = mBuffer[mTail];
37 }
38 mTail = increment(mTail);
39 return true;
40 }
41
42 bool push_front(const T& value) {
43 if (full()) {
44 mHead = decrement(mHead); // Overwrite the oldest element
45 }
46 mTail = decrement(mTail);
47 mBuffer[mTail] = value;
48 return true;
49 }
50
51 bool pop_back(T* dst = nullptr) {
52 if (empty()) {
53 return false;
54 }
55 mHead = decrement(mHead);
56 if (dst) {
57 *dst = mBuffer[mHead];
58 }
59 return true;
60 }
61
62 T& front() {
63 return mBuffer[mTail];
64 }
65
66 const T& front() const {
67 return mBuffer[mTail];
68 }
69
70 T& back() {
71 return mBuffer[(mHead + mCapacity - 1) % mCapacity];
72 }
73
74 const T& back() const {
75 return mBuffer[(mHead + mCapacity - 1) % mCapacity];
76 }
77
78 T& operator[](size_t index) {
79 return mBuffer[(mTail + index) % mCapacity];
80 }
81
82 const T& operator[](size_t index) const {
83 return mBuffer[(mTail + index) % mCapacity];
84 }
85
86 size_t size() const {
87 return (mHead + mCapacity - mTail) % mCapacity;
88 }
89
90 size_t capacity() const {
91 return mCapacity - 1;
92 }
93
94 bool empty() const {
95 return mHead == mTail;
96 }
97
98 bool full() const {
99 return increment(mHead) == mTail;
100 }
101
102 void clear() {
103 mHead = mTail = 0;
104 }
105
106private:
107 size_t increment(size_t index) const {
108 return (index + 1) % mCapacity;
109 }
110
111 size_t decrement(size_t index) const {
112 return (index + mCapacity - 1) % mCapacity;
113 }
114
115 fl::scoped_array<T> mBuffer;
116 size_t mCapacity;
117 size_t mHead;
118 size_t mTail;
119};
120
121
122}
Implements the FastLED namespace macros.
Implements a simple red square effect for 2D LED grids.
Definition crgb.h:16