/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ #pragma once #include #include #include #include namespace OpenVulkano { template, typename Vec = std::vector, typename = std::enable_if_t::value>> class BinSearchArrayMap { public: BinSearchArrayMap() = default; ~BinSearchArrayMap() = default; void Insert(K key, V value) noexcept { // Check if the key is bigger than the last element if (m_data.empty() || key > m_data.back().first) { m_data.emplace_back(key, value); return; } throw std::runtime_error("Key cannot be lesser than the last used key."); } template void Emplace(K key, Args... args) { // Check if the key is bigger than the last element if (m_data.empty() || key > m_data.back().first) { m_data.emplace_back(key, V(args...)); return; } throw std::runtime_error("Key cannot be lesser than the last used key."); } void Remove(K key) noexcept { auto it = std::lower_bound(m_data.begin(), m_data.end(), key, [](const auto& pair, const K& key) { return pair.first < key; }); if (it != m_data.end()) { m_data.erase(it); } else { throw std::runtime_error("Key not found."); } } void Size() const noexcept { m_data.size(); } V& operator[](K key) noexcept { auto it = std::lower_bound(m_data.begin(), m_data.end(), key, [](const auto& pair, const K& key) { return pair.first < key; }); return it->second; } V& Get(K key) noexcept { auto it = std::lower_bound(m_data.begin(), m_data.end(), key, [](const auto& pair, const K& key) { return pair.first < key; }); if (it != m_data.end()) { return it->second; } else { throw std::runtime_error("Key not found."); } } bool Contains(K key) const noexcept { auto it = std::lower_bound(m_data.begin(), m_data.end(), key, [](const auto& pair, const K& key) { return pair.first < key; }); return it != m_data.end(); } bool Contains(V& value) const noexcept { auto it = std::find_if(m_data.begin(), m_data.end(), [&value](const auto& pair) { return pair.second == value; }); return it != m_data.end(); } private: Vec m_data; }; }