Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Database {
- public:
- auto Put(const Record& record) -> bool;
- auto GetById(const string& id) const -> const Record*;
- auto Erase(const string& id) -> bool;
- template <typename Callback> void RangeByTimestamp(int low, int high, Callback callback) const;
- template <typename Callback> void RangeByKarma(int low, int high, Callback callback) const;
- template <typename Callback> void AllByUser(const string& user, Callback callback) const;
- private:
- unordered_map<string, Record> mDatabase;
- unordered_map<int, unordered_set<string>> mKarmaIndex;
- unordered_map<int, unordered_set<string>> mTimestampIndex;
- unordered_map<string, unordered_set<string>> mUserIndex;
- };
- auto Database::Put(const Record& record) -> bool {
- const auto[recordIterator, bResult] = mDatabase.insert({record.id, record});
- if (bResult) {
- mKarmaIndex[record.karma].insert(record.id);
- mTimestampIndex[record.timestamp].insert(record.id);
- mUserIndex[record.user].insert(record.id);
- }
- return bResult;
- }
- auto Database::GetById(const string& id) const -> const Record* {
- if (mDatabase.count(id)) {
- return &mDatabase.at(id);
- } else {
- return nullptr;
- }
- }
- auto Database::Erase(const string& id) -> bool {
- const auto foundRecord = mDatabase.find(id);
- if (foundRecord != mDatabase.end()) {
- mKarmaIndex[foundRecord->second.karma].erase(id);
- mTimestampIndex[foundRecord->second.timestamp].erase(id);
- mUserIndex[foundRecord->second.user].erase(id);
- mDatabase.erase(id);
- return true;
- } else {
- return false;
- }
- }
- template<typename Callback> void Database::RangeByTimestamp(int low, int high, Callback callback) const {
- for (int i = low; i <= high; ++i) {
- try {
- for (const auto& item : mTimestampIndex.at(i)) {
- if (!callback(mDatabase.at(item))) {
- return;
- }
- }
- } catch (exception&) {}
- }
- }
- template<typename Callback> void Database::RangeByKarma(int low, int high, Callback callback) const {
- for (int i = low; i <= high; ++i) {
- try {
- for (const auto& item : mKarmaIndex.at(i)) {
- if (!callback(mDatabase.at(item))) {
- return;
- }
- }
- } catch (exception&) {}
- }
- }
- template<typename Callback> void Database::AllByUser(const string& user, Callback callback) const {
- if (!mUserIndex.count(user)) {
- return;
- }
- for (const auto& item : mUserIndex.at(user)) {
- if (!callback(mDatabase.at(item))) {
- return;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement