Implement basic library class that other libraries inherit from for performance.
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
2020-02-15 18:51:21 +01:00
parent a47f60cdf7
commit d6ea16b467
11 changed files with 87 additions and 195 deletions

View File

@@ -0,0 +1,50 @@
#ifndef CREATURELIB_BASELIBRARY_HPP
#define CREATURELIB_BASELIBRARY_HPP
#include <algorithm>
#include <string>
#include <unordered_map>
namespace CreatureLib::Library {
template <class T> class BaseLibrary {
inline static constexpr char charToLower(const char c) { return (c >= 'A' && c <= 'Z') ? c + ('a' - 'A') : c; }
inline static uint32_t constexpr Hash(char const* input) {
return charToLower(*input) ? static_cast<uint32_t>(charToLower(*input)) + 33 * Hash(input + 1) : 5381;
}
std::unordered_map<uint32_t, const T*> _values;
public:
BaseLibrary(size_t initialCapacity = 32) : _values(initialCapacity) {}
virtual ~BaseLibrary() {
for (const auto& v : _values) {
delete v.second;
}
_values.clear();
}
inline void Insert(const char* key, const T* value) { _values.insert({Hash(key), value}); }
inline void Delete(const char* key) { _values.erase(Hash(key)); }
bool TryGet(const char* name, const T*& out) const {
auto find = this->_values.find(Hash(name));
if (find == this->_values.end()) {
out = nullptr;
return false;
}
out = find->second;
return true;
}
inline const T* Get(const char* name) const { return _values.at(Hash(name)); }
inline const T* operator[](const char* name) const { return Get(name); }
inline const std::unordered_map<uint32_t, const T*>& GetIterator() const { return _values; }
size_t GetCount() const { return _values.count(); }
};
}
#endif // CREATURELIB_BASELIBRARY_HPP