#pragma once #include #include #include #include #include #include #include #include using std::string; class KeyValueStore { public: using Value = std::variant; void set(const string& key, const Value& value) { std::unique_lock lock(mutex_); data_[key] = value; } template std::optional get(const string& key) { std::shared_lock lock(mutex_); auto it = data_.find(key); if (it == data_.end()) return std::nullopt; if (auto* ptr = std::get_if(&it->second)) { return *ptr; } return std::nullopt; } const std::unordered_map& get_all() { std::shared_lock lock(mutex_); return data_; } bool del(const string& key) { std::unique_lock lock(mutex_); return data_.erase(key) > 0; } size_t size() { std::shared_lock lock(mutex_); return data_.size(); } void set_file(const string& filename) { std::unique_lock lock(mutex_); filename_ = filename; } void load() { std::ifstream file(filename_); if (!file.is_open()) return; std::unique_lock lock(mutex_); string line; while (std::getline(file, line)) { size_t eq = line.find('='); if (eq == string::npos || eq < 2) continue; string key = line.substr(2, eq - 2); string val_str = line.substr(eq + 1); char type = line[0]; switch (type) { case 'i': data_[key] = std::stoi(val_str); break; case 'd': data_[key] = std::stod(val_str); break; case 's': data_[key] = val_str; break; case 'b': data_[key] = (val_str == "1"); break; } } } void save() { std::shared_lock lock(mutex_); std::ofstream file(filename_); if (!file.is_open()) return; for (const auto& [key, value] : data_) { file << serialize_entry(key, value) << "\n"; } } private: string serialize_entry(const string& key, const Value& value) { return std::visit([&key](const auto& val) -> string { using T = std::decay_t; if constexpr (std::is_same_v) { return "i:" + key + "=" + std::to_string(val); } else if constexpr (std::is_same_v) { return "d:" + key + "=" + std::to_string(val); } else if constexpr (std::is_same_v) { return "s:" + key + "=" + val; } else if constexpr (std::is_same_v) { return "b:" + key + "=" + (val ? "1" : "0"); } }, value); } std::unordered_map data_; mutable std::shared_mutex mutex_; string filename_ = "store.txt"; };