69 lines
1.8 KiB
MQL5
69 lines
1.8 KiB
MQL5
#ifndef CIRCULAR_BUFFER_MQH
|
|
#define CIRCULAR_BUFFER_MQH
|
|
|
|
template <typename Type> class Circular_buffer {
|
|
protected:
|
|
Type array[];
|
|
const int capacity;
|
|
int write_position;
|
|
int size;
|
|
|
|
public:
|
|
Circular_buffer(const int &_capacity)
|
|
: capacity(_capacity), write_position(0), size(0) {
|
|
const int new_size = capacity;
|
|
if (ArrayResize(array, new_size) == -1) {
|
|
Print("Cannot resize the array!");
|
|
}
|
|
}
|
|
|
|
Circular_buffer(const Circular_buffer &circular_buffer)
|
|
: capacity(circular_buffer.capacity),
|
|
write_position(circular_buffer.write_position),
|
|
size(circular_buffer.size) {
|
|
const int new_size = capacity;
|
|
if (ArrayResize(array, new_size) == -1) {
|
|
Print("Cannot resize the array!");
|
|
}
|
|
for (int position = 0; position < capacity; ++position) {
|
|
array[position] = circular_buffer.array[position];
|
|
}
|
|
}
|
|
|
|
virtual ~Circular_buffer() { ArrayFree(array); }
|
|
|
|
public:
|
|
Circular_buffer operator=(const Circular_buffer &circular_buffer) {
|
|
for (int position = 0; position < capacity; ++position) {
|
|
array[position] = circular_buffer.array[position];
|
|
}
|
|
write_position = circular_buffer.write_position;
|
|
size = circular_buffer.size;
|
|
return *this;
|
|
}
|
|
|
|
public:
|
|
int get_size() const { return size; }
|
|
|
|
void write(const Type &value) {
|
|
array[write_position] = value;
|
|
write_position = (write_position + 1) % capacity;
|
|
if (size >= capacity) {
|
|
return;
|
|
}
|
|
++size;
|
|
return;
|
|
}
|
|
|
|
bool read(int position_offset, Type &value) const {
|
|
if (position_offset < 0 || position_offset >= size) {
|
|
return false;
|
|
}
|
|
const int read_position =
|
|
(write_position - 1 - position_offset + capacity) % capacity;
|
|
value = array[read_position];
|
|
return true;
|
|
}
|
|
};
|
|
|
|
#endif
|