2018-03-06 14:25:36 +01:00
|
|
|
//
|
2018-12-31 23:02:34 +01:00
|
|
|
// Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2019
|
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"
|
2018-03-06 17:27:52 +01:00
|
|
|
#include "td/utils/logging.h"
|
2018-03-06 14:25:36 +01:00
|
|
|
#include "td/utils/misc.h"
|
|
|
|
|
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
|
|
|
|
|
|
|
Key add(ValueT v) {
|
2018-03-07 08:47:33 +01:00
|
|
|
int32 next_id = narrow_cast<int32>(arr_.size() + 1);
|
|
|
|
bool was_inserted;
|
|
|
|
decltype(map_.begin()) it;
|
2018-03-07 13:46:58 +01:00
|
|
|
std::tie(it, was_inserted) = map_.emplace(std::move(v), next_id);
|
2018-03-07 08:47:33 +01:00
|
|
|
if (was_inserted) {
|
|
|
|
arr_.push_back(&it->first);
|
|
|
|
}
|
|
|
|
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 {
|
2018-03-07 13:46:58 +01:00
|
|
|
auto pos = static_cast<size_t>(key - 1);
|
|
|
|
CHECK(pos < arr_.size());
|
|
|
|
return *arr_[pos];
|
2018-03-06 14:25:36 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
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
|