1 /**
2     Numem Heaps.
3     
4     Copyright:
5         Copyright © 2023-2025, Kitsunebi Games
6         Copyright © 2023-2025, Inochi2D Project
7     
8     License:   $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
9     Authors:   Luna Nielsen
10 */
11 module numem.heap;
12 import numem.core.hooks;
13 
14 /**
15     A heap represents a destination for placement new operations.
16     This allows classes to be instantiated into memory in developer
17     specified configurations.
18 */
19 abstract
20 class NuHeap {
21 @nogc:
22 
23     /** 
24         Allocates memory on the heap.
25         
26         Params:
27             bytes = The amount of bytes to allocate from the heap.
28         Returns: 
29             A pointer to the memory allocated on the heap.
30             $(D null) if operation failed.
31     */
32     abstract void* alloc(size_t bytes);
33 
34     /** 
35         Attempts to reallocate an existing memory allocation on the heap.
36 
37         Params:
38             allocation = The original allocation
39             bytes = The new size of the allocation, in bytes.
40         Returns:
41             A pointer to the memory allocated on the heap.
42             $(D null) if the operation failed. 
43     */
44     abstract void* realloc(void* allocation, size_t bytes);
45 
46     /** 
47         Frees memory from the heap.
48         Note: Only memory owned by the heap may be freed by it.
49 
50         Params:
51             allocation = The allocation to free.
52     */
53     abstract void free(void* allocation);
54 }
55 
56 /**
57     A heap which is a simple abstraction over nuAlloc, nuRealloc and nuFree.
58 */
59 class NuMallocHeap : NuHeap {
60 @nogc:
61 
62     /** 
63         Allocates memory on the heap.
64         
65         Params:
66             bytes = The amount of bytes to allocate from the heap.
67         Returns: 
68             A pointer to the memory allocated on the heap.
69             $(D null) if operation failed.
70     */
71     override
72     void* alloc(size_t bytes) {
73         return nu_malloc(bytes);
74     }
75 
76     /** 
77         Attempts to reallocate an existing memory allocation on the heap.
78 
79         Params:
80             allocation = The original allocation
81             bytes = The new size of the allocation, in bytes.
82         Returns:
83             A pointer to the memory allocated on the heap.
84             $(D null) if the operation failed. 
85     */
86     override
87     void* realloc(void* allocation, size_t bytes) {
88         return nu_realloc(allocation, bytes);
89     }
90 
91     /** 
92         Frees memory from the heap.
93 
94         Params:
95             allocation = The allocation to free.
96     */
97     override
98     void free(void* allocation) {
99         return nu_free(allocation);
100     }
101 }