// Squawk messenger. // Copyright (C) 2019 Yury Gubich // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see . #ifndef CORE_CACHE_HPP #define CORE_CACHE_HPP #include "cache.h" template Core::Cache::Cache(const QString& name): storage(name), cache(new std::map ()), abscent(new std::set ()) {} template Core::Cache::~Cache() { close(); delete cache; delete abscent; } template void Core::Cache::open() { storage.open();} template void Core::Cache::close() { storage.close();} template void Core::Cache::addRecord(const K& key, const V& value) { storage.addRecord(key, value); cache->insert(std::make_pair(key, value)); abscent->erase(key); } template V Core::Cache::getRecord(const K& key) const { typename std::map::const_iterator itr = cache->find(key); if (itr == cache->end()) { if (abscent->count(key) > 0) { throw Archive::NotFound(std::to_string(key), storage.getName().toStdString()); } try { V value = storage.getRecord(key); itr = cache->insert(std::make_pair(key, value)).first; } catch (const Archive::NotFound& error) { abscent->insert(key); throw error; } } return itr->second; } template bool Core::Cache::checkRecord(const K& key) const { typename std::map::const_iterator itr = cache->find(key); if (itr != cache->end()) return true; if (abscent->count(key) > 0) return false; try { V value = storage.getRecord(key); itr = cache->insert(std::make_pair(key, value)).first; } catch (const Archive::NotFound& error) { return false; } return true; } template void Core::Cache::changeRecord(const K& key, const V& value) { storage.changeRecord(key, value); //there is a non straightforward behaviour: if there was no element at the sorage it will be added cache->at(key) = value; abscent->erase(key); //so... this line here is to make it coherent with the storage } template void Core::Cache::removeRecord(const K& key) { storage.removeRecord(key); cache->erase(key); abscent->insert(key); } #endif //CORE_CACHE_HPP