NeoN
A framework for CFD software
Loading...
Searching...
No Matches
allocator.hpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2025 - 2026 NeoN authors
2//
3// SPDX-License-Identifier: MIT
4
5#pragma once
6
7#include "NeoN/core/error.hpp"
8
9#include <memory>
10
11
12namespace NeoN
13{
14
15
16enum class MemorySpace
17{
18 CPU,
19 GPU
20};
21
22
24{
25
26protected:
27
28 // TODO check if enforcing via Ctor is an option
30
31public:
32
35
37 virtual void* alloc(size_t size) = 0;
38
40 virtual void* realloc(void* ptr, size_t size) = 0;
41
43 virtual void free(void* ptr) = 0;
44
45 virtual ~AllocatorStrategy() {}
46};
47
48
50{
51
52 std::unique_ptr<AllocatorStrategy> strategy {};
53
54public:
55
56 void setStrategy(std::unique_ptr<AllocatorStrategy> strategyIn)
57 {
58 strategy = std::move(strategyIn);
59 }
60
62 template<typename T>
63 T* alloc(size_t elements) const
64 {
65 if (!strategy)
66 {
67 NF_ERROR_EXIT("No allocator set");
68 }
69 return reinterpret_cast<T*>(strategy->alloc(sizeof(T) * elements));
70 }
71
73 template<typename T>
74 T* realloc(void* ptr, size_t elements) const
75 {
76 if (!strategy)
77 {
78 NF_ERROR_EXIT("No allocator set");
79 }
80 return reinterpret_cast<T*>(strategy->realloc(ptr, sizeof(T) * elements));
81 }
82
83 void free(void* ptr) const
84 {
85 if (!strategy)
86 {
87 NF_ERROR_EXIT("No allocator set");
88 }
89 return strategy->free(ptr);
90 }
91};
92
93
94}
void free(void *ptr) const
Definition allocator.hpp:83
T * alloc(size_t elements) const
allocate a space for n elements of type T
Definition allocator.hpp:63
T * realloc(void *ptr, size_t elements) const
reallocate a space for n elements of type T
Definition allocator.hpp:74
void setStrategy(std::unique_ptr< AllocatorStrategy > strategyIn)
Definition allocator.hpp:56
virtual void * alloc(size_t size)=0
allocate a block of size bytes
void setMemSpace(MemorySpace memSpace)
set tag controlling where allocation happens
Definition allocator.hpp:34
virtual void * realloc(void *ptr, size_t size)=0
reallocate a block of size bytes
virtual void free(void *ptr)=0
free a block of size bytes
#define NF_ERROR_EXIT(message)
Macro for printing an error message and aborting the program.
Definition error.hpp:90
Integer types used throughout NeoN.
Definition array.hpp:18
MemorySpace
Definition allocator.hpp:17