VIANC/pw_plugin/circ_buffer.h

32 lines
730 B
C++

#include <cstring>
#include <cmath>
#include <cstdio>
#pragma once
template<size_t N, typename DataType=float>
class circ_buffer {
public:
void enqueue(DataType* ptr, size_t num) {
auto fst_xfer = std::min(num, N - head);
std::memcpy(&raw[head], ptr, fst_xfer*sizeof(DataType));
if(fst_xfer < num) {
std::memcpy(&raw[0], &ptr[fst_xfer], (num - fst_xfer)*sizeof(DataType));
head = num - fst_xfer;
} else {
head += num;
}
}
// 0 means the last sample in the buffer, etc.
DataType operator[](int numsamps) {
int offset = head + numsamps - 1;
if(offset <= 0) {
offset += N;
}
return raw[offset];
}
DataType raw[N] = {0};
int head = 0; // head is where the next sample is going to be stored
};