96 lines
1.6 KiB
C++
96 lines
1.6 KiB
C++
// =============================================
|
|
// Aster: freelist.h
|
|
// Copyright (c) 2020-2025 Anish Bhobe
|
|
// =============================================
|
|
|
|
#pragma once
|
|
|
|
#include <optional>
|
|
|
|
struct FreeListNode
|
|
{
|
|
FreeListNode *m_Next;
|
|
};
|
|
|
|
template <typename T>
|
|
concept FreeListCapable = sizeof(T) >= sizeof(FreeListNode);
|
|
|
|
template <FreeListCapable T>
|
|
struct FreeList
|
|
{
|
|
using Value = T;
|
|
using Reference = T &;
|
|
using ConstReference = const T &;
|
|
using Pointer = T *;
|
|
|
|
FreeListNode *m_Top;
|
|
|
|
FreeList()
|
|
: m_Top{nullptr}
|
|
{
|
|
}
|
|
|
|
FreeList(FreeList &&other) noexcept
|
|
: m_Top{Take(other.m_Top)}
|
|
{
|
|
}
|
|
|
|
FreeList &
|
|
operator=(FreeList &&other) noexcept
|
|
{
|
|
if (this == &other)
|
|
return *this;
|
|
m_Top = Take(other.m_Top);
|
|
return *this;
|
|
}
|
|
|
|
DISALLOW_COPY_AND_ASSIGN(FreeList);
|
|
|
|
~FreeList()
|
|
{
|
|
m_Top = nullptr;
|
|
}
|
|
|
|
[[nodiscard]] bool
|
|
Empty() const
|
|
{
|
|
return !m_Top;
|
|
}
|
|
|
|
[[nodiscard]] Reference
|
|
Pop()
|
|
{
|
|
assert(m_Top);
|
|
Reference ref = *reinterpret_cast<Pointer>(m_Top);
|
|
m_Top = m_Top->m_Next;
|
|
return ref;
|
|
}
|
|
|
|
void
|
|
Push(Reference ref)
|
|
{
|
|
auto next = reinterpret_cast<FreeListNode *>(&ref);
|
|
next->m_Next = m_Top;
|
|
m_Top = next;
|
|
}
|
|
|
|
[[nodiscard]] ConstReference
|
|
Peek() const
|
|
{
|
|
assert(m_Top);
|
|
return *m_Top;
|
|
}
|
|
|
|
[[nodiscard]] Reference
|
|
Peek()
|
|
{
|
|
assert(m_Top);
|
|
return *m_Top;
|
|
}
|
|
|
|
void
|
|
Clear()
|
|
{
|
|
m_Top = nullptr;
|
|
}
|
|
}; |