diff --git a/include/fggl/ds/placeholder.hpp b/include/fggl/ds/placeholder.hpp index e1cdfdcc0f239a8fb0538be77dbed04722e28982..ab9d9f77baaf34cec86326871e52daf0919a6fac 100644 --- a/include/fggl/ds/placeholder.hpp +++ b/include/fggl/ds/placeholder.hpp @@ -21,8 +21,55 @@ #ifndef FGGL_DS_PLACEHOLDER_HPP #define FGGL_DS_PLACEHOLDER_HPP +#include <map> +#include <cassert> + namespace fggl::ds { + template<typename T, std::size_t N> + class FakeSlotMap { + public: + using WeakRef = std::size_t; + constexpr static WeakRef BAD_INDEX = 0; + + bool valid(WeakRef idx) const { + return m_data.find(idx) != m_data.end(); + } + + WeakRef allocate() { + if ( N <= m_data.size() ) { + assert(0 && "Fake slot map emulated out of space"); + return BAD_INDEX; + } + + auto myIdx = m_nextIdx++; + m_data[myIdx] = T(); + } + + void free(WeakRef idx) { + m_data.erase(idx); + } + + T& get(WeakRef idx) const { + assert( valid(idx) ); + return m_data[idx]; + } + + T* tryGet(WeakRef idx) const { + if( valid(idx) ) { + return &m_data[idx]; + } + return nullptr; + } + + private: + std::map<WeakRef, T> m_data; + std::size_t m_nextIdx = 1; + }; + + template<typename T, std::size_t N> + using SlotMap = FakeSlotMap<T, N>; + } // namespace fggl::ds #endif //FGGL_DS_PLACEHOLDER_HPP