90 lines
1.9 KiB
C++
90 lines
1.9 KiB
C++
/*
|
|
* 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 <vector>
|
|
#include <map>
|
|
#include <utility>
|
|
#include <type_traits>
|
|
|
|
namespace OpenVulkano
|
|
{
|
|
template<typename K, typename V, typename Pair = std::pair<K, V>, typename Vec = std::vector<Pair>,
|
|
typename = std::enable_if_t<std::is_integral<K>::value>>
|
|
class BinSearchArrayMap
|
|
{
|
|
public:
|
|
void Insert(K key, const V& value)
|
|
{
|
|
// 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<typename... Args> 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, std::forward<Args>(args)...);
|
|
return;
|
|
}
|
|
|
|
throw std::runtime_error("Key cannot be lesser than the last used key.");
|
|
}
|
|
|
|
void Remove(const K key)
|
|
{
|
|
auto& it = FindPair(key);
|
|
m_data.erase(it);
|
|
}
|
|
|
|
size_t Size() const { return m_data.size(); }
|
|
|
|
V& operator[](const K key) noexcept { return Get(key); }
|
|
|
|
V& Get(const K key) { return FindPair(key).second; }
|
|
|
|
Pair& FindPair(const K key)
|
|
{
|
|
int low = 0;
|
|
int high = m_data.size() - 1;
|
|
|
|
while (low <= high)
|
|
{
|
|
int mid = low + (high - low) / 2;
|
|
|
|
if (m_data[mid].first == key)
|
|
{
|
|
return m_data[mid]; // The difference
|
|
}
|
|
else if (m_data[mid].first < key)
|
|
{
|
|
low = mid + 1;
|
|
}
|
|
else
|
|
{
|
|
high = mid - 1;
|
|
}
|
|
}
|
|
|
|
throw std::runtime_error("Key not found.");
|
|
}
|
|
|
|
bool Contains(const K key) const { return true; }
|
|
bool Contains(const V& value) const { return true; }
|
|
|
|
private:
|
|
Vec m_data;
|
|
};
|
|
}
|