54 lines
1.6 KiB
C++
54 lines
1.6 KiB
C++
#ifndef __JABYENGINE_CIRCULAR_BUFFER_HPP__
|
|
#define __JABYENGINE_CIRCULAR_BUFFER_HPP__
|
|
#include "../../stddef.h"
|
|
|
|
namespace JabyEngine {
|
|
class CircularBuffer {
|
|
private:
|
|
typedef uint32_t T;
|
|
|
|
T* start_adr = nullptr;
|
|
size_t end_idx = 0;
|
|
size_t read_idx = 0;
|
|
size_t write_idx = 0;
|
|
|
|
static size_t increment(size_t cur_idx, size_t end_idx) {
|
|
static constexpr size_t Step = 1;
|
|
|
|
cur_idx += Step;
|
|
if(cur_idx >= end_idx) {
|
|
return (end_idx - cur_idx);
|
|
}
|
|
|
|
return cur_idx;
|
|
}
|
|
|
|
public:
|
|
CircularBuffer() = default;
|
|
|
|
void setup(T* buffer_start_adr, size_t element_count) {
|
|
this->start_adr = buffer_start_adr;
|
|
this->end_idx = element_count;
|
|
this->read_idx = 0;
|
|
this->write_idx = 0;
|
|
}
|
|
|
|
T* push() {
|
|
const auto new_idx = CircularBuffer::increment(this->write_idx, this->end_idx);
|
|
if(new_idx != this->read_idx) {
|
|
auto* dst = (this->start_adr + this->write_idx);
|
|
|
|
this->write_idx = new_idx;
|
|
return dst;
|
|
}
|
|
|
|
return nullptr;
|
|
}
|
|
|
|
constexpr bool has_data() const {
|
|
return (this->read_idx != this->write_idx);
|
|
}
|
|
};
|
|
}
|
|
|
|
#endif //!__JABYENGINE_CIRCULAR_BUFFER_HPP__
|