diff --git a/modules/common/chowdsp_data_structures/Allocators/chowdsp_FlatMemoryPool.h b/modules/common/chowdsp_data_structures/Allocators/chowdsp_FlatMemoryPool.h index 14862d60..c40532b0 100644 --- a/modules/common/chowdsp_data_structures/Allocators/chowdsp_FlatMemoryPool.h +++ b/modules/common/chowdsp_data_structures/Allocators/chowdsp_FlatMemoryPool.h @@ -1,12 +1,21 @@ #pragma once +#if ! JUCE_TEENSY + #if JUCE_WINDOWS +#define NOMINMAX +#define WIN32_LEAN_AND_MEAN 1 +#include #else #include #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 {}; @@ -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); @@ -80,12 +87,13 @@ struct FlatMemoryPool return Frame { *this }; } - void init() + void init (size_t reserve_bytes = 1 << 28) { page_size = static_cast (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 (VirtualAlloc (nullptr, reserve_padded, MEM_RESERVE, PAGE_READWRITE)); #else memory_base = static_cast (mmap (nullptr, reserve_padded, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0)); jassert (memory_base != nullptr); @@ -102,6 +110,7 @@ struct FlatMemoryPool return; #if JUCE_WINDOWS + VirtualFree (memory_base, 0, MEM_RELEASE); #else munmap (memory_base, static_cast (address_limit - memory_base)); #endif @@ -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), MEM_COMMIT, PAGE_READWRITE); + first_uncommitted_page += size; +#else + first_uncommitted_page = juce::snapPointerToAlignment (end, page_size); #endif + } }; } // namespace chowdsp + +#endif