Skip to content

Buddy allocator #87

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -644,6 +644,7 @@ add_executable(${CRYMP_CLIENT_EXE} WIN32
Code/Launcher/MemoryPatch.cpp
Code/Launcher/MemoryPatch.h
Code/Launcher/Resources.h
Code/Library/BuddyAllocator.h
Code/Library/CPUID.cpp
Code/Library/CPUID.h
Code/Library/CrashLogger.cpp
Expand Down
63 changes: 63 additions & 0 deletions Code/Library/BuddyAllocator.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
#pragma once

#include <bit>
#include <bitset>
#include <cstddef>
#include <memory>

template<std::size_t ARENA_SIZE_BYTES>
class BuddyAllocator
{
static_assert(std::has_single_bit(ARENA_SIZE_BYTES)); // make sure ARENA_SIZE_BYTES is a power of two

static constexpr std::size_t SMALLEST_CHUNK_SIZE_BYTES = 16;

static constexpr std::size_t GetTreeOrder()
{
constexpr std::size_t maxChunkCount = ARENA_SIZE_BYTES / SMALLEST_CHUNK_SIZE_BYTES;

return (sizeof(std::size_t) * 8) - std::countl_zero(std::bit_ceil(maxChunkCount));
}

static constexpr std::size_t GetTreeSize()
{
std::size_t result = 0;
std::size_t multiplier = 1;
for (std::size_t order = GetTreeOrder(); order > 0; order--)
{
result += order * multiplier;
multiplier *= 2;
}

return result;
}

static constexpr std::size_t GetTreeUpperPosBound()
{
return 1 << GetTreeOrder();
}

std::unique_ptr<std::byte[]> m_arena = std::make_unique<std::byte[]>(ARENA_SIZE_BYTES);
std::bitset<GetTreeSize()> m_tree;

public:
void* Allocate(std::size_t bytes)
{
// TODO
return nullptr;
}

bool Deallocate(void* pointer)
{
std::byte* chunk = static_cast<std::byte*>(pointer);

if (chunk < m_arena.get() || chunk >= (m_arena.get() + ARENA_SIZE_BYTES))
{
return false;
}

// TODO

return true;
}
};