Skip to content

Commit

Permalink
Flat Pool working on Windows
Browse files Browse the repository at this point in the history
  • Loading branch information
jatinchowdhury18 committed Dec 4, 2024
1 parent 2b2f623 commit cb1408d
Showing 1 changed file with 22 additions and 8 deletions.
Original file line number Diff line number Diff line change
@@ -1,12 +1,21 @@
#pragma once

#if ! JUCE_TEENSY

#if JUCE_WINDOWS
#define NOMINMAX
#define WIN32_LEAN_AND_MEAN 1
#include <windows.h>
#else
#include <sys/mman.h>
#endif

namespace chowdsp
{
/**
* A "flat" memory pool that reserves a ton of virtual memory,
* and then commits pages of that memory as needed.
*/
struct FlatMemoryPool
{
std::byte* current_pointer {};
Expand All @@ -15,8 +24,6 @@ struct FlatMemoryPool
std::byte* address_limit {};
size_t page_size {};

static constexpr size_t DEFAULT_VIRTUAL_MEMORY_RESERVE = 256 * 1024 * 1024;

void* allocate_bytes (size_t num_bytes, size_t alignment = 8)
{
auto* p = juce::snapPointerToAlignment (current_pointer, alignment);
Expand Down Expand Up @@ -80,12 +87,13 @@ struct FlatMemoryPool
return Frame { *this };
}

void init()
void init (size_t reserve_bytes = 1 << 28)
{
page_size = static_cast<size_t> (juce::SystemStats::getPageSize());
const auto reserve_padded = page_size * ((DEFAULT_VIRTUAL_MEMORY_RESERVE + page_size - 1) / page_size);
const auto reserve_padded = page_size * ((reserve_bytes + page_size - 1) / page_size);

#if JUCE_WINDOWS
memory_base = static_cast<std::byte*> (VirtualAlloc (nullptr, reserve_padded, MEM_RESERVE, PAGE_READWRITE));
#else
memory_base = static_cast<std::byte*> (mmap (nullptr, reserve_padded, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0));
jassert (memory_base != nullptr);
Expand All @@ -102,6 +110,7 @@ struct FlatMemoryPool
return;

#if JUCE_WINDOWS
VirtualFree (memory_base, 0, MEM_RELEASE);
#else
munmap (memory_base, static_cast<size_t> (address_limit - memory_base));
#endif
Expand All @@ -110,13 +119,18 @@ struct FlatMemoryPool
}

private:
#if JUCE_WINDOWS
#else
void extend_committed_pages (std::byte* end)
{
jassert (end - first_uncommitted_page >= 0);
first_uncommitted_page = juce::snapPointerToAlignment (current_pointer, page_size);
}
#if JUCE_WINDOWS
const auto size = juce::snapPointerToAlignment (end, page_size) - first_uncommitted_page;
VirtualAlloc(first_uncommitted_page, static_cast<size_t> (size), MEM_COMMIT, PAGE_READWRITE);
first_uncommitted_page += size;
#else
first_uncommitted_page = juce::snapPointerToAlignment (end, page_size);
#endif
}
};
} // namespace chowdsp

#endif

0 comments on commit cb1408d

Please sign in to comment.