2018-03-06 14:25:36 +01:00
|
|
|
//
|
2024-01-01 01:07:21 +01:00
|
|
|
// Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2024
|
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"
|
2022-08-03 21:51:07 +02:00
|
|
|
#include "td/utils/WaitFreeVector.h"
|
2018-03-06 14:25:36 +01:00
|
|
|
|
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
|
|
|
|
|
|
|
Key add(ValueT v) {
|
2019-11-26 18:53:50 +01:00
|
|
|
CHECK(arr_.size() < static_cast<size_t>(std::numeric_limits<int32>::max() - 1));
|
2021-10-19 17:11:16 +02:00
|
|
|
auto next_id = static_cast<int32>(arr_.size() + 1);
|
2018-03-07 08:47:33 +01:00
|
|
|
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
|
|
|
}
|
|
|
|
|
2022-04-25 19:52:44 +02:00
|
|
|
size_t size() const {
|
|
|
|
CHECK(map_.size() == arr_.size());
|
|
|
|
return arr_.size();
|
|
|
|
}
|
|
|
|
|
2022-07-20 12:40:14 +02:00
|
|
|
bool empty() const {
|
|
|
|
return size() == 0;
|
|
|
|
}
|
|
|
|
|
2018-03-06 14:25:36 +01:00
|
|
|
private:
|
2018-03-07 08:47:33 +01:00
|
|
|
std::map<ValueT, int32> map_;
|
2022-08-03 21:51:07 +02:00
|
|
|
WaitFreeVector<const ValueT *> arr_;
|
2018-03-06 14:25:36 +01:00
|
|
|
};
|
|
|
|
|
|
|
|
} // namespace td
|