Sane C++ Libraries
C++ Platform Abstraction Libraries
VirtualMemory.h
1// Copyright (c) Stefano Cristiano
2// SPDX-License-Identifier: MIT
3#pragma once
4#include "../Foundation/Memory.h" // FixedAllocator
5#include "../Foundation/PrimitiveTypes.h"
6namespace SC
7{
8struct SC_COMPILER_EXPORT VirtualMemory;
9struct SC_COMPILER_EXPORT VirtualAllocator;
10} // namespace SC
13
24{
27
28 void* memory = nullptr;
29
31 [[nodiscard]] static size_t roundUpToPageSize(size_t size);
32
34 [[nodiscard]] static size_t getSystemPageSize();
35
39 [[nodiscard]] bool reserve(size_t maxCapacityInBytes);
40
42 [[nodiscard]] bool release();
43
47 [[nodiscard]] bool commit(size_t newCapacityBytes);
48
50 [[nodiscard]] bool shrink(size_t newCapacityBytes);
51};
52
55{
56 VirtualAllocator(VirtualMemory& virtualMemory);
57
58 protected:
59 VirtualMemory& virtualMemory;
60
61 virtual void* allocateImpl(const void* owner, size_t numBytes, size_t alignment) override;
62 virtual void* reallocateImpl(void* memory, size_t numBytes) override;
63
64 void syncFixedAllocator();
65};
66
#define SC_COMPILER_EXPORT
Macro for symbol visibility in non-MSVC compilers.
Definition: Compiler.h:78
A MemoryAllocator implementation using a finite slice of memory.
Definition: Memory.h:108
A MemoryAllocator implementation based on a growable slice of VirtualMemory.
Definition: VirtualMemory.h:55
virtual void * allocateImpl(const void *owner, size_t numBytes, size_t alignment) override
Allocate virtual function to be reimplemented.
virtual void * reallocateImpl(void *memory, size_t numBytes) override
Re-allocate virtual function to be reimplemented.
Reserves a contiguous slice of virtual memory committing just a portion of it.
Definition: VirtualMemory.h:24
void * memory
Pointer to start of reserved memory.
Definition: VirtualMemory.h:28
bool shrink(size_t newCapacityBytes)
Reclaims all unused pages past newCapacityBytes (previously committed with VirtualMemory::commit)
size_t committedCapacityBytes
Current amount of committed memory.
Definition: VirtualMemory.h:26
bool commit(size_t newCapacityBytes)
Ensures at least newCapacityBytes to be committed / accessible from the large maxCapacityInBytes bloc...
static size_t roundUpToPageSize(size_t size)
Round up the passed in size to system memory page size.
bool reserve(size_t maxCapacityInBytes)
Reserves a large block of virtual memory of size maxCapacityInBytes.
size_t reservedCapacityBytes
Maximum amount of reserved memory that can be committed.
Definition: VirtualMemory.h:25
bool release()
Reclaims the entire virtual memory block (reserved with VirtualMemory::reserve)
static size_t getSystemPageSize()
Obtains system memory page size.