forked from MrBesen/lolautoaccept
48 lines
1.3 KiB
C++
48 lines
1.3 KiB
C++
#include "memoryimagecache.h"
|
|
|
|
#include <algorithm>
|
|
#include <Log.h>
|
|
|
|
MemoryImageCache::MemoryImageCache(size_t maxsize) : maxsize(maxsize) {}
|
|
|
|
void MemoryImageCache::addImage(QPixmap img, const QString& title, int type) {
|
|
auto it = std::find_if(cache.begin(), cache.end(), getImageMatcher(title, type));
|
|
if(it == cache.end()) {
|
|
// insert new
|
|
cache.push_back({time(0), img, title, type});
|
|
cleanUp();
|
|
return;
|
|
}
|
|
|
|
// update old
|
|
it->lastaccessed = time(0);
|
|
it->imageref = img;
|
|
}
|
|
|
|
QPixmap MemoryImageCache::getImage(const QString& title, int type) {
|
|
auto it = std::find_if(cache.begin(), cache.end(), getImageMatcher(title, type));
|
|
if(it == cache.end()) {
|
|
return {};
|
|
}
|
|
it->lastaccessed = time(0);
|
|
return it->imageref;
|
|
}
|
|
|
|
void MemoryImageCache::cleanUp() {
|
|
if(cache.size() < maxsize) return;
|
|
|
|
auto oldest = std::min_element(cache.begin(), cache.end());
|
|
|
|
cache.erase(oldest);
|
|
}
|
|
|
|
bool MemoryImageCache::CachedImage::operator<(const MemoryImageCache::CachedImage& other) const {
|
|
return lastaccessed < other.lastaccessed;
|
|
}
|
|
|
|
std::function<bool(const MemoryImageCache::CachedImage&)> MemoryImageCache::getImageMatcher(const QString& title, int type) {
|
|
return [title, type](const MemoryImageCache::CachedImage& img) -> bool {
|
|
return img.type == type && img.title == title;
|
|
};
|
|
}
|