Implement basic library class that other libraries inherit from for performance.
All checks were successful
continuous-integration/drone/push Build is passing
All checks were successful
continuous-integration/drone/push Build is passing
This commit is contained in:
50
src/Library/BaseLibrary.hpp
Normal file
50
src/Library/BaseLibrary.hpp
Normal 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
|
||||
Reference in New Issue
Block a user