67 lines
1.4 KiB
C++
67 lines
1.4 KiB
C++
#pragma once
|
|
|
|
#include <unordered_map>
|
|
#include <mutex>
|
|
#include <fstream>
|
|
#include <optional>
|
|
#include <string>
|
|
|
|
using std::string;
|
|
|
|
class KeyValueStore {
|
|
public:
|
|
void set(const string& key, const string& value) {
|
|
std::lock_guard<std::mutex> lock(mutex_);
|
|
data_[key] = value;
|
|
}
|
|
|
|
std::optional<string> get(const string& key) {
|
|
std::lock_guard<std::mutex> lock(mutex_);
|
|
auto it = data_.find(key);
|
|
return it != data_.end() ? std::optional<string>{it->second} : std::nullopt;
|
|
}
|
|
|
|
bool del(const string& key) {
|
|
std::lock_guard<std::mutex> lock(mutex_);
|
|
return data_.erase(key) > 0;
|
|
}
|
|
|
|
size_t size() {
|
|
std::lock_guard<std::mutex> 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<std::mutex> 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<std::mutex> 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<string, string> data_;
|
|
mutable std::mutex mutex_;
|
|
string filename_ = "server_store.txt";
|
|
};
|