FastLED 3.9.15
Loading...
Searching...
No Matches
circular_buffer.h
Go to the documentation of this file.
1#pragma once
2
3#include "fl/math_macros.h"
4#include "fl/namespace.h"
5#include "fl/scoped_array.h"
6#include "fl/stdint.h" // For standard integer types
7
8namespace fl {
9
10// TODO:
11// ERROR bit to indicate over flow.
12
13template <typename T> class CircularBuffer {
14 public:
16 : mCapacity(capacity + 1), mHead(0),
17 mTail(0) { // Extra space for distinguishing full/empty
18 mBuffer.reset(new T[mCapacity]);
19 }
20
21 CircularBuffer(const CircularBuffer &) = delete;
23
24 bool push_back(const T &value) {
25 if (full()) {
26 mTail = increment(mTail); // Overwrite the oldest element
27 }
28 mBuffer[mHead] = value;
30 return true;
31 }
32
33 bool pop_front(T *dst = nullptr) {
34 if (empty()) {
35 return false;
36 }
37 if (dst) {
38 *dst = mBuffer[mTail];
39 }
41 return true;
42 }
43
44 bool push_front(const T &value) {
45 if (full()) {
46 mHead = decrement(mHead); // Overwrite the oldest element
47 }
49 mBuffer[mTail] = value;
50 return true;
51 }
52
53 bool pop_back(T *dst = nullptr) {
54 if (empty()) {
55 return false;
56 }
58 if (dst) {
59 *dst = mBuffer[mHead];
60 }
61 return true;
62 }
63
64 T &front() { return mBuffer[mTail]; }
65
66 const T &front() const { return mBuffer[mTail]; }
67
68 T &back() { return mBuffer[(mHead + mCapacity - 1) % mCapacity]; }
69
70 const T &back() const {
71 return mBuffer[(mHead + mCapacity - 1) % mCapacity];
72 }
73
74 T &operator[](fl::size index) { return mBuffer[(mTail + index) % mCapacity]; }
75
76 const T &operator[](fl::size index) const {
77 return mBuffer[(mTail + index) % mCapacity];
78 }
79
80 fl::size size() const { return (mHead + mCapacity - mTail) % mCapacity; }
81
82 fl::size capacity() const { return mCapacity - 1; }
83
84 bool empty() const { return mHead == mTail; }
85
86 bool full() const { return increment(mHead) == mTail; }
87
88 void clear() { mHead = mTail = 0; }
89
90 private:
91 fl::size increment(fl::size index) const { return (index + 1) % mCapacity; }
92
93 fl::size decrement(fl::size index) const {
94 return (index + mCapacity - 1) % mCapacity;
95 }
96
98 fl::size mCapacity;
99 fl::size mHead;
100 fl::size mTail;
101};
102
103} // namespace fl
fl::size capacity() const
fl::size increment(fl::size index) const
bool pop_front(T *dst=nullptr)
bool pop_back(T *dst=nullptr)
T & operator[](fl::size index)
const T & operator[](fl::size index) const
fl::scoped_array< T > mBuffer
CircularBuffer & operator=(const CircularBuffer &)=delete
const T & back() const
CircularBuffer(fl::size capacity)
bool push_front(const T &value)
bool push_back(const T &value)
CircularBuffer(const CircularBuffer &)=delete
fl::size decrement(fl::size index) const
fl::size size() const
const T & front() const
Implements the FastLED namespace macros.
IMPORTANT!
Definition crgb.h:20