CreatureLib/src/Library/BaseLibrary.hpp

88 lines
3.3 KiB
C++

#ifndef CREATURELIB_BASELIBRARY_HPP
#define CREATURELIB_BASELIBRARY_HPP
#include <Arbutils/Assert.hpp>
#include <Arbutils/Collections/Dictionary.hpp>
#include <Arbutils/Collections/List.hpp>
#include <Arbutils/Memory/BorrowedPtr.hpp>
#include <Arbutils/Random.hpp>
#include <Arbutils/StringView.hpp>
#include <algorithm>
#include <memory>
#include <string>
namespace CreatureLib::Library {
template <class T> class BaseLibrary {
ArbUt::Dictionary<uint32_t, std::unique_ptr<const T>> _values;
ArbUt::List<uint32_t> _listValues;
size_t _index;
public:
BaseLibrary(size_t initialCapacity = 32) : _values(initialCapacity), _listValues(initialCapacity) {}
virtual ~BaseLibrary() noexcept { _values.Clear(); }
inline void Insert(const ArbUt::StringView& key, const T* value) {
AssertNotNull(value)
_values.GetStdMap().insert({key.GetHash(), std::unique_ptr<const T>(value)});
_listValues.Append(key);
}
inline void Insert(uint32_t hashedKey, const T* value) {
AssertNotNull(value)
_values.GetStdMap().insert({hashedKey, std::unique_ptr<const T>(value)});
_listValues.Append(hashedKey);
}
inline void Delete(const ArbUt::StringView& key) noexcept {
_values.erase(key.GetHash());
auto k = _listValues.IndexOf(key);
_listValues.Remove(k);
}
inline void Delete(uint32_t hashedKey) noexcept {
_values.Remove(hashedKey);
auto k = _listValues.IndexOf(hashedKey);
_listValues.Remove(k);
}
bool TryGet(const ArbUt::BasicStringView& name, ArbUt::BorrowedPtr<const T>& out) const noexcept {
return TryGet(name.GetHash(), out);
}
bool TryGet(uint32_t hashedKey, ArbUt::BorrowedPtr<const T>& out) const noexcept {
auto find = _values.GetStdMap().find(hashedKey);
if (find == _values.GetStdMap().end())
return false;
out = std::get<1>(*find);
return true;
}
[[nodiscard]] inline ArbUt::BorrowedPtr<const T> Get(const ArbUt::BasicStringView& name) const {
return _values.Get(name.GetHash());
}
[[nodiscard]] inline ArbUt::BorrowedPtr<const T> Get(uint32_t hashedKey) const {
return _values.Get(hashedKey);
}
[[nodiscard]] inline ArbUt::BorrowedPtr<const T> operator[](const ArbUt::BasicStringView& name) const {
return Get(name);
}
[[nodiscard]] inline ArbUt::BorrowedPtr<const T> operator[](uint32_t hashedKey) const { return Get(hashedKey); }
[[nodiscard]] inline const ArbUt::Dictionary<uint32_t, const std::unique_ptr<const T>>&
GetIterator() const noexcept {
return _values;
}
[[nodiscard]] size_t GetCount() const noexcept { return _values.Count(); }
inline ArbUt::BorrowedPtr<const T> GetRandomValue(ArbUt::Random rand = ArbUt::Random()) const noexcept {
auto i = rand.Get(_listValues.Count());
return _values[_listValues[i]];
}
inline ArbUt::BorrowedPtr<const T> GetRandomValue(ArbUt::Random* rand) const noexcept {
auto i = rand->Get(_listValues.Count());
return _values[_listValues[i]];
}
};
}
#endif // CREATURELIB_BASELIBRARY_HPP