// // Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2020 // // 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 #include "td/utils/common.h" #include #include #include namespace td { template class Enumerator { public: using Key = int32; std::map get_map() const { return map_; } Key next() { if (!empty_id_.empty()) { auto res = empty_id_.back(); empty_id_.pop_back(); return res; } return arr_.size() + 1; } void erase_map_key(ValueT key_x, Key key_y) { empty_id_.push_back(key_y); map_.erase(key_x); arr_[key_y] = nullptr; } Key add(ValueT v) { CHECK(arr_.size() < static_cast(std::numeric_limits::max() - 1)); Key next_id = next(); bool was_inserted; decltype(map_.begin()) it; std::tie(it, was_inserted) = map_.emplace(std::move(v), next_id); if (was_inserted) { arr_.push_back(&it->first); } return it->second; } const ValueT &get(Key key) const { auto pos = static_cast(key - 1); CHECK(pos < arr_.size()); return *arr_[pos]; } private: std::vector empty_id_; std::map map_; std::vector arr_; }; } // namespace td