2018-03-06 14:25:36 +01:00
|
|
|
//
|
2020-01-01 02:23:48 +01:00
|
|
|
// Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2020
|
2018-03-06 14:25:36 +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
|
2018-03-06 17:27:52 +01:00
|
|
|
|
2018-03-06 14:25:36 +01:00
|
|
|
#include "td/utils/common.h"
|
|
|
|
|
2019-11-26 18:53:50 +01:00
|
|
|
#include <limits>
|
2018-03-07 08:47:33 +01:00
|
|
|
#include <map>
|
2018-03-07 13:46:58 +01:00
|
|
|
#include <tuple>
|
2018-03-06 14:25:36 +01:00
|
|
|
|
|
|
|
namespace td {
|
|
|
|
|
|
|
|
template <class ValueT>
|
|
|
|
class Enumerator {
|
|
|
|
public:
|
|
|
|
using Key = int32;
|
2018-03-07 00:10:54 +01:00
|
|
|
|
2020-05-23 21:27:24 +02:00
|
|
|
std::map<ValueT, int32> get_map() const {
|
|
|
|
return map_;
|
|
|
|
}
|
|
|
|
|
|
|
|
std::pair<Key, bool> next() {
|
|
|
|
if (!empty_id_.empty()) {
|
|
|
|
auto res = empty_id_.back();
|
|
|
|
empty_id_.pop_back();
|
|
|
|
return std::make_pair(res, true);
|
|
|
|
}
|
|
|
|
|
|
|
|
return std::make_pair((Key) (arr_.size() + 1), false);
|
|
|
|
}
|
|
|
|
|
|
|
|
void erase(Key key_y) {
|
|
|
|
empty_id_.push_back(key_y);
|
|
|
|
}
|
|
|
|
|
2018-03-07 00:10:54 +01:00
|
|
|
Key add(ValueT v) {
|
2020-05-23 21:27:24 +02:00
|
|
|
auto next_id = next();
|
2018-03-07 08:47:33 +01:00
|
|
|
bool was_inserted;
|
|
|
|
decltype(map_.begin()) it;
|
2020-05-23 21:27:24 +02:00
|
|
|
std::tie(it, was_inserted) = map_.emplace(std::move(v), next_id.first);
|
|
|
|
if (was_inserted && next_id.second) {
|
|
|
|
arr_[next_id.first - 1] = &it->first;
|
|
|
|
} else if (was_inserted) {
|
2018-03-07 08:47:33 +01:00
|
|
|
arr_.push_back(&it->first);
|
2020-05-23 21:27:24 +02:00
|
|
|
} else if (next_id.second) {
|
|
|
|
empty_id_.push_back(next_id.first);
|
2018-03-07 08:47:33 +01:00
|
|
|
}
|
|
|
|
return it->second;
|
2018-03-06 14:25:36 +01:00
|
|
|
}
|
2018-03-07 00:10:54 +01:00
|
|
|
|
2018-03-06 14:25:36 +01:00
|
|
|
const ValueT &get(Key key) const {
|
2020-05-23 21:27:24 +02:00
|
|
|
auto pos = static_cast<Key>(key - 1);
|
2018-03-07 13:46:58 +01:00
|
|
|
return *arr_[pos];
|
2018-03-06 14:25:36 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
2020-05-23 21:27:24 +02:00
|
|
|
std::vector<Key> empty_id_;
|
2018-03-07 08:47:33 +01:00
|
|
|
std::map<ValueT, int32> map_;
|
|
|
|
std::vector<const ValueT *> arr_;
|
2018-03-06 14:25:36 +01:00
|
|
|
};
|
|
|
|
|
|
|
|
} // namespace td
|