diff options
Diffstat (limited to 'include/fud_allocator.hpp')
-rw-r--r-- | include/fud_allocator.hpp | 46 |
1 files changed, 41 insertions, 5 deletions
diff --git a/include/fud_allocator.hpp b/include/fud_allocator.hpp index 9b90deb..95e1d5a 100644 --- a/include/fud_allocator.hpp +++ b/include/fud_allocator.hpp @@ -26,6 +26,12 @@ namespace fud { +/** \brief The default allocation function for globalFudAllocator. */ +extern std::byte* fudAlloc(size_t size); + +/** \brief The default deallocation function for globalFudAllocator. */ +extern void fudFree(std::byte* ptr); + class alignas(std::max_align_t) Allocator { public: virtual ~Allocator() = default; @@ -68,11 +74,41 @@ class NullAllocator : public Allocator { extern NullAllocator globalNullAllocator; -/** \brief The default allocation function for globalFudAllocator. */ -extern std::byte* fudAlloc(size_t size); - -/** \brief The default deallocation function for globalFudAllocator. */ -extern void fudFree(std::byte* ptr); +template <size_t Size> +class SimpleStackAllocator final : public Allocator { +private: + std::byte m_memory[Size]{}; + size_t m_allocated{0}; + +public: + virtual ~SimpleStackAllocator() override final = default; + + virtual Result<std::byte*, FudStatus> allocate(size_t bytes, size_t alignment = alignof(std::max_align_t)) override final { + using RetType = Result<std::byte*, FudStatus>; + static_cast<void>(alignment); + if (bytes > Size - m_allocated) { + return RetType::error(FudStatus::AllocFailure); + } + + auto* data = m_memory + m_allocated; + m_allocated += bytes; + + return RetType::okay(data); + } + + virtual void deallocate(std::byte* pointer, size_t bytes) override final + { + if (pointer + bytes != m_memory + m_allocated) { + m_allocated = Size; + return; + } + m_allocated -= bytes; + } + + virtual bool isEqual(const Allocator& rhs) const override final { + return &rhs == this; + } +}; } // namespace fud |