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"
9
10#include <memory>
11
12
13namespace NeoN
14{
15
16
17enum class MemorySpace
18{
21};
22
23
25{
26
27protected:
28
29 // TODO check if enforcing via Ctor is an option
31
32public:
33
35 void setMemSpace(MemorySpace memSpace) { memSpace_ = memSpace; }
36
38 virtual void* alloc(sizeType size) = 0;
39
41 virtual void* realloc(void* ptr, sizeType size) = 0;
42
44 virtual void free(void* ptr) = 0;
45
46 virtual ~AllocatorStrategy() {}
47};
48
49
51{
52
53 std::unique_ptr<AllocatorStrategy> strategy {};
54
55public:
56
57 void setStrategy(std::unique_ptr<AllocatorStrategy> strategyIn)
58 {
59 strategy = std::move(strategyIn);
60 }
61
63 template<typename T>
64 T* alloc(sizeType elements) const
65 {
66 if (!strategy)
67 {
68 NF_ERROR_EXIT("No allocator set");
69 }
70 return reinterpret_cast<T*>(strategy->alloc(sizeof(T) * elements));
71 }
72
74 template<typename T>
75 T* realloc(void* ptr, sizeType elements) const
76 {
77 if (!strategy)
78 {
79 NF_ERROR_EXIT("No allocator set");
80 }
81 return reinterpret_cast<T*>(strategy->realloc(ptr, sizeof(T) * elements));
82 }
83
84 void free(void* ptr) const
85 {
86 if (!strategy)
87 {
88 NF_ERROR_EXIT("No allocator set");
89 }
90 return strategy->free(ptr);
91 }
92};
93
94
95}
T * realloc(void *ptr, sizeType elements) const
reallocate a space for n elements of type T
Definition allocator.hpp:75
void free(void *ptr) const
Definition allocator.hpp:84
void setStrategy(std::unique_ptr< AllocatorStrategy > strategyIn)
Definition allocator.hpp:57
T * alloc(sizeType elements) const
allocate a space for n elements of type T
Definition allocator.hpp:64
virtual void * alloc(sizeType size)=0
allocate a block of size bytes
virtual void * realloc(void *ptr, sizeType size)=0
reallocate a block of size bytes
void setMemSpace(MemorySpace memSpace)
set tag controlling where allocation happens
Definition allocator.hpp:35
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
std::size_t sizeType
Definition label.hpp:56
MemorySpace
Definition allocator.hpp:18