CookMem 1.4.0
A C++ memory context / allocator
Loading...
Searching...
No Matches
mmaparena.h
1/*
2 * Copyright (c) 2018-2026 Heng Yuan
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16#ifndef COOK_MMAP_MEM_ARENA_H
17#define COOK_MMAP_MEM_ARENA_H
18
19#ifdef _WIN32
20#include <windows.h>
21#else // _WIN32
22#include <sys/mman.h>
23#endif // _WIN32
24
25#include "config.h"
26#include "arena.h"
27
28namespace cookmem
29{
30
31#ifdef _WIN32
40class MmapArena
41{
42public:
54 MmapArena (std::size_t minSize = DEFAULT_MIN_SEGMENT_SIZE, DWORD prot = PAGE_READWRITE, DWORD type = ( MEM_RESERVE | MEM_COMMIT ))
55 : m_minSize (minSize),
56 m_prot (prot),
57 m_type (type)
58 {
59 }
60
69 void*
70 getSegment(std::size_t& size)
71 {
72 if (size < m_minSize)
73 {
74 size = m_minSize;
75 }
76 return VirtualAlloc (nullptr, size, m_type, m_prot);
77 }
78
86 bool
87 freeSegment (void* ptr, std::size_t)
88 {
89 return VirtualFree (ptr, 0, MEM_RELEASE) == 0;
90 }
91
96 void
97 releaseAll ()
98 {
99 }
100
101private:
102 std::size_t m_minSize;
103 DWORD m_prot;
104 DWORD m_type;
105};
106#else // _WIN32
114class MmapArena
115{
116public:
129 : m_minSize (minSize),
130 m_prot (prot),
131 m_flag (flag)
132 {
133 }
134
143 void*
144 getSegment (std::size_t& size)
145 {
146 if (size < m_minSize)
147 {
148 size = m_minSize;
149 }
150 void* ptr = mmap(nullptr, size, m_prot, m_flag, -1, 0);
151 if (ptr == MAP_FAILED)
152 {
153 return nullptr;
154 }
155 return ptr;
156 }
157
167 bool
168 freeSegment (void* ptr, std::size_t size)
169 {
170 return munmap (ptr, size) != 0;
171 }
172
177 void
179 {
180 }
181
182private:
183 std::size_t m_minSize;
184 int m_prot;
185 int m_flag;
186};
187#endif // _WIN32
188
189} // namespace cookmem
190
191#endif // COOK_MMAP_MEM_ARENA_H
Definition allocator.h:39
void releaseAll()
Definition mmaparena.h:178
void * getSegment(std::size_t &size)
Definition mmaparena.h:144
bool freeSegment(void *ptr, std::size_t size)
Definition mmaparena.h:168
MmapArena(std::size_t minSize=DEFAULT_MIN_SEGMENT_SIZE, int prot=(PROT_READ|PROT_WRITE), int flag=(MAP_PRIVATE|MAP_ANONYMOUS))
Definition mmaparena.h:128
Definition allocator.h:29
const std::size_t DEFAULT_MIN_SEGMENT_SIZE
Definition config.h:52