#pragma once #include #include #include #include #include using std::string; class KeyValueStore { public: void set(const string& key, const string& value) { std::lock_guard lock(mutex_); data_[key] = value; } std::optional get(const string& key) { std::lock_guard lock(mutex_); auto it = data_.find(key); return it != data_.end() ? std::optional{it->second} : std::nullopt; } bool del(const string& key) { std::lock_guard lock(mutex_); return data_.erase(key) > 0; } size_t size() { std::lock_guard lock(mutex_); return data_.size(); } void set_file(const string& filename) { filename_ = filename; } void load() { std::ifstream file(filename_); if (!file.is_open()) return; std::lock_guard lock(mutex_); string line; while (std::getline(file, line)) { size_t eq = line.find('='); if (eq != string::npos) { data_[line.substr(0, eq)] = line.substr(eq + 1); } } } void save() { std::lock_guard lock(mutex_); std::ofstream file(filename_); if (!file.is_open()) return; for (const auto& [key, value] : data_) { file << key << "=" << value << "\n"; } } private: std::unordered_map data_; mutable std::mutex mutex_; string filename_ = "server_store.txt"; };