From 3f82be9bc8588c1dc64b34eb511a372160f74ea8 Mon Sep 17 00:00:00 2001 From: Joseph Walton-Rivers <joseph@walton-rivers.uk> Date: Sat, 23 Jul 2022 16:18:33 +0100 Subject: [PATCH] fake a slotmap for API purposes --- include/fggl/ds/placeholder.hpp | 47 +++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/include/fggl/ds/placeholder.hpp b/include/fggl/ds/placeholder.hpp index e1cdfdc..ab9d9f7 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 -- GitLab