mirror-chatterino2/messages/limitedqueue.h

103 lines
2.6 KiB
C
Raw Normal View History

2017-02-02 20:35:12 +01:00
#ifndef LIMITEDQUEUE_H
#define LIMITEDQUEUE_H
#include "messages/limitedqueuesnapshot.h"
#include <memory>
#include <mutex>
#include <vector>
2017-04-14 17:52:22 +02:00
namespace chatterino {
namespace messages {
2017-02-02 20:35:12 +01:00
template <typename T>
class LimitedQueue
{
public:
LimitedQueue(int limit = 100, int buffer = 25)
: mutex()
2017-02-02 20:35:12 +01:00
, offset(0)
, limit(limit)
, buffer(buffer)
{
vector = std::make_shared<std::vector<T>>();
vector->reserve(this->limit + this->buffer);
}
2017-04-12 17:46:44 +02:00
void clear()
{
std::lock_guard<std::mutex> lock(this->mutex);
this->vector = std::make_shared<std::vector<T>>();
this->vector->reserve(this->limit + this->buffer);
this->offset = 0;
2017-02-02 20:35:12 +01:00
}
// return true if an item was deleted
// deleted will be set if the item was deleted
2017-04-12 17:46:44 +02:00
bool appendItem(const T &item, T &deleted)
2017-02-02 20:35:12 +01:00
{
std::lock_guard<std::mutex> lock(this->mutex);
if (this->vector->size() >= this->limit) {
2017-02-02 20:35:12 +01:00
// vector is full
if (this->offset == this->buffer) {
deleted = this->vector->at(this->offset);
// create new vector
auto newVector = std::make_shared<std::vector<T>>();
newVector->reserve(this->limit + this->buffer);
2017-02-02 20:35:12 +01:00
for (unsigned int i = 0; i < this->limit - 1; i++) {
newVector->push_back(this->vector->at(i + this->offset));
2017-02-02 20:35:12 +01:00
}
newVector->push_back(item);
2017-02-02 20:35:12 +01:00
this->offset = 0;
this->vector = newVector;
2017-02-02 20:35:12 +01:00
return true;
} else {
deleted = this->vector->at(this->offset);
2017-04-12 17:46:44 +02:00
// append item and increment offset("deleting" first element)
this->vector->push_back(item);
2017-02-02 20:35:12 +01:00
this->offset++;
return true;
}
} else {
// append item
this->vector->push_back(item);
2017-02-02 20:35:12 +01:00
return false;
}
}
2017-04-12 17:46:44 +02:00
messages::LimitedQueueSnapshot<T> getSnapshot()
2017-02-02 20:35:12 +01:00
{
std::lock_guard<std::mutex> lock(this->mutex);
2017-02-02 20:35:12 +01:00
2017-04-12 17:46:44 +02:00
if (vector->size() < limit) {
return LimitedQueueSnapshot<T>(this->vector, this->offset, this->vector->size());
} else {
return LimitedQueueSnapshot<T>(this->vector, this->offset, this->limit);
}
2017-02-02 20:35:12 +01:00
}
private:
std::shared_ptr<std::vector<T>> vector;
2017-02-02 20:35:12 +01:00
std::mutex mutex;
unsigned int offset;
unsigned int limit;
unsigned int buffer;
2017-02-02 20:35:12 +01:00
};
2017-04-14 17:52:22 +02:00
} // namespace messages
} // namespace chatterino
2017-02-02 20:35:12 +01:00
#endif // LIMITEDQUEUE_H