2018-12-31 20:04:05 +01:00
|
|
|
//
|
2022-01-01 01:35:39 +01:00
|
|
|
// Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2022
|
2018-12-31 20:04:05 +01:00
|
|
|
//
|
|
|
|
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
|
|
|
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
|
|
|
//
|
|
|
|
#pragma once
|
|
|
|
|
2022-11-23 17:37:32 +01:00
|
|
|
#include "td/utils/HashTableUtils.h"
|
2022-02-07 22:04:34 +01:00
|
|
|
#include "td/utils/Slice.h"
|
2018-12-31 20:04:05 +01:00
|
|
|
|
2022-02-09 22:59:52 +01:00
|
|
|
#include <unordered_map>
|
|
|
|
|
2018-12-31 20:04:05 +01:00
|
|
|
namespace td {
|
2018-07-17 22:08:38 +02:00
|
|
|
|
2018-12-31 20:04:05 +01:00
|
|
|
class SeqKeyValue {
|
|
|
|
public:
|
|
|
|
using SeqNo = uint64;
|
|
|
|
SeqKeyValue() = default;
|
|
|
|
SeqKeyValue(SeqKeyValue &&) = default;
|
|
|
|
SeqKeyValue &operator=(SeqKeyValue &&) = default;
|
|
|
|
SeqKeyValue(const SeqKeyValue &) = delete;
|
|
|
|
SeqKeyValue &operator=(const SeqKeyValue &) = delete;
|
|
|
|
~SeqKeyValue() = default;
|
|
|
|
|
|
|
|
SeqNo set(Slice key, Slice value) {
|
2022-02-07 20:41:07 +01:00
|
|
|
auto it_ok = map_.emplace(key.str(), value.str());
|
2018-12-31 20:04:05 +01:00
|
|
|
if (!it_ok.second) {
|
|
|
|
if (it_ok.first->second == value) {
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
it_ok.first->second = value.str();
|
|
|
|
}
|
|
|
|
return next_seq_no();
|
|
|
|
}
|
2022-08-17 15:52:27 +02:00
|
|
|
|
2018-12-31 20:04:05 +01:00
|
|
|
SeqNo erase(const string &key) {
|
|
|
|
auto it = map_.find(key);
|
|
|
|
if (it == map_.end()) {
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
map_.erase(it);
|
|
|
|
return next_seq_no();
|
|
|
|
}
|
2022-08-17 15:52:27 +02:00
|
|
|
|
2018-12-31 20:04:05 +01:00
|
|
|
SeqNo seq_no() const {
|
|
|
|
return current_id_ + 1;
|
|
|
|
}
|
2022-08-17 15:52:27 +02:00
|
|
|
|
2018-12-31 20:04:05 +01:00
|
|
|
string get(const string &key) const {
|
|
|
|
auto it = map_.find(key);
|
|
|
|
if (it == map_.end()) {
|
|
|
|
return string();
|
|
|
|
}
|
|
|
|
return it->second;
|
|
|
|
}
|
|
|
|
|
2022-08-17 15:52:27 +02:00
|
|
|
bool isset(const string &key) const {
|
|
|
|
auto it = map_.find(key);
|
|
|
|
if (it == map_.end()) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2018-12-31 20:04:05 +01:00
|
|
|
size_t size() const {
|
|
|
|
return map_.size();
|
|
|
|
}
|
|
|
|
|
2022-11-23 17:37:32 +01:00
|
|
|
std::unordered_map<string, string, Hash<string>> get_all() const {
|
2018-12-31 20:04:05 +01:00
|
|
|
return map_;
|
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
2022-11-23 17:37:32 +01:00
|
|
|
std::unordered_map<string, string, Hash<string>> map_;
|
2018-12-31 20:04:05 +01:00
|
|
|
SeqNo current_id_ = 0;
|
|
|
|
SeqNo next_seq_no() {
|
|
|
|
return ++current_id_;
|
|
|
|
}
|
|
|
|
};
|
2018-07-17 22:08:38 +02:00
|
|
|
|
2018-12-31 20:04:05 +01:00
|
|
|
} // namespace td
|