Arduino PulseWire Transceiver Library
Loading...
Searching...
No Matches
RingBuffer.h
1#pragma once
2#include <stddef.h>
3#include <stdint.h>
4#include <string.h>
5
6namespace pulsewire {
7
23template <typename T>
25 public:
26 RingBuffer(size_t size = 128) { resize(size); }
27
28 ~RingBuffer() {
29 delete[] _buffer;
30 _buffer = nullptr;
31 }
32
33 void resize(size_t new_size) {
34 delete[] _buffer;
35 _buffer = new T[new_size];
36 _capacity = new_size;
37 clear();
38 }
39
40 bool write(const T& value) {
41 if (isFull()) return false;
42 _buffer[_tail] = value;
43 _tail = (_tail + 1) % _capacity;
44 _count++;
45 return true;
46 }
47
48 int writeArray(const T* data, size_t len) {
49 int written = 0;
50 for (size_t i = 0; i < len; ++i) {
51 if (write(data[i])) {
52 ++written;
53 } else {
54 break;
55 }
56 }
57 return written;
58 }
59
60 size_t available() const { return _count; }
61
62 void clear() {
63 _head = 0;
64 _tail = 0;
65 _count = 0;
66 }
67
68 bool isFull() const { return _count == _capacity; }
69
70 bool isEmpty() const { return _count == 0; }
71
72 size_t size() const { return _capacity; }
73
75 bool read(T& out) {
76 if (_count == 0) return false;
77 out = _buffer[_head];
78 _head = (_head + 1) % _capacity;
79 _count--;
80 return true;
81 }
82
85 int read() {
86 if (_count == 0) return -1;
87 T value = _buffer[_head];
88 _head = (_head + 1) % _capacity;
89 _count--;
90 return static_cast<int>(value);
91 }
92
94 int readArray(T* dest, size_t len) {
95 int n = 0;
96 while (n < static_cast<int>(len) && _count > 0) {
97 dest[n] = _buffer[_head];
98 _head = (_head + 1) % _capacity;
99 _count--;
100 ++n;
101 }
102 return n;
103 }
104
106 bool peek(T& out) const {
107 if (_count == 0) return false;
108 out = _buffer[_head];
109 return true;
110 }
111
113 int peek() const {
114 if (_count == 0) return -1;
115 return static_cast<int>(_buffer[_head]);
116 }
117
119 size_t availableForWrite() const { return _capacity - _count; }
120
121 protected:
122 T* _buffer = nullptr;
123 size_t _capacity = 0;
124 size_t _head = 0;
125 size_t _tail = 0;
126 size_t _count = 0;
127};
128
129} // namespace pulsewire
Efficient lock-free ring buffer for storing data.
Definition RingBuffer.h:24
size_t availableForWrite() const
Returns available space for writing.
Definition RingBuffer.h:119
bool read(T &out)
Read and remove the next element. Returns true if successful.
Definition RingBuffer.h:75
int peek() const
Peek (uint8_t specialization compatibility). Returns -1 if empty.
Definition RingBuffer.h:113
int readArray(T *dest, size_t len)
Read up to len elements into dest, returns number of elements read.
Definition RingBuffer.h:94
bool peek(T &out) const
Peek at the next element without removing it. Returns true if successful.
Definition RingBuffer.h:106
Small, header-only vector replacement for non-STL environments.
Definition Vector.h:29